Published 9月 09, 2018 by with 0 comment

習題30 - else和if




這次是學elif & else語句.
elif 是多條件判斷語句,
如果第一行的if語句布林表達式為真, 則運行程式碼.
如果為假, 則跳過, 到下一行elif, 繼續去判斷.

如果第一個的elif語句布林表達式為真,
則運行程式碼. 就不再繼續接下來的elif判斷語句.
如果第一個的elif語句布林表達式為假,
則跳過, 到下一行elif, 繼續去判斷.

如果if, elif 語句都為假.
則執行最後一行的else.

用Notepad++打下列的程式碼,
另存為ex30.py. 我附上中文注釋方便好讀.
people = 20
cars = 40
trucks = 15

# 如果(if)為真 (cars  (40) > people (20)), 則執行print("We should take the cars.")
if cars > people:
    print("We should take the cars.")
# 如果(if)為假, 則執行print("We should not take the cars.")
elif cars < people:
    print("We should not take the cars.")
# 如果(if & else)皆為假, 則執行print("We should not take the cars.")
else:
    print("We can't decide.")

if trucks > cars:
    print("That's too many trucks.")
elif trucks < cars:
    print("Maybe we could take the trucks.")
else:
    print("We still can't decide.")

if people > trucks:
    print("Alright, let's just take the trucks")
else:
    print ("Fine, let's stay home then")

然後用Windows的cmd, 執行python.
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW
C:\Users\Peter\Desktop\Python\LP3THW>python ex30.py
We should take the cars.
Maybe we could take the trucks.
Alright, let's just take the trucks

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

完成


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

0 comments:

張貼留言