Python break statement

0 0
Read Time:1 Minute, 36 Second

Imagine you’re playing a game where you have to guess a number. You keep guessing until you get it right. Now, let’s say you want to stop playing once you’ve guessed the number correctly. This is where the break statement in Python comes in handy.

Here’s a simple explanation:

  1. Guessing Game: Think of a guessing game where you have to guess a number between 1 and 100.
  2. Looping: You use a loop to keep asking for guesses until you get the right one.
  3. Break Out: When you finally guess the correct number, you want to stop playing. This is where break comes in.
    • The break statement in Python is like a big red button that says “Stop!”. When Python sees this break, it immediately stops the loop it’s in and moves on to the next line of code after the loop.
    • So, when you guess the correct number, you use break to jump out of the guessing loop and stop playing the game.

Here’s a simple example in Python code:

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 == 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.")

In this code:

  • We use a while True loop, which means it will keep running indefinitely until we break out of it.
  • Inside the loop, we ask the user to guess a number.
  • If the guess is correct (guess == secret_number), we print a congratulatory message and then use break to exit the loop.
  • If the guess is too high or too low, we give the user a hint to adjust their guess accordingly.

That’s the basic idea of how the break statement works in Python!

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