Python continue statement

0 0
Read Time:1 Minute, 49 Second

Let’s continue with our guessing game example to explain the continue statement.

Imagine you’re playing the same guessing game, but this time, you want to give a special message when the player makes an invalid guess, like guessing a number outside the allowed range.

Here’s how the continue statement fits in:

  1. Validating Guesses: Before checking if the guess is correct, you want to make sure it’s a valid guess within the range.
  2. Skip Ahead: When the guess is invalid, you don’t want to process it further. Instead, you want to skip to the next iteration of the loop.
    • The continue statement in Python is like a magic wand that says “Skip this one!”. When Python sees continue, it jumps back to the start of the loop for the next iteration, ignoring the rest of the code inside the loop for the current iteration.
    • So, when the guess is invalid, you use continue to skip the rest of the loop code and start the next iteration.

Here’s how you might use continue in our guessing game:

import random

# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

# Start the guessing game
while True:
    guess = int(input("Guess the number (between 1 and 100): "))

    if guess < 1 or guess > 100:
        print("Please guess a number between 1 and 100.")
        continue  # Skip the rest of the loop code and start the next iteration

    if guess == secret_number:
        print("Congratulations! You guessed the correct number.")
        break  # Stop the loop because the correct number was guessed
    elif guess < secret_number:
        print("Try higher.")
    else:
        print("Try lower.")

Save to grepper

In this code:

  • After getting the user’s guess, we check if it’s outside the allowed range using the condition guess < 1 or guess > 100.
  • If it’s outside the range, we print a message and then use continue to skip the rest of the loop code and start the next iteration (i.e., asking for another guess).
  • If the guess is within the range and not correct, we continue with the normal flow of the game.

That’s how the continue statement helps you manage the flow of your code in Python!

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %