笨方法”学Python3,习题 21:函数可以返回某些东西
1、函数返回是什么 ?
2、如何运用函数返回 ?
一、基础代码
所写的代码:
def add(a, b):
print(f"ADDING {a} + {b}")
return a + b
def substract(a, b):
print(f"SUBSTRACTING {a} - {b}")
return a - b
def multiply(a, b):
print(F"MULTIPLYING {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 = substract(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, substract(height, multiply(weight, divide(iq, 2))))
print("That becomes: ", what, "Can you do it hand?")
---------------------------------------------------------------------------------------------------
应该看到的结果:
PS D:\代码> & D:/软件/python/python.exe d:/代码/ex21.py
Let's do some math with just functions!
ADDING 30 + 5
SUBSTRACTING 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
SUBSTRACTING 74 - 4500.0
ADDING 35 + -4426.0
That becomes: -4391.0 Can you do it hand?
二、巩固练习1、用 return 写代码
所写的代码:
def f(*args):
a, b, c, d = args
return a * b - c + d
a = int(input("a?"))
b = int(input("b?"))
c = int(input("c?"))
d = int(input("d?"))
q = f(a,b,c,d)
print("a * b - c + d = ",q)
---------------------------------------------------------------------------------------------------
应该看到的结果:
PS D:\代码> & D:/软件/python/python.exe d:/代码/ps.py
a?1
b?2
c?3
d?4
a * b - c + d = 3
理解:
① 先定义了有多个参数的函数f,函数内部先参数解包,再返回到a*b-c+d的值。
② 执行脚本时,分别输入了四次字符串,int函数将其转换为数值并分别赋值给了四个变量。
③ 调用函数,将四个变量abcd的值传递给参数abcd,函数内部返回到a*b-c+d的值,将值赋值给变量q。
④ 打印格式化的字符串。4、写一个简单的公式,用函数计算它
总结:
1、函数 return 可以返回到对应公式的值,调用函数后,打印出来的结果是 return 后的值
2、return 就像一个过程,执行后面的公式,只不过没打印,使用时直接加公式即可
3、函数内部可以调用函数,顺序是从内向外执行的
^ v ^,知乎此系列文章内容均会在微信公众号中同步更新,公众号:小民有个小旮旯