你已經(jīng)學(xué)過使用 = 給變量命名,以及將變量定義為某個(gè)數(shù)字或者字符串。接下來我們將讓你見證更多奇跡。我們要演示給你的是如何使用 = 以及一個(gè)新的 Python 詞匯return 來將變量設(shè)置為“一個(gè)函數(shù)的值”。有一點(diǎn)你需要及其注意,不過我們暫且不講,先撰寫下面的腳本吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | def add(a, b):
print "ADDING %d + %d" % (a, b)
return a + b
def subtract(a, b):
print "SUBTRACTING %d - %d" % (a, b)
return a - b
def multiply(a, b):
print "MULTIPLYING %d * %d" % (a, b)
return a * b
def divide(a, b):
print "DIVIDING %d / %d" % (a, b)
return a / b
print "Let's do some math with just functions!"
age = add(30, 5)
height = subtract(78, 4)
weight = multiply(90, 2)
iq = divide(100, 2)
print "Age: %d, Height: %d, Weight: %d, IQ: %d" % (age, height, weight, iq)
# A puzzle for the extra credit, type it in anyway.
print "Here is a puzzle."
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print "That becomes: ", what, "Can you do it by hand?"
|
現(xiàn)在我們創(chuàng)建了我們自己的加減乘除數(shù)學(xué)函數(shù): add, subtract, multiply, 以及 divide。重要的是函數(shù)的最后一行,例如 add 的最后一行是 return a + b,它實(shí)現(xiàn)的功能是這樣的:
和本書里的很多其他東西一樣,你要慢慢消化這些內(nèi)容,一步一步執(zhí)行下去,追蹤一下究竟發(fā)生了什么。為了幫助你理解,本節(jié)的加分習(xí)題將讓你解決一個(gè)迷題,并且讓你學(xué)到點(diǎn)比較酷的東西。
$ python ex21.py
Let's do some math with just functions!
ADDING 30 + 5
SUBTRACTING 78 - 4
MULTIPLYING 90 * 2
DIVIDING 100 / 2
Age: 35, Height: 74, Weight: 180, IQ: 50
Here is a puzzle.
DIVIDING 50 / 2
MULTIPLYING 180 * 25
SUBTRACTING 74 - 4500
ADDING 35 + -4426
That becomes: -4391 Can you do it by hand?
$
這個(gè)習(xí)題可能會(huì)讓你有些頭大,不過還是慢慢來,把它當(dāng)做一個(gè)游戲,解決這樣的迷題正是編程的樂趣之一。后面你還會(huì)看到類似的小謎題。