標籤:style 列印 控制流程 print integer pytho sed 包括 個數
在Python 中有三種控制流程語句——if、for 和while。 1.if語句
Number = 23Guess = int(input(‘Enter an integer : ‘))if Guess == Number: print(‘Congratulations, you guessed it.‘) print(‘(but you do not win any prizes!)‘)elif Guess < Number: print(‘No, it is a little higher than that‘)else: print(‘No, it is a little lower than that‘)print(‘Done‘)
輸出:Enter an integer : 50No, it is a little lower than thatDoneEnter an integer : 22No, it is a little higher than thatDoneEnter an integer : 23Congratulations, you guessed it.(but you do not win any prizes!)Doneelif事實上是把兩個相關聯的if else-if else語句結合為一個if-else-else語句,使程式更簡單,並且減少所需的縮排數量。2.while語句
number = 23Running = Truewhile Running: Guess = int(input("Enter an integer:")) if Guess == Number: print("Congratulations, you guessed it.") elif Guess < Number: print("No, it is a little higher.") else: print("No, it is a little lower.")else: print("the while loop is over.")print("Done")輸出:
Enter an integer : 50No, it is a little lower.Enter an integer : 22No, it is a little higher.Enter an integer : 23Congratulations, you guessed it.The while loop is over.Done
while 語句有一個可選的else 從句,他將始終被執行,除非迴圈永遠迴圈下去。3.for迴圈
for i in range(1,5): print(i)else: print("The for loop is over")輸出:1234The for loop is over 在這裡,提供兩個數,range返回一個序列的數,這個序列從第一個數開始到第二個數位置,range(1,5)給出序列[1,2,3,4]。預設range的步長為1。如果為range提供第三個數,那麼它將作為步長,例如,range(1,5,2)給出序列[1,3],步長為2。range的範圍不包括第二個數。 for i in range(1,5)等價於for i in [1,2,3,4],把序列的裡的每個數賦值給i,一次一個。這個程式中列印的是i的值。 else是可選的,如果包含else,他總在for迴圈結束後執行一次,除非遇到break語句。
Python基礎之控制語句