Using Loops and Iteration
In this article, you’ll learn about loops, which allow you to repeat processing in Python.
Using the for Statement
By using a for statement, you can execute a process as many times as you like.
for variable in iterable:
process
The for statement is often used together with lists
(see the previous article about lists),
and a common pattern is to process each value in a list one by one.
member = ["Maruko", "Tama", "Maruo"]
for person in member:
print(person)
# Maruko
# Tama
# Maruo
When combined with the range() function,
you can generate a sequence of numbers and process them in order.
range(end) # Numbers from 0 to end - 1
range(start, end) # Numbers from start to end - 1
range(start, end, step) # Numbers from start to end - 1, skipping by step
# Print numbers from 0 to 9
for n in range(10):
print(n)
# 0
# 1
# 2
# ...(omitted)
# 7
# 8
# 9
Using the continue Statement
By using continue, you can skip the current iteration of a loop.
When continue is executed, the remaining code in that iteration is skipped,
and the loop moves on to the next iteration.
# Loop through numbers from 0 to 9
for n in range(10):
if n % 2 == 0:
continue # Skip even numbers
print(n)
# 1
# 3
# 5
# 7
# 9
Using the break Statement
By using break, you can stop a loop immediately.
When break is executed, the entire loop is terminated.
# Loop through numbers from 0 to 9
for n in range(10):
if n == 5:
break # Stop the loop when n is 5
print(n)
# 0
# 1
# 2
# 3
# 4 <- The loop ends here
Using the while Statement
The while statement is another commonly used loop structure.
Make sure to understand this one as well.
while condition:
process
Here is a concrete example:
# Calculate the sum of numbers from 0 to 9
total = 0
n = 0
while n < 10:
total += n
n += 1
print(total) # 45
Just like the for statement,
while can also be used together with continue and break.
However, be careful:
if you make a mistake in the loop condition, you may end up with an infinite loop.
What’s Next?
Thank you for reading!
In the next article, we’ll learn about functions.
The next title will be:
“Getting Started with Python (Part 7): Using Functions”
Stay tuned! 🚀
Top comments (0)