Break and Continue statement in Python

break statement

the break statements terminate from the loop, if the controller encounters it the loop breaks, break statement should have the condition to break, if not the loop becomes an infinite loop, let’s see one example

pass2="kingdom2"
i=0
for x in pass2:
x=input(f"enter your passowrd {i} time:")
i=i+1
if pass2==x:
print("logged in successfully")
break
if i==6:
pass2="kingdom2"
i=0
for x in pass2:
x=input(f"enter your passowrd {i} time:")
i=i+1
if pass2==x:
print("logged in successfully")
break
if i==5:
print("tried too many times! BLOCKED")
break
enter your passowrd 0 time:fjghj
enter your passowrd 1 time:fdhdfh
enter your passowrd 2 time:kingdom2
logged in successfully

the above example is the best example for the break statement, the user needs to enter the password, the entry limit is 5 times if the user exceeds more than 5times, the program exits stating “tried too many times! BLOCKED”, if the user gives correct password the program exits stating “logged in successfully”

continue statement

continue statement is used to, move the controller to the next iteration by ignoring the other statements in the body, continue statement should have the condition to break, if not the loop becomes an infinite loop, let’s see one example

for num in [66, 147, 21, 69, 4, 88, 22]:
# Skipping the iteration when number is odd
if num%2 !=0:
continue
# This statement will be skipped for all oddnumbers
print(num)
66
4
88
22
Last updated on by vishal devxo