Python For Loop
1. What is a For Loop?
A for loop in Python is used when you want to repeat a block of code a
certain number of times.
It helps you go through (or “loop over”) items in a list, string, or any
sequence.
Example in real life:
If your teacher says, “Write your name 5 times,” you can use a for loop
to do that!
2. Syntax of For Loop
The basic structure of a for loop is:
for variable in sequence:
code to repeat
- for: This keyword starts the loop.
- variable: A name used to store each value from the sequence (like a list
or range).
- sequence: The collection of items you want to loop through.
- code to repeat: The code that runs each time.
3. Example 1: Printing Numbers from 1 to 5
Example:
for i in range(1, 6):
print(i)
Explanation:
- The `range(1, 6)` generates numbers from 1 to 5.
- The loop prints each number one by one.
4. Example 2: Printing Each Letter of a Word
Example:
for letter in "Python":
print(letter)
Explanation:
- The loop goes through each letter in the word "Python".
- It prints one letter at a time.
5. Example 3: Loop Through a List
Example:
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
Explanation:
- The loop takes each item (fruit) from the list and prints it.
6. Example 4: Using range()
The range() function is often used with for loops to repeat
something a certain number of times.
Example:
for i in range(5):
print("Hello!")
Explanation:
- The loop runs 5 times (from 0 to 4).
- It prints “Hello!” five times.
7. Example 5: Printing Table of 2
Example:
for i in range(1, 11):
print("2 x", i, "=", 2 * i)
Explanation:
- The loop runs from 1 to 10.
- Each time, it prints the multiplication of 2 with `i`.
8. Nested For Loops
You can use a for loop inside another for loop. This is called a
nested loop.
Example:
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
Explanation:
- The outer loop runs for each `i`.
- For every `i`, the inner loop runs completely.
9. Break and Continue in For Loop
The break statement stops the loop early.
The continue statement skips to the next loop turn.
Example using break:
for i in range(1, 10):
if i == 5:
break
print(i)
Output: 1 2 3 4
Example using continue:
for i in range(1, 6):
if i == 3:
continue
print(i)
Output: 1 2 4 5
10. Example 6: Sum of Numbers
Example:
total = 0
for i in range(1, 6):
total = total + i
print("Sum =", total)
Explanation:
- The loop adds numbers from 1 to 5.
- At the end, it prints the total.
11. Practice Questions
Try these to test your understanding:
1. Print numbers from 10 to 1 using a for loop.
2. Print the table of 7 using a for loop.
3. Print all even numbers from 2 to 20.
4. Print all characters of your name using a for loop.
5. Find the sum of all odd numbers between 1 and 50.
6. Print each element of a list: [2, 4, 6, 8, 10].
7. Use a nested loop to print this pattern:
*
**
***
8. Write a program that asks your name 3 times and prints “Hello [name]!” each
time.