Python3簡明教程(四)—— 流程控制之分支
阿新 • • 發佈:2019-02-13
流程控制 bin tar chang 是否 lease ... 改變 print
我們通過 if-else
語句來做決定,來改變程序運行的流程。
if語句
語法如下:
if expression: do this
如果表達式 expression
的值為真(不為零的任何值都為真),程序將執行縮進後的內容。務必要使用正確的縮進,在表達式為真的情況將會執行縮進的所有行。
例如,檢查一個數是否小於100:
#!/usr/bin/env python3 number = int(input("Enter a number: ")) if number < 100: print("The number is less than 100")
真值檢測
檢測真值的優雅方式是這樣的:
if x: pass
不要像下面這樣做:
if x == True: pass
else語句
我們使用 else
語句在 if
語句未滿足的情況時工作。
例如,對上面程序的補充:
#!/usr/bin/env python3 number = int(input("Enter a number: ")) if number < 100: print("The number is less than 100") else: print("The number is greater than 100")
還有多個分支的情況
>>> x = int(input("Please enter an integer: ")) >>> if x < 0: ... x = 0 ... print(‘Negative changed to zero‘) ... elif x == 0: ... print(‘Zero‘) ... elif x == 1: ... print(‘Single‘) ... else: ... print(‘More‘)
請註意,elif 雖然是else if 的簡寫,但編寫程序時並不能把它們展開寫。
參考鏈接:https://www.shiyanlou.com/courses/596
Python3簡明教程(四)—— 流程控制之分支