Python control statements include if, while, for, break, and continue.
1. If statement
The following is an example of a guess digital game:
# 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")
Note that the if statement ends with a colon (:), and all control statements end with a colon. Python does not have a switch statement. You can use if... Elif... else to perform the same function.
2. While statement
You may find that you have to start a number game before you can guess it. You can use the while statement to control it until you guess it.
# 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.")
In fact, the else relative to the while statement is redundant, which is the same as placing its statement directly behind the while statement block.
3. For statement
# Filename: for.pyfor i in range(1, 5): print(i)else: print("The for loop is over.")
Output result:
1
2
3
4
The for loop is over.
4. Break statement
# Filename: break.pywhile True: s = input("Enter something:") if s == "quit": break print("Length of the string is", len(s))print("Done")5. Continue statement
# Filename: continue.pywhile True: s = input("Enter something:") if s == "quit": break if len(s) < 3: continue print("Input is of sufficient length")