How to Use For Loop in Python: Syntax and Examples
In Python, a
for loop is used to repeat a block of code for each item in a sequence like a list or string. You write it as for variable in sequence: followed by an indented block of code to run for each item.Syntax
The for loop syntax in Python is simple and easy to read. It starts with the keyword for, followed by a variable name that will hold each item from the sequence one by one. Then comes the keyword in, followed by the sequence (like a list, string, or range). The loop body is indented and contains the code to repeat.
- for: starts the loop
- variable: temporary name for each item
- in: keyword to check membership
- sequence: the collection to loop over
- :: marks the start of the loop block
- indented block: code to run each time
python
for item in sequence: # code to run for each item
Example
This example shows a for loop that prints each fruit in a list. It demonstrates how the loop variable takes each value and runs the print statement for each one.
python
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit)
Output
apple
banana
cherry
Common Pitfalls
One common mistake is forgetting the colon : after the for statement, which causes a syntax error. Another is not indenting the loop body properly, which leads to indentation errors. Also, modifying the sequence inside the loop can cause unexpected behavior.
python
wrong: for i in range(3): print(i) right: for i in range(3): print(i)
Quick Reference
| Part | Description |
|---|---|
| for | Starts the loop |
| variable | Holds current item from sequence |
| in | Checks membership in sequence |
| sequence | List, string, range, or other iterable |
| : | Marks start of loop block |
| Indented block | Code to repeat for each item |
Key Takeaways
Use
for variable in sequence: to loop over items in Python.Indent the loop body to tell Python what to repeat.
Remember the colon
: after the for statement.Avoid changing the sequence inside the loop to prevent bugs.
Use
range() to loop a specific number of times.