Continue vs Pass loop control statement in Python [ Explained ]

continue vs pass in python

Summary of continue, pass, and break.

  • Break, continue, and pass are loop control statements
  • A break statement is used when we want to exit the loop before the usual time. When we run into a break statement inside a loop, the loop stops iterating immediately and the program continues with the next statement after the loop.
  • We use a continue statement when we want to skip the execution of the remaining code inside a loop for a specific iteration and proceed to the next iteration. 
  • Pass statement is used as a placeholder where you do not want any code to execute. 

Difference between continue and pass statement of python in a loop. [ continue vs pass ]

Both continue and pass are loop control statements. They both can be used within a while and for loop. Whenever a continue statement is encountered, we directly jump to the next iteration skipping any code that comes after the continue statement within the loop. Whereas a pass statement does nothing when executed. It is a placeholder where in the future you will write the code. In short, it’s an empty code block that will be filled later.

Let’s take an example to show continue vs pass in for loop at the code level. We will write code to print numbers in a list that are multiple of 3. The list “numbers” contains all the integers on which we want to check whether they are divisible by 3. We apply a for loop to traverse the list and check if it is not divisible by 3. If yes, a continue statement is encountered which jumps to the next iteration in the loop. Else, if the number is divisible by 3 we print the number is divisible by 3. 

numbers=[3,78,9,12,89,42,56,66,33]

for number in numbers:
    if number%3!=0:
        continue
    print(f'{number} is a multiple of 3')
Output
3 is a multiple of 3
78 is a multiple of 3
9 is a multiple of 3
12 is a multiple of 3
42 is a multiple of 3
66 is a multiple of 3
33 is a multiple of 3
Similarly, using while loop
numbers=[3,78,9,12,89,42,56,66,33]
index=0
while index < len(numbers):
    if numbers[index]%3!=0:
        index+=1
        continue
    print(f'{numbers[index]} is a multiple of 3')
    index+=1
Output
3 is a multiple of 3
78 is a multiple of 3
9 is a multiple of 3
12 is a multiple of 3
42 is a multiple of 3
66 is a multiple of 3
33 is a multiple of 3
Pass statement is used to do nothing. In the below example, we will convert all lowercase character inside a word “PythonCodeLab!!” to upper case and remove if any special character is present in the word. First we will loop over all characters in the word and check if a special character is present. If there is a special character we  get into an if block which has a pass statement which does nothing and move to the next line of code. If a special character is not present we convert lower case character to upper case and add it to the u_word variable. The pass statement doesn’t jump to the next iteration after getting encountered as in case of a continue statement. Pass statements make execution move to the next line of code from the block where it was mentioned.
import re
word='PythonCodeLab'
u_word=''
for character in word:
    if character in '!@#$%^&*()_+-<>;|?':
        pass
    else:
        u_word+=character.upper()
    
print(u_word)
Output
PYTHONCODELAB

What is the differences between using 'try except continue' and 'try except pass' in Python ?

The difference comes in execution of except block. When we use pass statement in except block we are catching the error but do nothing and move to execute the next line of code i.e. printing number. We can see that we get error at index 1 and 3  where  except block code is executed which has pass statement. The pass statement does nothing as execution jumps to next line i.e. printing number.  
numbers=[1,0,2,0,4,5,8,6,91,4]
for number in numbers:
    try: 
        output=0/number
    except Exception as e:
        pass

    print(number)

Output
1
0
2
0
4
5
8
6
91
4
The continue statement in the except block helps us to move to next iteration without executing next line of code. In the below code we are trying to divide 10 by numbers in the list. Whenever we get error, the execution goes to except block which has a print and continue statement. The print statement prints the error and continue statement move the code to next iteration. If you see the output, when we get error we only print the error else we print the division numbers and its value after division.
numbers=[1,0,2,0,4,5,8,6,91,4]
for number in numbers:
    try:
        output=10/number
    except Exception as e:
        print(f'Error : {e}')
        continue

    print(f'10/{number}={round(output,2)}')
Output
10/1=10.0
Error : division by zero
10/2=5.0
Error : division by zero
10/4=2.5
10/5=2.0
10/8=1.25
10/6=1.67
10/91=0.11
10/4=2.5

Disadvantages of continue, pass and break ?

Python provides tools for controlling the flow of the program using continue , pass and break. But they come with certain disadvantages

  1. The code becomes less readable when  we use continue, break, and pass statement very oftent. We always try to write more readable code in production.
  2. Use of these statement make the code complex. The code becomes more error prone and harder to debug and maintain the codebase increases.
  3. If continue statement not used properly 

FAQ

Q : Difference between continue, pass and break in python. [continue vs pass vs break]                                                                  OR

Q : What is the difference between break and continue in python?

Continue statement is used to jump to next iteration by skipping the code after detecting continue statement where as break statement is used to exit the loop when encountered. Pass statement is used as a placeholder for code block which will be written in future.

Q. Can break and continue be used together?

Yes, both the statement can be used together. Here is a code demo.

We have a list of dictionaries called task_list. Each dictionary contains a task and its priority. We will skip all the tasks with priority as medium and low by using the continue statement. Exit the loop when the priority is high and start coding that task.

task_list = [
    {"task": "Go to market", "priority": "low"},
    {"task": "Make call to Mangesh", "priority": "low"},
    {"task": "Read book", "priority": "medium"},
    {"task": "Repair Laptop", "priority": "high"}]

for tasks in task_list:
    if tasks["priority"] == "high":
        print(f"Handling high priority task: {tasks['task']}")
        break  
    elif tasks["priority"] == "low" or tasks["priority"] == "medium":
        print(f"Skipping low priority task: {tasks['task']}")
        continue
print(f"started working on {tasks['task']} tasks processed.")

Output

Skipping low priority task: Go to market
Skipping low priority task: Make call to Mangesh
Skipping low priority task: Read the book
Handling high-priority task: Repair Laptop
Working on Repair Laptop tasks processed.

Q : Is it good practice to use continue in Python?

Yes, it is good practice to use continue statement in Python but not very often because it makes the code complex and difficult to debug. Keeping a record of the flow of the code becomes difficult which increases the chances of errors.

We have also written a blog to solve EOF errors.

1 thought on “Continue vs Pass loop control statement in Python [ Explained ]”

  1. Pingback: Solve Typeerror: object of type datetime is not JSON serializable in python

Leave a Comment

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