练习21 源代码
#创建函数,return返回a+b的值
def add(a, b):
print(f"ADDING {a} + {b}")
return a + b
#创建函数,return返回a-b的值
def subtract(a, b):
print(f"SUBTRACTING {a} - {b}")
return a - b
#创建函数,return返回a*b的值
def multiply(a, b):
print(f"MULTIPLYING {a} * {b}")
return a * b
#创建函数,return返回a/b的值
def divide(a, b):
print(f"DIVIDING {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(f"Age:{age}, Height: {height}, Weight: {weight}, IQ: {iq}")
# A puzzle for the extra credit, type it in anyway.
print("Here is a puzzle.")
#变量what,返回各函数值
what = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "\nCan you do it by hand?")
输出结果
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.0
Here is a puzzle.
DIVIDING 50.0 / 2
MULTIPLYING 180 * 25.0
SUBTRACTING 74 - 4500.0
ADDING 35 + -4426.0
That becomes: -4391.0
Can you do it by hand?
知识点:
- return返回变量的值。可以返回到对应公式的值,调用函数后,打印出来的结果是 return 后的值。
- return 就像一个过程,执行后面的公式,只不过没打印,使用时直接加公式即可
- 函数内部可以调用函数,顺序是从内向外执行的
附加练习
- 如果你还不能真正理解 return 是干什么的,试着写几个你自己的函数,并且让它们返回一些值。你可以让它 return 任何东西,只要你把它们放在 = 右边即可。
输入:
def f(a,b,c):
return a * b + c
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
print("a * b + c =", f(a,b,c))
输出:
a: 1
b: 2
c: 3
a * b + c = 5
解析:
int函数将其转换为数值并分别赋值给了变量。
2. 写一个简单的公式,然后用同一种方式通过函数来计算它。
输入:
#求 360/4-3*(2+5)
def add(a,b):
print(f"ADDING {a} + {b}")
return a + b
def subtract(a,b):
print(f"SUBTRACTUNG {a} - {b}")
return a - b
def multiply(a,b):
print(f"MULTIPLY {a} * {b}")
return a * b
def divide(a,b):
print(f"DIVIDING {a} / {b}")
return a / b
what = subtract(divide(360,4),multiply(3,add(2,5)))
print("360/4-3*(2+5) = ", what)
输出:
DIVIDING 360 / 4
ADDING 2 + 5
MULTIPLY 3 * 7
SUBTRACTUNG 90.0 - 21
360/4-3*(2+5) = 69.0
常见问题
- **我如何使用 input() 来输入我自己的值?**还记得 int(input()) 吗?这样做的问题是你不能输入浮点数,所以试着用 float(input()) 来代替。
输入:
def f(a,b,c):
return a * b + c
a = float(input("a: "))
b = float(input("b: "))
c = float(input("c: "))
print("a * b + c =", f(a,b,c))
输出:
a: 1.5
b: 2.3
c: 0.9
a * b + c = 4.35
float()函数是指浮点数类型。
- “写一个公式”是什么意思? 先试试 24 + 34 / 100 - 1023 吧,变成使用函数来计算。然后自己想出一个类似的数学公式,要用变量让它看起来更像一个公式。
答案同附加练习4(书中)。