用Notepad++打下列的程式碼,
另存為ex3.py.
print ("I will now count my chickens:") print ("Hens", 25 + 30 / 6) print ("Roosters", 100 - 25 * 3 % 4) print ("Now I will count the eggs:") print (3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print ("Is it true that 3 + 2 < 5 - 7?") print (3 + 2 < 5 - 7) print ("What is 3 + 2?", 3 + 2) print ("What is 5 - 7?", 5 - 7) print ("Oh that's why it's False.") print ("How about some more.") print ("Is it greater?", 5 > -2) print ("Is it greater or equal?", 5 >= -2) print ("Is it less or equal?", 5 <= -2)
然後用Windows的cmd, 執行python打開它
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW C:\Users\Peter\Desktop\Python\LP3THW>python .\ex3.py I will now count my chickens: Hens 30.0 Roosters 97 Now I will count the eggs: 6.75 Is it true that 3 + 2 < 5 - 7? False What is 3 + 2? 5 What is 5 - 7? -2 Oh that's why it's False. How about some more. Is it greater? True Is it greater or equal? True Is it less or equal? False C:\Users\Peter\Desktop\Python\LP3THW>
完成.
順道一提, 運算順序就是先乘除後加減, 再比較大小
%號是求餘數的符號, 例如4%3, 就會是1
如果加上小數點, 就變成浮點數(float)運算.
運算結果如果是整數, 也會出現小數點.
接下來修改程式, 觀察有啥不同
比如
Line 4 加上小數點.0, 結果也會產生小數點.
Line 14 加上加減乘除求餘數, 了解其運算順序
3 + 2 * 4 / 2 % 3
= 3 + 8 / 2 % 3
= 3 + 4 % 3
= 3 + 1
= 4
Line 15 加上個 > 1, 就了解是先做運算, 再做 > 比較.
5 - 7 > 1
= -2 > 1
= False
print ("I will now count my chickens:") print ("Hens", 25 + 30 / 6) print ("Roosters", 100 - 25.0 * 3 % 4) print ("Now I will count the eggs:") print (3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print ("Is it true that 3 + 2 < 5 - 7?") print (3 + 2 < 5 - 7) print ("What is 3 + 2 * 4 / 2 % 3?", 3 + 2 * 4 / 2 % 3) print ("What is 5 - 7 > 1?", 5 - 7 > 1) print ("Oh that's why it's False.") print ("How about some more.") print ("Is it greater?", 5 > -2) print ("Is it greater or equal?", 5 >= -2) print ("Is it less or equal?", 5 <= -2)
結果
C:\Users\Peter\Desktop\Python\LP3THW>python .\ex3.py I will now count my chickens: Hens 30.0 Roosters 97.0 Now I will count the eggs: 6.75 Is it true that 3 + 2 < 5 - 7? False What is 3 + 2 * 4 / 2 % 3? 4.0 What is 5 - 7 > 1? False Oh that's why it's False. How about some more. Is it greater? True Is it greater or equal? True Is it less or equal? False C:\Users\Peter\Desktop\Python\LP3THW>
最初發表 / 最後更新: 2018.07.25 / 2018.07.25
0 comments:
張貼留言