用Notepad++打下列的程式碼,
另存為ex21.py. 我附上中文注釋方便好讀.
# -*- coding: UTF-8 -*- #定義函數叫add, 返回 a + b之值 def add (a, b): print (f"ADDING {a} + {b}") return a + b #定義函數叫subtract, 返回 a - b之值 def subtract (a, b): print (f"SUBTRACTING {a} - {b}") return a - b #定義函數叫multiply, 返回 a * b之值 def multiply (a, b): print (f"MULTIPLYING {a} * {b}") return a * b #定義函數叫divide, 返回 a / b之值 def divide (a, b): print (f"DIVIDE {a} / {b}") return a / b print ("Let's do some math with just functions!") #變量age, height, weight 和 iq. 他們調用函數add, subtract, multiply, divide並傳入其需要的變量. age = add (30, 5) height = subtract (78, 4) weight = multiply (90, 2) iq = divide (100, 2) #印出來age, height, weight 和 iq經過函數調用後的值. 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.") #這裡的運作方式是從內(iq,2), 一直往外(age)算 #然後iq = divide, divide函數需要兩個值, 一個就是50 (100/2), 另外一個就是Line 36所示:2 what = add (age, subtract (height, multiply (weight, divide (iq, 2)))) print ("That become: ", what, "Can you do it by hand?")
然後用Windows的cmd, 執行python打開它.
C:\Users\Peter\Desktop\Python\LP3THW>python ./ex21.py Let's do some math with just functions! ADDING 30 + 5 SUBTRACTING 78 - 4 MULTIPLYING 90 * 2 DIVIDE 100 / 2 Age: 35, Height: 74, Weight: 180, IQ: 50.0 Here is a puzzle. DIVIDE 50.0 / 2 MULTIPLYING 180 * 25.0 SUBTRACTING 74 - 4500.0 ADDING 35 + -4426.0 That become: -4391.0 Can you do it by hand? C:\Users\Peter\Desktop\Python\LP3THW>
完成
Line 37 算法主要是由內向外
所以整行表示age(35) + (height (74) - (weight (180) * (iq(50) / 2)))
= 35 + (74 - (180 * 25))
= 35 + (74 - 4500)
= 35 + (-4426)
= -4391
可以用print調用出來看看. print (">>>>", age, height, weight, iq)
最初發表 / 最後更新: 2018.08.24 / 2018.08.24
0 comments:
張貼留言