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?")
練習(xí)
- 如果你不是很確定return的功能,嘗試自己寫幾個(gè)函數(shù)出來辣往,讓它們返回一些值兔院。你可以將任何可以放在=右邊的東西作為一個(gè)函數(shù)的返回值。
- 這個(gè)腳本的結(jié)尾是一個(gè)迷題站削。我將一個(gè)函數(shù)的返回值用作了另外一個(gè)函數(shù)的參數(shù)坊萝。我將它們連接一起,就像寫數(shù)學(xué)等式一樣。這樣可能有些難懂屹堰,不過運(yùn)行一下你就知道結(jié)果了肛冶。你可以試試看能不能用正常的方法實(shí)現(xiàn)和這個(gè)表達(dá)式一樣的功能街氢。
- 一旦你解決了這個(gè)迷題扯键,試著修改一下函數(shù)里的某些部分,然后看會(huì)有什么樣的結(jié)果珊肃。你可以有目的地修改它荣刑,讓它輸出另外一個(gè)值。
- 顛倒過來再做一次伦乔。寫一個(gè)簡單的等式厉亏,使用相同的函數(shù)來計(jì)算它。
答案
這個(gè)計(jì)算是從里到外的
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.")
first = divide(iq, 2)
second = multiply(weight, first)
third = subtract(height, second)
what = add(age, third)
print("That becomes: ", what, "Can you do it by hand?")
# 這是練習(xí)3的答案
practice = subtract(age, divide(height, divide(weight, add(iq, 2))))
print(practice)
公式:7-(5/(4+3*(2+1)))
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
return a / b
number = subtract(7, add(4, multiply(3, add(2, 1))))
print(f"the answer is {number}")