Python break Statement (With Examples)

Python break statement: Here, we are going to learn about the break statement in Python with examples. By IncludeHelp Last updated : December 18, 2023

Python break statement

Like other programming languages, in Python, break statement is used to terminate the loop's execution. It terminates the loop's execution and transfers the control to the statement written after the loop.

If there is a loop inside another loop (nested loop), and break statement is used within the inner loop – it breaks the statement of the inner loop and transfers the control to the next statement written after the inner loop. Similarly, if break statement is used in the scope of the outer loop – it breaks the execution of the outer loop and transfers the control to the next statement written after the outer loop.

Syntax of the Python break statement

Below is the syntax of the break statement:

break

# Use within the condition (when required)
if condition:
    break

Python break Statement: Examples

To understand the use of the break statement, practice these examples.

Example 1

Here, we are printing the serious of numbers from 1 to 10 and terminating the loop if counter’s value is equal to 7.

# python example of break statement

counter = 1

# loop for 1 to 10
# terminate if counter == 7

while counter<=10:
	if counter == 7:
		break
	print(counter)
	counter += 1

print("outside of the loop")

Output

1
2
3
4
5
6
outside of the loop

Example 2

Here, we are printing the characters of a string and terminating the printing of the characters if the character is not an alphabet.

# python example of break statement

string = "IncludeHelp.Com"

# terminate the loop if 
# any character is not an alphabet 

for ch in string:
    if not((ch>='A' and ch<='Z') or (ch>='a' and ch<='z')):
        break
    print(ch)

print("outside of the loop")    

Output

I
n
c
l
u
d
e
H
e
l
p
outside of the loop

Example 3

Here, we have two loops, outer loop is "while True:" which is handling the multiple inputs and inner loop is using to print the table of given number – as input is 0 – inner loop will be terminated.

# python example of break statement

count = 1
num = 0
choice = 0

while True:
    # input the number 
    num = int(input("Enter a number: "))
    
    # break if num is 0
    if num==0:
        break   # terminates inner loop
    
    # print the table 
    count = 1
    while count<=10:
        print(num*count)
        count += 1

    # input choice
    choice = int(input("press 1 to continue..."))
    if choice != 1:
        break   # terminates outer loop

print("bye bye!!!")

Output

Enter a number: 21
21 
42 
63 
84 
105
126
147
168
189
210
press 1 to continue...1
Enter a number: 23
23 
46 
69 
92 
115
138
161
184
207
230
press 1 to continue...0
bye bye!!!

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.