Using For Loops in Python
Master Python iteration with practical for loop fundamentals
This tutorial covers for loops in Python, also known as definite loops because we know exactly how many times they will execute.
For Loop vs While Loop Overview
| Feature | For Loop | While Loop |
|---|---|---|
| Type | Definite loop | Indefinite loop |
| Execution count | Known in advance | Depends on condition |
| Best use case | Iterating through sequences | Conditional repetition |
How to Write a For Loop
Start with the keyword 'for'
Every for loop must begin with the for keyword to tell Python you're creating a loop structure.
Create a variable name
Choose a descriptive variable name that will hold each item as the loop iterates through the sequence.
Use 'in' followed by your sequence
Specify the list, string, or other iterable object you want to loop through using the 'in' keyword.
Add colon and indentation
End the for statement with a colon and indent the code block that should execute for each iteration.
Key For Loop Concepts
Iteration Variable
The variable after 'for' holds each item from the sequence one at a time. In the example, 'name' holds 'John', then 'Mark', then 'Mary' in sequence.
Automatic Assignment
Python automatically assigns each item from the list to your variable. You don't need to manually access list indexes or manage the loop counter.
Sequential Processing
The loop processes items in order from the sequence. Each iteration executes the indented code block with the current item value.
It kinda goes through that sequence of items, grabs an item and assign it to 'name'
For Loop Best Practices
Choose names like 'name' or 'item' that clearly indicate what each iteration represents
Python requires consistent indentation for the code block inside the loop
Focus on one clear task per loop iteration for better readability and debugging
Key Takeaways