Python break statement

libertycodervice

libertycodervice

Posted on March 1, 2020

Python break statement

The Python break statement, like in C or the C++ programming language, breaks or closes a for loop or a while loop.

The break statement can be used to terminate a loop statement, i.e., False condition or loop condition has not yet been completed, will stop the execution loop.

The break statement can be used in a while and for loop.

If you are using nested loops, break statement to stop the execution of code gets very confusion, it stops the innermost loop.

Python language break statement syntax:
The syntax for the break statement is: (drum rolls)

    break

flow chart:

break statement

Example:

The example below creates two loops, both which are stopped using the break statement. In the first example we use strings, in the second example a plain variable counter var.

#!/usr/bin/python

for letter in 'Python': # first instance
   if letter == 'h':
      break
   print('current letter:', letter)

var = 10 # second instance
while var> 0:
   print('current variable values:', var)
   var = var -1
   if var == 5: # var is equal to 5 when the variable loop exits
      break

print("Good bye!")

The results of the above examples:

current letter: P
current letter: y
current letter: t
current variable values: 10
current variable values: 9
current variable values: 8
current variable values: 7
current variable values: 6
Good bye!
💖 💪 🙅 🚩
libertycodervice
libertycodervice

Posted on March 1, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Learning Python
javascript Learning Python

November 28, 2024

Calculate savings with Python!
beginners Calculate savings with Python!

November 26, 2024

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Beginners Guide for Classes
python Beginners Guide for Classes

November 20, 2024