Loops in Python
Types of Loops in Python
➢ While Loops in Python
➢ For Loops in Python
➢ Nested Loops in Python
Examples
for loop (basic)
for i in range(5):
print(i)
for loop with start and end
for i in range(1, 6):
print(i)
for loop to print a message multiple times
for i in range(3):
print("Hello")
Hello
Hello
Hello
while loop (basic)
i = 1
while i <= 5:
print(i)
i += 1
while loop to print a word
i = 0
while i < 3:
print("Python")
i += 1
Python
Python
Python
Loop with user input
n = int(input("Enter a number: "))
for i in range(1, n + 1):
print(i)
Basic Nested for Loop
for i in range(1, 4):
for j in range(1, 4):
print(i, j)
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Nested Loop – Print a Square Pattern
for i in range(3):
for j in range(3):
print("*", end=" ")
print()
* * *
* * *
* * *
Nested Loop – Print a Number Pattern
for i in range(1, 4):
for j in range(1, i + 1):
print(i, end=" ")
print()
2 2
3 3 3
Nested while Loop
i = 1
while i <= 3:
j = 1
while j <= 3:
print(i, j)
j += 1
i += 1
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Nested Loop with User Input
n = int(input("Enter number of rows: "))
for i in range(1, n + 1):
for j in range(1, i + 1):
print("*", end=" ")
print()
* *
* * *
* * * *