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

  • for is a keyword
  • variable stores 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
  • 6 is not included

for Loop with String

  • Each character is accessed individually

for Loop with List


How for Loop Works Internally

  1. Python picks the first element from the sequence
  2. Executes loop body
  3. Picks next element
  4. Repeats until sequence ends

for Loop vs while Loop

  • for loop is simpler when iteration count is known
  • while loop 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
  1. Print numbers from 1 to 10 using for loop
  2. Print each character of your name
  3. Loop through a list of subjects and print them
  4. Use range() to print even numbers from 2 to 20