代码如下
#代码调用函数时使用了两个参数,a和b
#打印函数的功能,计算加法ADDING
#然后,将a+b,再把结果返回
#python将两个数相加,然后当函数结束时,返回a+b的值,再将a+b的结果赋给一个变量
def add(a,b):
print(f"adding{a}+{b}")
return a+b
def subtract(a,b):
print(f"subtracting{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
#1
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}")
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?")
结果输出
adding30+5
subtracting78-4
multiplying90*2
dividing100/2
Age: 35, Height: 74, Weight: 180, IQ: 50.0
Here is a puzzle.
dividing50.0/2
multiplying180*25.0
subtracting74-4500.0
adding35+-4426.0
That becomes: -4391.0 Can you do it by hand?
进程已结束,退出代码0
巩固练习
1. return功能
可以将放在=右边的东西作为函数的返回值
2. 怎么使用input()输入自己的值?
int(input())和float(input())
3. 24+34/100-1023
def add(a,b):
print(f"adding{a}+{b}")
return a+b
def subtract(a,b):
print(f"subtracting{a}-{b}")
return a-b
def divide(a,b):
print(f"dividing{a}/{b}")
return a/b
#1
a1 = add(24,34)
a2 = subtract(100,1023)
a3 = divide(a1,a2)
print(f"first step: {a1}, next step: {a2}, last step: {a3}")
print("Here is a puzzle.")
adding24+34
subtracting100-1023
dividing58/-923
first step: 58, next step: -923, last step: -0.0628385698808234
Here is a puzzle.
dividing-0.0628385698808234/2
subtracting-923--0.0314192849404117
adding58+-922.9685807150596
That becomes: -864.9685807150596 Can you do it by hand?
进程已结束,退出代码0