在這道習(xí)題中,我們將關(guān)注函數(shù)的返回值。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def add(a, b):
print(f"ADDING {a} + ")
return a + b
def subtract(a, b):
print(f"SUBTRACTING {a} - ")
return a - b
def multiply(a, b):
print(f"MULTIPLYING {a} * ")
return a * b
def divide(a, b):
print(f"DIVIDING {a} / ")
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 = add(age, subtract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it by hand?")
運(yùn)行結(jié)果如下:

ex21運(yùn)行結(jié)果
ex21中的程序邏輯是:
- 定義了四則運(yùn)算的4個(gè)函數(shù)。
- 依次調(diào)用4個(gè)函數(shù),計(jì)算出了
age、height、weight和iq,并打印。 - 最后以嵌套調(diào)用的方式計(jì)算了出了變量
what的值,并打印。
在這里,我們重點(diǎn)需要關(guān)注函數(shù)中的返回值是如何得到的?答案就在于Python中return的這個(gè)關(guān)鍵字。將函數(shù)的返回值寫在return后面,函數(shù)就擁有了返回值。
小結(jié)
- 定義函數(shù)的返回值。