Python的控制語句有if、while、for、break、continue。
1. if語句
下面是一個猜數字遊戲例子:
# Filename: if.pynumber = 10guess = int(input("Enter a integer:"))if guess == number: print("Congratulations, you guessed it.")elif guess < number: print("No, it is a little higher than that")else: print("No, it is a little lower than that")
注意if語句結尾處包含一個冒號(:),所有控制語句結尾處都需要冒號。Python沒有switch語句,您可以用if...elif...else來完成相同功能。
2. while語句
您可能發現上面猜數字遊戲,每次都要啟動一下才能猜,下面可以用while語句來控制直到你猜中才離開遊戲。
# Filename: while.pynumber = 10running = Truewhile running: guess = int(input("Enter a integer:")) if guess == number: print("Congratulations, you guessed it.") running = False elif guess < number: print("No, it is a little higher than that") else: print("No, it is a little lower than that")else: print("The game is over.")
其實與while相對的else是多餘的,與直接把它的語句放在在while語句塊後面的效果相同。
3. for語句
# Filename: for.pyfor i in range(1, 5): print(i)else: print("The for loop is over.")
輸出結果為:
1
2
3
4
The for loop is over.
4. break語句
# Filename: break.pywhile True: s = input("Enter something:") if s == "quit": break print("Length of the string is", len(s))print("Done")
5. continue語句
# Filename: continue.pywhile True: s = input("Enter something:") if s == "quit": break if len(s) < 3: continue print("Input is of sufficient length")