Python for Loops

🐍 Python for Loops — Full Tutorial

The for loop in Python is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item.


🔹 1. Basic For Loop with List

fruits = ["Apple", "Banana", "Cherry"]

for fruit in fruits:
print(fruit)

✅ Output:

Apple
Banana
Cherry

🔹 2. For Loop with Range

The range() function generates a sequence of numbers:

# Print 0 to 4
for i in range(5):
print(i)

# Print 1 to 5
for i in range(1, 6):
print(i)

  • range(start, stop, step)

  • start → beginning number (inclusive)

  • stop → end number (exclusive)

  • step → increment (default is 1)

for i in range(0, 10, 2):
print(i) # 0 2 4 6 8

🔹 3. Loop Through String

name = "Python"

for char in name:
print(char)

✅ Output:

P
y
t
h
o
n

🔹 4. Nested For Loops

for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")
  • Useful for tables, patterns, matrices.


🔹 5. Using break in For Loop

break stops the loop immediately.

for i in range(1, 10):
if i == 5:
break
print(i)

✅ Output:

1
2
3
4

🔹 6. Using continue in For Loop

continue skips the current iteration.

for i in range(1, 6):
if i == 3:
continue
print(i)

✅ Output:

1
2
4
5

🔹 7. Using else with For Loop

  • else runs if the loop completes normally (not stopped by break).

for i in range(1, 5):
print(i)
else:
print("Loop finished!")

✅ Output:

1
2
3
4
Loop finished!

🔹 8. Looping Through Dictionary

student = {"name": "Vipul", "age": 25}

# Loop through keys
for key in student:
print(key)

# Loop through values
for value in student.values():
print(value)

# Loop through key-value pairs
for key, value in student.items():
print(key, ":", value)


🔹 9. Looping Through Tuple

numbers = (1, 2, 3, 4)

for num in numbers:
print(num)


🔹 10. Practical Examples

Multiplication Table

num = 5
for i in range(1, 11):
print(f"{num} x {i} = {num*i}")

Sum of Numbers in a List

numbers = [10, 20, 30, 40]
total = 0
for n in numbers:
total += n
print("Total:", total)

Pattern Printing

for i in range(1, 6):
print("*" * i)

✅ Output:

*
**
***
**
**
*****

🔹 11. For Loop Tips

  1. Use range() for number sequences.

  2. Use break to exit loop early.

  3. Use continue to skip iteration.

  4. else block executes only if loop finishes naturally.

  5. Works with lists, tuples, sets, dictionaries, strings.


🧠 Practice Exercises

  1. Print all even numbers from 1 to 50.

  2. Print multiplication table for a user-entered number.

  3. Calculate the factorial of a number using for loop.

  4. Print a triangle pattern using *.

  5. Loop through a dictionary of students and print their names.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *