Loops: for loops (Part 1)
Following our exploration of Conditional Statements, this article introduces another fundamental concept in programming: loops. We'll start with the for loop, which allows you to iterate over a sequence of elements.
📚 Prerequisites
A basic understanding of Python variables and data types, especially lists and strings.
🎯 Article Outline: What You'll Master
In this article, you will learn:
- ✅ What loops are and why they are useful.
- ✅ The syntax of the
forloop. - ✅ How to iterate over different types of sequences.
- ✅ How to use the
range()function withforloops.
🧠 Section 1: What are Loops?
Loops are a way to execute a block of code multiple times. They are essential for automating repetitive tasks and for working with collections of data.
💻 Section 2: The for Loop
The for loop in Python is used to iterate over a sequence (like a list, tuple, or string) or other iterable objects.
Syntax:
for item in sequence:
# code to be executed for each item
item: A variable that takes on the value of the current item in the sequence during each iteration.sequence: The collection of items to iterate over.
🛠️ Section 3: Iterating Over Different Sequences
Let's look at some examples of how to use for loops with different types of sequences.
Iterating over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Iterating over a string:
for letter in "Python":
print(letter)
🔬 Section 4: The range() Function
The range() function is often used with for loops to generate a sequence of numbers.
range(stop):
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
range(start, stop):
for i in range(2, 5):
print(i) # Output: 2, 3, 4
range(start, stop, step):
for i in range(0, 10, 2):
print(i) # Output: 0, 2, 4, 6, 8
💡 Conclusion & Key Takeaways
You've now learned the basics of the for loop, a powerful tool for iterating over sequences in Python.
Let's summarize the key takeaways:
- Loops: A way to execute a block of code multiple times.
forLoop: Iterates over a sequence of elements.range(): Generates a sequence of numbers, often used withforloops.
Challenge Yourself:
Write a script that uses a for loop to print the numbers from 1 to 10, and then prints "Blastoff!".
➡️ Next Steps
In the next article, we'll continue our exploration of loops with "Loops: for loops (Part 2)", where we'll cover nested loops and more advanced for loop patterns.
Happy coding!
Glossary (Python Terms)
- Loop: A control flow statement that allows code to be executed repeatedly.
- Iteration: A single execution of the code block inside a loop.
- Sequence: An ordered collection of items, such as a list, tuple, or string.