Learn ptyon the Hrad Way

exercise 21

2018-01-02  本文已影响0人  不娶名字
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


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?")

练习

  1. 如果你不是很确定return的功能,尝试自己写几个函数出来,让它们返回一些值。你可以将任何可以放在=右边的东西作为一个函数的返回值。
  2. 这个脚本的结尾是一个迷题。我将一个函数的返回值用作了另外一个函数的参数。我将它们连接一起,就像写数学等式一样。这样可能有些难懂,不过运行一下你就知道结果了。你可以试试看能不能用正常的方法实现和这个表达式一样的功能。
  3. 一旦你解决了这个迷题,试着修改一下函数里的某些部分,然后看会有什么样的结果。你可以有目的地修改它,让它输出另外一个值。
  4. 颠倒过来再做一次。写一个简单的等式,使用相同的函数来计算它。

答案

这个计算是从里到外的

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


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?")
# 这是练习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}")
上一篇下一篇

猜你喜欢

热点阅读