Home > Article > Backend Development > How to use break in python
This article mainly talks about the usage of the break statement in Python. It is often used when a certain condition is met and the current loop needs to be exited immediately (jump out of the loop). The break statement can be used in for loops and while in a loop statement. Simply put, the break statement will exit the loop immediately, and the loop code behind it will not be executed.
Usage of break statement
>>>x = 1 >>>while True: >>> x+=1 >>> print x
Assuming that the while condition is true, the execution code block will be executed. Because the condition is always true, the program will continue to be executed and enter an infinite loop until your computer crashes. So how to solve this problem? python breaks out of loop! At this time, you need to use the break statement to end or continue to jump out.
>>>x = 1 >>>while True: >>> x+=1 >>> print x >>> break 2
After adding the break statement at the end of the code, the program only runs once and then ends. This shows that the break statement will exit the loop immediately. You can also set another condition for it, and then execute the exit operation when the other condition is true. This is the break and if statement in the while loop that will be discussed below. You can also jump out of the for loop in python.
If break and if statements are used in while loops
braak statements can appear in the body of while or for loops, most often together with if statements. Also use the above example to illustrate:
>>>x = 1 >>>while True: >>> x+=1 >>> print x >>> if x >= 5: >>> break 2 3 4 5
Before the end, an additional condition is added. When x is greater than or equal to 5, the break statement will be executed. The break statement is nested in the if. Pay attention to the indentation problem to avoid program running errors.
The break statement in Python has many uses. Its usage in while and for statements is roughly the same. You can check other tutorials on the PHP Chinese website.
The above is the detailed content of How to use break in python. For more information, please follow other related articles on the PHP Chinese website!