Published 7月 27, 2018 by with 0 comment

習題5 - 更多的變量和打印




用Notepad++打下列的程式碼,
另存為ex5.py.
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'

print (f"Let's talk about {my_name}.")
print (f"He's {my_height} inches tall.")
print (f"He is {my_weight} pounds heavy.")
print ("Actually that's not too heavy.")
print (f"He's got {my_eyes} eyes and {my_hair} hair.")
print (f"His teeth are usually {my_teeth} depending on the coffee.")

#this line is tricky, try to get it exactly right
total = my_age + my_height + my_weight
print (f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")

然後用Windows的cmd, 執行python打開它.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW

C:\Users\Peter\Desktop\Python\LP3THW>python .\ex5.py
Let's talk about Zed A. Shaw.
He's 74 inches tall.
He is 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.

C:\Users\Peter\Desktop\Python\LP3THW>

完成

然後, 修改Line 3, 把他改成cm (1 inch =2.54 cm)
修改Line 4, 把他改成kg (1 lbs =0.45 kg)
my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 * 2.54 # inches * 2.54 = cm
my_weight = 180 * 0.45 # lbs * 0.45 = kg
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'

print (f"Let's talk about {my_name}.")
print (f"He's {my_height} cm tall.")
print (f"He is {my_weight} kg heavy.")
print ("Actually that's not too heavy.")
print (f"He's got {my_eyes} eyes and {my_hair} hair.")
print (f"His teeth are usually {my_teeth} depending on the coffee.")

#this line is tricky, try to get it exactly right
total = my_age + my_height + my_weight
print (f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")

print (2.2 * 3)

結果,
C:\Users\Peter\Desktop\Python\LP3THW>python .\ex5.py
Let's talk about Zed A. Shaw.
He's 187.96 cm tall.
He is 81.0 kg heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 187.96, and 81.0 I get 303.96000000000004.
6.6000000000000005

C:\Users\Peter\Desktop\Python\LP3THW>
Line 3, 由原本的整數 (int)74, 變成浮點數(Float) 187.96.
Line 4, 由原本的整數 (int)180, 變成浮點數(Float) 81.0.
還發現Line 8, 有303.96000000000004, 查了一下google 發現這是python 浮點數精度問題.
可以看到line 9, (2.2 * 3) 結果顯示6.6000000000000005, 也是相同浮點數精度問題.


最初發表 / 最後更新: 2018.07.27 / 2018.07.27

0 comments:

張貼留言