Introduction to For Loop
3 min read ·
A
for loop is used to iterate over a sequence and execute a block of code once for each item in that sequence.In Python,
for loops are mainly used to loop through:- Lists
- Tuples
- Strings
- Dictionaries
- Ranges
Why Use a for Loop?
Use a
for loop when:- You know how many times the loop should run
- You want to access each element of a sequence
- You want clean and readable iteration
Basic Idea of for Loop
foris a keywordvariablestores one value at a time from the sequence- Loop runs until the sequence ends
- Indentation defines the loop body
Simple for Loop Example
- Loop runs 5 times
- Each value is printed one by one
for Loop with range()
- Starts from 1
- Ends at 5
6is not included
for Loop with String
- Each character is accessed individually
for Loop with List
How for Loop Works Internally
- Python picks the first element from the sequence
- Executes loop body
- Picks next element
- Repeats until sequence ends
for Loop vs while Loop
forloop is simpler when iteration count is knownwhileloop is condition-based
Common Beginner Mistake
Caution
for loop works with iterables, not numbers directly.
Correct Way
Real World Example
Real World Scenario
Printing marks of all students
Exercise
Practice Task
- Print numbers from 1 to 10 using
forloop - Print each character of your name
- Loop through a list of subjects and print them
- Use
range()to print even numbers from 2 to 20