In Python, the break
statement is used to exit or terminate a loop prematurely. It is primarily used within for
and while
loops to stop the execution of the loop’s block of code and move on to the next section of the program.
Here’s an example to illustrate the usage of the break
statement in a while
loop:
count = 0
while count < 5:
print("Count:", count)
if count == 3:
break
count += 1
print("Loop ended")
Code language: Python (python)
Output:
Count: 0
Count: 1
Count: 2
Count: 3
Loop ended
Code language: Python (python)
In the above code, the while
loop is executed until the count
variable reaches a value of 3. When count
becomes 3, the break
statement is encountered, causing an immediate exit from the loop. Consequently, the program moves on to the statement after the loop, printing “Loop ended.”
The break
statement can also be used in a for
loop in a similar manner to prematurely terminate the loop.
How do you add a break in Python?
To add a break
statement in Python, you simply need to write the keyword break
at the point where you want to exit the loop. The break
statement should be placed within the loop’s block of code, where you want to stop the iteration and move on to the next section of the program.
Here’s an example that demonstrates how to add a break
statement in a while
loop:
while True:
user_input = input("Enter a number (or 'q' to quit): ")
if user_input == 'q':
break
number = int(user_input)
result = number * 2
print("The result is:", result)
Code language: Python (python)
In this code, the while
loop continues indefinitely until a user enters the letter ‘q’ as input. When the input matches ‘q’, the if
statement is executed, and the break
statement is encountered, causing an immediate exit from the loop.
Note that the condition True
is used for the while
loop, which ensures that the loop keeps running until the break
statement is encountered.
Read More;
- How to do Single Line for Loop in Python
- What is Len() in Python With Example
- What does V mean in Python?
- What is Async and Await in Python With Example
- For i in Range Python Example
- What is a decorator in Python With Example
- Can you do a for loop with a DataFrame in Python?
- What is ‘Self’ in Python With Example
- What is Keyword Argument in Python with Example?
- What is Inheritance With Examples in Python
- What is Token in Python With Example
- How to Use def in Python With Example