這篇文章是閱讀Asabeneh的30 Days Of Python: Day 9 - Conditionals後的學習筆記與心得。
如果符合if
的條件判斷,就換執行區域中的指令,跟JavaScript(以下簡稱JS)差不多,但條件可以不用括弧()
,並且是用冒號:
與縮排(四個空白),做為符合條件後執行指令的區隔:
forecast = "sunny"
if forecase == "sunny":
print("Go hiking!")
# 'Go hiking!'
經過if
的判斷如果不符合條件,就會執行else
區域中的指令,還是跟JS差不多,但記得是用冒號及縮排:
forecast = "rainy"
if forecast == "sunny":
print("Go hiking!")
else:
print("Better stay home")
# 'Better stay home'
經過if
的判斷如果不符合條件,會再進入elif
中的條件判斷,跟JS的差別在else if
,變成了elif
:
forecast = "cloudy"
if forecast == "sunny":
print("Go hiking!")
elif forecast == "cloudy":
print("Bring an umbrella")
else:
print("Better stay home")
# 'Bring an umbrella'
上述提到的if...else,可以縮寫成code if condition else code
的形式,像是JS的三元運算式:
forecast = "cloudy"
print("Go hiking!") if forecast == "sunny" else print("Better stay home")
# 'Better stay home
if
條件式中可以再做一個if
條件式,更明確的說,要幾個都行,跟JS差不多:
input_string = input("Please enter a number among 1 to 100 step by 1: ")
input_value = int(input_string)
if input_value > 0:
if input_value % 2 == 0:
print("It is an even integer")
else:
print("It is an odd integer")
elif input_value == 0:
print("It is a 0")
else:
print("It is out of the rule")
可以透過結合and
運算符來避免巢狀結構:
input_string = input("Please enter a number among 1 to 100 step by 1: ")
input_value = int(input_string)
if input_value > 0 and input_value % 2 == 0:
print("It is an even integer")
elif input_value > 0 and input_value % 2 != 0:
print("It is an odd integer")
elif input_value == 0:
print("It is a 0")
else:
print("It is out of the rule")