#!usr/bin/python
# -*-coding:utf-8-*-
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?")
运行结果如下:
$ 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?
$
加分习题
①如果你不是很确定 return 的功能,试着自己写几个函数出来,让它们返回一些值。你可以将任何可以放在 = 右边的东西作为一个函数的返回值。
def addcase(a,b,c):
print ("addcase = %d + %d + %d" % (a,b,c))
return a + b +c
addtest = addcase(10,10,10)
print ("addtest result: %d" % addtest)
②这个脚本的结尾是一个迷题。我将一个函数的返回值用作了另外一个函数的参数。我将它们链接到了一起,就跟写数学等式一样。这样可能有些难读,不过运行一下你就知道结果了。接下来,你需要试试看能不能用正常的方法实现和这个表达式一样的功能。
part_one = divide(iq,2)
part_two = multiply(weight,part_one)
part_three = subtract(height,part_two)
part_four = add(age,part_three)
print ("That becomes:",part_four,"Can you do it by hand?")
一旦你解决了这个迷题,试着修改一下函数里的某些部分,然后看会有什么样的结果。你可以有目的地修改它,让它输出另外一个值。
最后,颠倒过来做一次。写一个简单的等式,使用一样的函数来计算它。
这个习题可能会让你有些头大,不过还是慢慢来,把它当做一个游戏,解决这样的迷题正是编程的乐趣之一。后面你还会看到类似的小谜题。
常见问题回答
为什么 Python 会把函数或公式倒着打印出来?
其实不是倒着打印,而是自内而外打印。如果你把函数内容逐句看下去,你会发现这里的规律。试着搞清楚为什么说它是“自内而外”而不是“自下而上”。
怎样使用 raw_input() 输入自定义值?
记得 int(raw_input()) 吧?不过这样也有一个问题,那就是你无法输入浮点数,所以你可以试着使用 float(raw_input())。
你说的“写一个公式”是什么意思?
来个简单的例子吧: 24 + 34 / 100 - 1023 ——把它用函数的形式写出来。然后自己想一些数学式子,像公式一样用变量写出来。