Range Function In Python Python Range Function With Example

20 Examples of for loop and while loop in python tutorial

20 Examples of For Loops in Python

Master the power of Python for loops with these clear, step-by-step examples.

What is a for loop in Python?
A for loop in Python is used to iterate over a sequence, such as a list, string, tuple, or any iterable object. It helps automate repetitive tasks efficiently.

1. Basic For Loop

A for loop iterates through a range of numbers:

for i in range(5):
    print(i)
      

Output:

0
1
2
3
4

2. For Loop with a List

Loop through a list of fruits:

fruits = ['apple', 'banana', 'mango']
for fruit in fruits:
    print(fruit)
      

Output:

apple
banana
mango

3. For Loop with a String

Iterate through characters in a string:

for char in "hello":
    print(char)
      

Output:

h
e
l
l
o

4. For Loop with a Tuple

Iterate through a tuple of numbers:

numbers = (1, 2, 3)
for number in numbers:
    print(number)
      

Output:

1
2
3

5. For Loop with a Dictionary

Loop through key-value pairs in a dictionary:

ages = {'Alice': 22, 'Bob': 27, 'Eve': 19}
for name, age in ages.items():
    print(f'{name} is {age} years old')
      

Output:

Alice is 22 years old
Bob is 27 years old
Eve is 19 years old
Explore these Python for loop examples to level up your coding skills. Happy Learning! 🎉

6. For Loop with Nested Lists

Iterate through rows and columns in a 2D list:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for col in row:
        print(col)
      

Output:

1
2
3
4
5
6
7
8
9

7. For Loop with Break

Stop a loop when a condition is met:

for i in range(5):
    if i == 3:
        break
    print(i)
      

Output:

0
1
2

8. For Loop with Continue

Skip an iteration when a condition is met:

for i in range(5):
    if i == 3:
        continue
    print(i)
      

Output:

0
1
2
4

9. For Loop with Range and Step

Iterate with custom steps in a range:

for i in range(10, 0, -2):
    print(i)
      

Output:

10
8
6
4
2

10. For Loop with Else Clause

Execute a block after the loop ends:

numbers = [1, 3, 5, 7]
for num in numbers:
    if num % 2 == 0:
        print(f"{num} is even")
        break
else:
    print("No even numbers found")
      

Output:

No even numbers found

11. For Loop with Enumerate

Get the index while looping through a list:

fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
      

Output:

0: apple
1: banana
2: mango

12. For Loop with Multiple Iterators

Combine two lists with `zip()`:

numbers = [1, 2, 3]
colors = ['red', 'green', 'blue']
for number, color in zip(numbers, colors):
    print(f"{number} is {color}")
      

Output:

1 is red
2 is green
3 is blue

13. For Loop to Reverse a String

Reverse a string using a for loop:

text = "python"
for char in reversed(text):
    print(char)
      

Output:

n
o
h
t
y
p

14. For Loop to Filter Items

Filter numbers greater than 5:

numbers = [3, 6, 8, 1, 4]
for num in numbers:
    if num > 5:
        print(num)
      

Output:

6
8

15. For Loop with Strings and Index

Display characters with their indexes:

word = "hello"
for i, char in enumerate(word):
    print(f"Index {i}: {char}")
      

Output:

Index 0: h
Index 1: e
Index 2: l
Index 3: l
Index 4: o

16. For Loop with Set

Iterate through a set of unique values:

unique_numbers = {1, 2, 3, 4}
for number in unique_numbers:
    print(number)
      

Output:

1
2
3
4

17. For Loop with Range and Float Conversion

Iterate through numbers and convert to float:

for i in range(5):
    print(float(i))
      

Output:

0.0
1.0
2.0
3.0
4.0

18. For Loop with Range for Multiplication

Print the multiplication table for 2:

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

Output:

2 x 1 = 2
2 x 2 = 4
2 x 3 = 6

2 x 10 = 20

19. For Loop with List Comprehension

Create a list of squares using list comprehension:

squares = [x**2 for x in range(5)]
print(squares)
      

Output:

[0, 1, 4, 9, 16]

20. For Loop with Generator Expression

Sum numbers using a generator expression:

total = sum(x for x in range(5))
print(total)
      

Output:

10
These 20 examples will help you understand Python for loops thoroughly. Practice and master them! 🎉

Example of While Loop

while loop flow chart python

20 Examples of While Loops in Python

Master Python while loops with these clear, step-by-step examples.

What is a while loop in Python? A while loop in Python repeatedly executes a block of code as long as a given condition is true.

1. Basic While Loop

Loop through numbers until a condition is met:
i = 0
while i < 5:
    print(i)
    i += 1
Output:
0 1 2 3 4

2. While Loop with a List

Iterate through a list until a condition is met:
fruits = ['apple', 'banana', 'mango']
i = 0
while i < len(fruits):
    print(fruits[i])
    i += 1
Output:
apple banana mango

3. While Loop with String

Iterate through the characters of a string:
text = "hello"
i = 0
while i < len(text):
    print(text[i])
    i += 1
Output:
h e l l o

4. While Loop with Break

Break the loop when a certain condition is met:
i = 0
while True:
    if i == 5:
        break
    print(i)
    i += 1
Output:
0 1 2 3 4

5. While Loop with Continue

Skip an iteration using the continue statement:
i = 0
while i < 5:
    if i == 3:
        i += 1
        continue
    print(i)
    i += 1
Output:
0 1 2 4

6. While Loop with Else Clause

Execute a block after the loop ends:
i = 0
while i < 5:
    print(i)
    i += 1
else:
    print("Loop ended")
Output:
0 1 2 3 4 Loop ended

7. While Loop with List Length

Loop through a list until a specific index:
fruits = ['apple', 'banana', 'mango']
i = 0
while i < len(fruits):
    print(fruits[i])
    i += 1
Output:
apple banana mango

8. While Loop with Nested Loops

Use nested while loops for complex iterations:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
i = 0
while i < len(matrix):
    j = 0
    while j < len(matrix[i]):
        print(matrix[i][j])
        j += 1
    i += 1
Output:
1 2 3 4 5 6 7 8 9

9. While Loop with Random Numbers

Generate random numbers until a condition is met:
import random
number = random.randint(1, 10)
while number != 5:
    print(number)
    number = random.randint(1, 10)
Output:
Random numbers until 5 appears

10. While Loop with User Input

Ask the user for input until a valid response is provided:
user_input = ''
while user_input != 'yes':
    user_input = input('Do you want to continue? (yes/no): ')
print('You chose to continue!')
Output:
User input until ‘yes’ is entered

11. While Loop with Counter

Use a counter to track loop iterations:

counter = 0
while counter < 10:
    print("Iteration:", counter)
    counter += 1
      

Output:

Iteration: 0
Iteration: 1
...
Iteration: 9

12. While Loop with a Timer

Use a while loop to simulate a timer:

import time
seconds = 0
while seconds < 5:
    print("Time passed:", seconds, "seconds")
    time.sleep(1)
    seconds += 1
      

Output:

Time passed: 0 seconds
Time passed: 1 seconds
...

13. While Loop with User Input Validation

Keep asking for input until a valid choice is made:

user_input = ''
while user_input not in ['yes', 'no']:
    user_input = input('Do you want to continue? (yes/no): ')
print('You chose to', user_input)
      

Output:

User chooses 'yes' or 'no'

14. While Loop to Count Down

Use a while loop to count down:

count = 10
while count > 0:
    print(count)
    count -= 1
print("Blast off!")
      

Output:

10
9
8
...
Blast off!

15. While Loop to Find Factorial

Calculate the factorial of a number using a while loop:

number = 5
factorial = 1
while number > 0:
    factorial *= number
    number -= 1
print("Factorial is:", factorial)
      

Output:

Factorial is: 120

16. While Loop with Multiple Conditions

Use multiple conditions in the while loop:

i = 0
while i < 5 and i != 3:
    print(i)
    i += 1
      

Output:

0
1
2

17. Infinite While Loop with Break

Create an infinite loop and break on condition:

while True:
    user_input = input("Type 'exit' to stop: ")
    if user_input == 'exit':
        break
    else:
        print("You typed:", user_input)
      

Output:

User types input until 'exit' is entered

18. While Loop with Dynamic List

Modify a list inside a while loop:

numbers = [1, 2, 3, 4]
while numbers:
    print(numbers.pop(0))
      

Output:

1
2
3
4

19. While Loop to Check Prime Number

Check if a number is prime using a while loop:

num = 29
i = 2
is_prime = True
while i <= num // 2:
    if num % i == 0:
        is_prime = False
        break
    i += 1
if is_prime:
    print(num, "is prime")
else:
    print(num, "is not prime")
      

Output:

29 is prime

20. While Loop with Fibonacci Sequence

Generate Fibonacci sequence using a while loop:

a, b = 0, 1
while a < 100:
    print(a, end=' ')
    a, b = b, a + b
      

Output:

0 1 1 2 3 5 8 13 21 34 55 89