For Loop in Python
A for loop in Python is used to repeat a block of code for each item in a sequence (like a list, string, or range of numbers). It helps when we know in advance how many times we want to run the loop.
For example, we can use a for loop to print numbers, display characters of a string, or go through a list of names.
Syntax:
for variable in sequence:
# block of code
Note: Indentation is very important in Python to define the block of code.
Example 1: Print names of 3 friends
friends = ["Vansh", "Yash", "Ojas"]
for name in friends:
print("Hello", name)
Output:
Hello Vansh
Hello Yash
Hello Ojas
Explanation:
- We have a list called
friends
that contains three names. - A
for
loop is used to go through each name in the list. - During each loop cycle, one name is stored in the variable
name
. - The program then prints a message: "Hello" followed by that name.
- This continues until all names in the list have been printed.
Example 2: Print numbers from 1 to 5
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Explanation:
range(1, 6)
gives numbers from 1 to 5 (6 is not included).- The loop runs 5 times and prints each number one by one.
Example 3: Loop through a string
for char in "Sky":
print(char)
Output:
S
k
y
Explanation:
- We are using a
for
loop to go through each character of the string"Sky"
. - In each round of the loop, one character from the string is picked and stored in the
variable
char
. - The
print(char)
statement then displays that character on a new line. - This continues until all characters in the string have been printed one by one.
Why we use for
Loop?
- To avoid repetition: Instead of writing the same line of code multiple times, we use a loop to repeat it automatically.
- To work with sequences: It helps us go through items in a list, string, tuple, or range one by one.
- To save time and make code shorter: A few lines using a loop can do what would take many lines otherwise.
- To perform actions on each item: We can print, calculate, or check conditions on every item in a sequence.
Summary:
- Used when: We know how many times we want to repeat.
- Works with: Lists, strings, tuples, ranges, etc.
- Syntax:
for variable in sequence:
- Runs the block: For each item in the sequence.
Common Mistakes to Avoid:
- Forgetting the colon
:
at the end of thefor
line. - Incorrect indentation — Python needs proper spacing!
- Using wrong variable name inside the loop.