Example code demonstrating continue’s functionality
Hey there, young Python enthusiast! Today, we’re going to explore a super cool feature in Python called the continue
statement. Don’t worry if you haven’t heard about it before; I’m here to explain it to you in the simplest way possible!
What is continue
?
Imagine you’re in a race, and suddenly you encounter a hurdle. What do you do? You don’t just stop and give up, right? You keep going! That’s exactly what the continue
statement does in Python. It helps you keep going in your code, even if you encounter a little bump.
How Does continue
Work?
Let’s break it down with a simple example. Imagine we have a list of numbers, and we want to print only the even ones. But wait, there’s a catch: if we encounter an odd number, we don’t want to print it; we just want to skip it and move on to the next number.
Here’s how we can do it with Python and the ‘continue
‘ statement:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num % 2 != 0: # If the number is odd
continue # Skip this number and continue with the next one
print(num) # If the number is even, print it
In this code:
- We loop through each number in the
numbers
list. - If the number is odd (i.e., not divisible by 2), we use
continue
to skip it. - If the number is even, we print it.
Practice Questions:
- Loop through the numbers from 1 to 20. Print all numbers except the multiples of 3. Use the
continue
statement.
- Print all the vowels in the given word “hello” using a
for
loop and thecontinue
statement.
Practice Solutions:
- Here’s how you can solve the first question:
for num in range(1, 21):
if num % 3 == 0:
continue
print(num)
- And for the second question:
word = "hello"
for char in word:
if char not in "aeiou":
continue
print(char)
Remember, practice makes perfect! Keep experimenting with continue
and other Python features, and you’ll become a Python pro in no time! If you have any questions, feel free to ask. Happy coding! 🐍✨