Skip to content

While else break Python

  • by

You can make many combinations of While else breaks in Python. Python that’s a combination of a while loop and an else statement, possibly involving a break statement.

  1. while Loop: A while loop in Python is used to repeatedly execute a block of code as long as a certain condition is true.
  2. else Statement with while: In Python, an else clause can be used with a while loop. The code in the else block will be executed after the loop completes, but only if the loop’s condition becomes False. In other words, the else block will not be executed if the loop was exited prematurely using a break statement.
  3. break Statement: The break statement is used to exit a loop prematurely. When encountered within a loop, it immediately terminates the loop’s execution and the program continues with the next statement after the loop.

While else break Python example

Here’s an example that combines a while loop with an else clause and a break statement in Python:

secret_number = 42
attempts = 0

while attempts < 3:
    guess = int(input("Guess the secret number: "))
    attempts += 1

    if guess == secret_number:
        print("Congratulations! You guessed the secret number.")
        break  # Exit the loop if the guess is correct
    else:
        print("Try again!")

else:
    print("Sorry, you've run out of attempts.")

Output:

While else break Python

n this example, the program asks the user to guess a secret number. The while loop continues as long as the user has attempted less than three times (attempts < 3). If the user guesses the correct number (guess == secret_number), the loop is exited using the break statement, and the “Congratulations” message is printed.

If the user doesn’t guess the correct number within three attempts, the else block associated with the while loop is executed, and the “Sorry, you’ve run out of attempts” message is printed.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading