How continue works in a loop
Hey there, young programmers! Today, we’re going to dive into the magical world of loops and learn about a special keyword called “continue” in Python. Have you ever wondered how you can make your loops skip certain parts of the code and move on to the next iteration? Well, that’s exactly what “continue” helps us with!
What is a Loop? Before we delve into “continue,” let’s quickly review what a loop is. A loop is like a magical spell that makes your computer do something over and over again. It’s super handy when you want to repeat a task without writing the same code over and over.
In Python, we have different types of loops, like the “for” loop and the “while” loop. But today, we’ll focus on the “for” loop.
Understanding “continue”: Imagine you’re counting sheep in a field, but suddenly you spot a colorful butterfly fluttering by. You don’t want to count that butterfly because you’re only interested in the sheep. So, you skip counting the butterfly and move on to the next sheep. That’s exactly what “continue” does in Python!
When Python encounters the “continue” keyword inside a loop, it says, “Hey, skip whatever comes next and go to the next iteration of the loop!”
Let’s see it in action with some code:
# Let's say we want to print only even numbers between 1 and 10
for num in range(1, 11):
if num % 2 != 0: # If the number is odd
continue # Skip this number and move to the next iteration
print(num) # Print the even number
Explanation of the code:
- We use the “for” loop to go through numbers from 1 to 10.
- Inside the loop, we use an “if” statement to check if the number is odd (not divisible by 2).
- If the number is odd, we encounter the “continue” keyword, which skips the current iteration and jumps to the next one.
- If the number is even, we print it out.
Practice Questions:
- Write a program to print all the letters in the word “PYTHON,” skipping the letter “Y” using the “continue” keyword.
- Create a program to print numbers from 1 to 20, but skip numbers divisible by 3.
- Write a program to print the first 10 multiples of 4, but skip multiples of 12.
Solutions: 1.
word = "PYTHON"
for letter in word:
if letter == 'Y':
continue
print(letter)
for num in range(1, 21):
if num % 3 == 0:
continue
print(num)
count = 0
for num in range(1, 100):
if num % 12 == 0:
continue
print(num)
count += 1
if count == 10:
break
Congratulations! You’ve mastered the art of using “continue” in loops. You now have a powerful tool to skip certain parts of your code and make your programs more efficient. Keep practicing and exploring, and soon you’ll become a Python wizard!