Discover Python and Patterns (4): Loops

Published December 11, 2019
Advertisement

The previous game only allows one try: you have to restart it to propose another word. In this post, I introduce loops, and I use them to repeat the game until the player finds the magic word.

This post is part of the Discover Python and Patterns series

While statement

The while statement allows to repeat a block until a condition is met:

while True:
    word = input("Enter the magic word: ")
    if word == "please":
        print("This is correct, you win!")
    else:
        print("This is not correct, try again!")
print("Thank you for playing this game!")

The while statement has the following syntax:

while [condition]:
    [what to repeat]
[these lines are not repeated]

It repeats the sub-block as long as the condition evaluates as True. This condition works in the same way as in the if statement.

If you run this program, the game repeats forever, and the final message “Thank you…” is never displayed. To stop its execution in Spyder, close the console window. It is as expected since the condition in the while statement is always True.

To end the program when the player finds the magic word, we can use a variable that states if the game is over or not:

repeat = True
while repeat:
    word = input("Enter the magic word: ")
    if word == "please":
        print("This is correct, you win!")
        repeat = False
    else:
        print("This is not correct, try again!")
print("Thank you for playing this game!")

We initialize the variable repeat as True (line 1). Note that we can name this variable as we want, we don’t have to name it repeat, as long as the name is not already used. Then, we repeat as long as repeat is True (line 2). If the player finds the magic word (line 4), we print the winning message (line 5) and set repeat to False. In this case, the next time the while condition is evaluated, it is False, and the loop stops.

Break statement

The previous approach does not stop the loop immediately. It means that we still execute the lines following repeat = False, even if we want to stop the loop. We can get a better result with the break statement:

while True:
    word = input("Enter the magic word: ")
    if word == "please":
        print("This is correct, you win!")
        breakelse:
        print("This is not correct, try again!")
print("Thank you for playing this game!")

When the break statement is executed (line 5), the loop ends, and we go straight to line 8. Note that we no more need to introduce a variable to control the flow.

Continue statement

The continue statement... continue reading on https://learngameprog.com






0 likes 0 comments

Comments

Nobody has left a comment. You can be the first!
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!
Advertisement