Python for Loops

🐍 Python for Loops

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


 

 Output:

Apple
Banana
Cherry

 2. For Loop with Range

The range() function generates a sequence of numbers:


 

  • range(start, stop, step)

  • start → beginning number (inclusive)

  • stop → end number (exclusive)

  • step → increment (default is 1)



 3. Loop Through String


 

 Output:

P
y
t
h
o
n

 4. Nested For Loops


  • Useful for tables, patterns, matrices.


 5. Using break in For Loop

break stops the loop immediately.


 Output:

1
2
3
4

 6. Using continue in For Loop

continue skips the current iteration.


 Output:

1
2
4
5

 7. Using else with For Loop

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


 Output:

1
2
3
4
Loop finished!

 8. Looping Through Dictionary


 


 9. Looping Through Tuple


 


 10. Practical Examples

Multiplication Table


Sum of Numbers in a List


Pattern Printing


 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.

You may also like...