if 判斷式是所有程式碼都需具備的基本語法。Python 的 if 後面接條件,條件不需使用 ()包含。每個條件最後需接 “:”,並使用Tab鍵內縮作為條件成立的執行區塊。
基本型
最簡單的基本型如下
if 條件 :
pass
example
price=eval(input('請輸入便當價格 : '))
if price>=100:
print('超級貴的')
print('天理何在')
結果:
如何輸入100元及以上,"超級貴的" 及 "天理何在" 都會被印出。
如果低於100,則什麼都不會列印。
if..else
這是屬於第二型,區分為二種結果,語法如下
if 條件:
pass
else:
pass
example
price=eval(input('請輸入便當價格'))
if price <100:
print("還吃的下去")
else:
print("超級貴的")
print("天理何在")
第三型
若有三種以上的可能,if..else則無法應付,需更改成如下
if 條件1:
pass
else:
if 條件2:
pass
else:
if 條件3:
pass
else:
pass
example
price=eval(input('請輸入便當價格'))
if price < 50:
print("便宜")
else:
if price < 70:
print("普通")
else:
if price < 100:
print("有點小貴")
else:
print("超級貴的")
print("天理何在")
第三型變型
第三型一直往內縮,實在有違人類的思考方式,並增加日後程式碼的維護,所以可以變型成如下

This is the type of content I always seek out online; truly informative and helpful.