Home > Backend Development > Python Tutorial > How to use break in python

How to use break in python

silencement
Release: 2019-07-10 13:16:18
Original
30408 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template