break

KeywordPython 2.0+Beginner

Exits the nearest enclosing for or while loop immediately

Quick Info

Documentation
Official Docs
Python Version
2.0+

Learn by Difficulty

Quick Example

python
# Find the first number divisible by 7
for i in range(1, 100):
    if i % 7 == 0:
        print(f"First multiple of 7: {i}")
        break

# Break out of a while loop
password = ["wrong", "wrong", "correct", "wrong"]
attempt = 0
while attempt < len(password):
    if password[attempt] == "correct":
        print(f"Access granted on attempt {attempt + 1}")
        break
    attempt += 1

break immediately exits the innermost loop. Code after break in the loop body is skipped.

Try in Playground

Tags

languagesyntaxcorecontrol-flowloop

Related Items