Python break and continue

Filed Under: Python

Today we will learn about Python break and continue statements. In previous post, we learnt about python while loop.

Python Break and Continue

Python break and continue statements are used only in loop. It helps to modify loop behaviour. Suppose you’re executing a loop, at one phase you need to terminate the loop or skip some statements then you need these statements.

Python break

This statement is used to break the loop. Suppose you’re printing odd numbers using while loop. But you don’t need to print numbers greater than 10. Then you can write the following python code.


number = 1 #Number is initially 1
 
while True : #This means the loop will continue infinite time
        print (number) #print the number
        number+=2 #calculate next odd number
 
        # Now give the breaking condition
        if number > 10:
                break;
                #Breaks the loop if number is greater than ten
                print (number) #This statement won't be executed

Python break example output
python break example

In the given example you will see that the statement(s) that are written after break, won’t be executed. So here, 11 will not be printed.

Python break statement can be used in for loop also. Suppose you are printing words from a list. If any words that matches with “exit” won’t be printed and the loop will terminate. The following python code illustrates the idea.


words = ["rain", "sun", "moon", "exit", "weather"]
 
for word in words:
        #checking for the breaking condition
        if word == "exit" :
                #if the condition is true, then break the loop
                break;
 
        #Otherwise, print the word
        print (word)

Python break for example
python break statement example with for loop

Python continue

Python continue statement is used to skip the statement of the loop and iterate to the next step. For example you’re printing number 1 to 10. You need to skip all statements at step 7. The following python code illustrates the scenario.


numbers = range(1,11)
'''
the range(a,b) function creates a list of number 1 to (b-1)
So, in this case it would generate
numbers from 1 to 10
'''
for number in numbers:
        #check the skipping condition
        if number == 7:
                #this statement will be executed
                print("7 is skipped")
                continue
                #this statement won't be executed
                print ("This won't be printed")
 
        #print the values
        #for example:
        #2 is double of 1
        print (number*2),
        print ("is double of"),
        print (number)

Python continue example output
python continue example code

Same thing you can do for while loop. Suppose, you are trying to print all the odd values from 1 to 10, then the python code which solves the problem would be:


numbers = [ 1, 2, 4, 3, 6, 5, 7, 10, 9 ]
pos = 0 #initial position is one
while pos < len(numbers):
        #checking skipping condition if number is divisible by two, it is even
        if numbers[pos] % 2 == 0 :
                #increment the position by one
                pos = pos + 1
                continue
        #print the odd number
        print (numbers[pos])
        #increment the position by one
        pos = pos + 1

Python continue example while loop
python continue while loop example

That’s all about python break and continue statement. Hope that you have learnt well. If you have any query about this topic, feel free to ask that in comment section.
#HappyCoding

Comments

  1. ghada says:

    weight = 0
    items = []
    for cargo_name, cargo_weight in manifest:
    print(“current weight: {}”.format(weight))
    if weight >= 100:
    print(” breaking from the loop now!”)
    break
    elif weight + cargo_weight > 100:
    print(” skipping {} ({})”.format(cargo_name, cargo_weight))
    continue
    else:
    print(” adding {} ({})”.format(cargo_name, cargo_weight))
    items.append(cargo_name)
    weight += cargo_weight

    print(“\nFinal Weight: {}”.format(weight))
    print(“Final Items: {}”.format(items))

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages