break in python

Previous
Next

break:

  • It is used to terminate the loop execution.
  • It can be used inside the loop only
  • It can terminate infinite loop also.
while True:
    print("Loop...")
    break
  • We cannot use break to terminate a block.
  • Block executes only once, hence no need to break explicitly
if True:
    print("Break...")
    break

We can break the loop with conditions using if block.

for i in range(10):
    if i==5:
        break
    print("i val :",i)

When break statement executes inside the inner loop, it terminates the flow of inner loop only and continue with the execution of Outer loop.

while True:
    print("Hi")
    while True:
        print("Hello")
        break

Break Outer and Inner loops:

while True:
    print("Hi")
    while True:
        print("Hello")
        break
    break

Output the code:

for i in range(5):
    for j in range(5):
        if i==j:
            break
        else:
            print(i,j)

Output the code:

for i in range(5):
    for j in range(5):
        if i==j:
            break
    print(i,j)
Previous
Next

Add Comment

Courses Enquiry Form