Python的控制语句有if、while、for、break、continue。
下面是一个猜数字游戏例子:
# Filename: if.py number = 10 guess = 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来完成相同功能。
您可能发现上面猜数字游戏,每次都要启动一下才能猜,下面可以用while语句来控制直到你猜中才退出游戏。
# Filename: while.py number = 10 running = True while 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语句块后面的效果相同。
# Filename: for.py for i in range(1, 5): print(i) else: print("The for loop is over.")
输出结果为:
1
2
3
4
The for loop is over.
# Filename: break.py while True: s = input("Enter something:") if s == "quit": break print("Length of the string is", len(s)) print("Done")
# Filename: continue.py while True: s = input("Enter something:") if s == "quit": break if len(s) < 3: continue print("Input is of sufficient length")