Home » Python continue Statement : A Tutorial

Python continue Statement : A Tutorial

Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription

The continue statement in Python is used to skip the current iteration of a loop and proceed with the next iteration. It works with both for and while loops.

When Python encounters the continue statement, it stops executing the remaining code in the current iteration and immediately starts the next iteration of the loop.

The continue statement is useful when you want to skip certain parts of the loop based on a condition, without breaking the loop entirely (unlike the break statement).

1. Basic Syntax of continue Statement

for item in sequence:
    if condition:
        continue  # Skip the current iteration
    # Rest of the loop code


while condition:
    if condition_to_skip:
        continue  # Skip the current iteration
    # Rest of the loop code

2. Using continue in a for Loop

Let’s start with a simple example of using the continue statement in a for loop to skip specific iterations.

Example: Using continue to Skip Even Numbers

# Example: Using continue to skip even numbers in a for loop
for num in range(1, 6):
    if num % 2 == 0:
        continue  # Skip even numbers
    print(num)

# Output:
# 1
# 3
# 5

In this example:

The continue statement skips the current iteration if the number is even (num % 2 == 0), so only odd numbers are printed.

3. Using continue in a while Loop

The continue statement can also be used in a while loop to skip the current iteration based on a condition.

Example: Using continue in a while Loop

# Example: Using continue in a while loop
i = 0

while i < 5:
    i += 1
    if i == 3:
        continue  # Skip when i equals 3
    print(i)

# Output:
# 1
# 2
# 4
# 5

In this example:

The continue statement is used to skip printing the value 3 by immediately proceeding to the next iteration when i == 3.

4. Using continue with User Input

You can use the continue statement to skip certain input values based on a condition.

Example: Skipping Negative Numbers from User Input

# Example: Using continue to skip negative numbers
for _ in range(5):
    number = int(input("Enter a number: "))
    if number < 0:
        print("Negative number, skipping...")
        continue  # Skip negative numbers
    print(f"You entered: {number}")

# Output (example input):
# Enter a number: -2
# Negative number, skipping...
# Enter a number: 4
# You entered: 4

In this example:

The loop skips the rest of the iteration if the user inputs a negative number, preventing it from being printed.

5. continue in Nested Loops

When used inside nested loops, the continue statement only affects the current loop (the loop in which it is called), not the outer loops.

Example: Using continue in Nested Loops

# Example: continue in nested loops
for i in range(3):  # Outer loop
    for j in range(3):  # Inner loop
        if j == 1:
            continue  # Skip the current iteration of the inner loop when j == 1
        print(f"i = {i}, j = {j}")

# Output:
# i = 0, j = 0
# i = 0, j = 2
# i = 1, j = 0
# i = 1, j = 2
# i = 2, j = 0
# i = 2, j = 2

In this example:

The continue statement only affects the inner loop when j == 1, skipping the rest of that iteration. The outer loop continues unaffected.

6. Skipping Items in a List

The continue statement can be used to skip specific items in a list based on a condition.

Example: Skipping Empty Strings in a List

# Example: Using continue to skip empty strings
names = ["Alice", "", "Bob", "", "Charlie"]

for name in names:
    if name == "":
        continue  # Skip empty strings
    print(f"Name: {name}")

# Output:
# Name: Alice
# Name: Bob
# Name: Charlie

In this example:

The continue statement is used to skip over any empty strings in the list, so only non-empty names are printed.

7. Using continue with else in Loops

In Python, you can combine the else clause with loops. The else block runs if the loop completes normally (i.e., without encountering a break statement). The continue statement does not affect the execution of the else block.

Example: continue with for-else

# Example: Using continue with for-else
numbers = [1, 2, 3, 4, 5]

for num in numbers:
    if num == 3:
        continue  # Skip number 3
    print(num)
else:
    print("Loop finished without a break.")

# Output:
# 1
# 2
# 4
# 5
# Loop finished without a break.

In this example:

The continue statement skips printing the number 3, but the loop completes normally, so the else block is executed.

8. Skipping Specific Letters in a String

You can use the continue statement to skip specific letters in a string, such as vowels or any other specified characters.

Example: Skipping Vowels in a String

# Example: Using continue to skip vowels in a string
text = "Python Programming"

for char in text:
    if char.lower() in "aeiou":
        continue  # Skip vowels
    print(char, end="")

# Output:
# Pythn Prgrmmng

In this example:

The loop skips vowels in the string text using the continue statement, printing only consonants.

9. Skipping Numbers Divisible by a Given Number

You can use the continue statement to skip numbers that meet specific conditions, such as being divisible by a given number.

Example: Skipping Numbers Divisible by 3

# Example: Using continue to skip numbers divisible by 3
for i in range(1, 11):
    if i % 3 == 0:
        continue  # Skip numbers divisible by 3
    print(i)

# Output:
# 1
# 2
# 4
# 5
# 7
# 8
# 10

In this example:

The continue statement skips numbers that are divisible by 3, so those numbers are not printed.

10. Skipping Divisors in a Number

You can use the continue statement to skip certain divisors in a range when checking for factors of a number.

Example: Skipping Specific Divisors of a Number

# Example: Skipping specific divisors
number = 12

for i in range(1, number + 1):
    if number % i != 0:
        continue  # Skip if i is not a divisor
    print(f"{i} is a divisor of {number}")

# Output:
# 1 is a divisor of 12
# 2 is a divisor of 12
# 3 is a divisor of 12
# 4 is a divisor of 12
# 6 is a divisor of 12
# 12 is a divisor of 12

In this example:

The continue statement skips numbers that are not divisors of 12, and only the divisors are printed.

11. Using continue in an Infinite Loop

The continue statement is also useful in infinite loops to skip certain iterations based on a condition.

Example: continue in an Infinite Loop

# Example: continue in an infinite loop
while True:
    user_input = input("Enter a number (or type 'exit' to quit): ")
    if user_input == "exit":
        break  # Exit the loop
    if not user_input.isdigit():
        print("Invalid input, please enter a number.")
        continue  # Skip to the next iteration if input is not a number
    print(f"You entered: {user_input}")

# Output:
# Enter a number (or type 'exit' to quit): abc
# Invalid input, please enter a number.
# Enter a number (or type 'exit' to quit): 5
# You entered: 5
# Enter a number (or type 'exit' to quit): exit

In this example:

The loop continues to prompt the user for input until they type ‘exit'. If the input is not a number, the continue statement skips the rest of the loop iteration and prompts the user again.

12. Practical Example: Skipping Non-Numeric Values in a List

You can use the continue statement to skip over non-numeric values in a list of mixed data types.

Example: Skipping Non-Numeric Values in a List

# Example: Skipping non-numeric values in a list
data = [10, "hello", 20, None, 30, "world", 40]

for item in data:
    if not isinstance(item, (int, float)):
        continue  # Skip non-numeric values
    print(f"Numeric value: {item}")

# Output:
# Numeric value: 10
# Numeric value: 20
# Numeric value: 30
# Numeric value: 40

In this example:

The loop skips any non-numeric values in the list (strings and None) and prints only the numeric values.

Summary

The continue statement is used to skip the rest of the current iteration and move to the next iteration of the loop.
It works with both for and while loops and is useful when you need to skip certain iterations based on a condition.
In nested loops, continue only affects the loop where it is called.
The continue statement can be used to skip specific items in sequences such as lists or strings.
It’s also useful in infinite loops and can help handle invalid user input or skip specific data points.

By mastering the continue statement, you can create more flexible and efficient loops that handle specific conditions without interrupting the entire loop’s execution.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More