Interview Questions, Answers and Tutorials

Definition and purpose of the continue statement

Definition and purpose of the continue statement

Hey there budding Pythonistas!

Today, we’re diving into one of the cool tools Python gives us: the “continue” statement. Now, don’t worry if you haven’t heard of it before. I’ll explain it to you just like I’m talking to a 10-year-old.

What is the “continue” statement?

Imagine you’re playing a game, and you encounter an obstacle. You don’t want to stop playing the game altogether, right? You just want to skip over that obstacle and keep going. Well, that’s what the “continue” statement does in Python!

Purpose of the “continue” statement:

  1. Skipping Over Stuff: Let’s say you’re going through a list of things to do, and you come across something you can’t do right now. Instead of stopping everything, you can use “continue” to skip that task and move on to the next one.
  2. Skipping Bad Data: Sometimes, when working with data, you might encounter something weird or bad. Instead of letting that mess up your program, you can just skip over it and continue doing what you need to do.

Now, let’s look at some examples!

Python Code Examples:

# Example 1: Skipping even numbers
for num in range(1, 11):
    if num % 2 == 0:  # Check if the number is even
        continue  # Skip this iteration
    print(num)  # Print only odd numbers

In this example, we’re printing only the odd numbers from 1 to 10. When we encounter an even number, we use “continue” to skip it and move on to the next number.

# Example 2: Skipping vowels in a word
word = "hello"
for letter in word:
    if letter in "aeiou":  # Check if the letter is a vowel
        continue  # Skip vowels
    print(letter)  # Print consonants

Here, we’re printing only the consonants in the word “hello” by skipping over the vowels.

Practice Questions:

  1. Print numbers from 1 to 20, skipping multiples of 3.
  2. Print each character of the word “banana” except ‘a’.

Solutions:

  1. Print numbers from 1 to 20, skipping multiples of 3:

for num in range(1, 21):
    if num % 3 == 0:
        continue
    print(num)

  1. Print each character of the word “banana” except ‘a’:

word = "banana"
for letter in word:
    if letter == 'a':
        continue
    print(letter)

Great job! You’re now a “continue” expert! Just remember, when you encounter something you want to skip in Python, just say “continue” and keep on coding! Keep practicing, and soon you’ll be a Python pro! 🐍💻