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.
while
Loop: Awhile
loop in Python is used to repeatedly execute a block of code as long as a certain condition is true.else
Statement withwhile
: In Python, anelse
clause can be used with awhile
loop. The code in theelse
block will be executed after the loop completes, but only if the loop’s condition becomesFalse
. In other words, theelse
block will not be executed if the loop was exited prematurely using abreak
statement.break
Statement: Thebreak
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:
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.