Category: python
python Loop
Published on 24 Jul 2026
Explanation
The for loop is used to iterate over a sequence such as a string, list, tuple, dictionary, set, or range
Code:
# Using range()
for i in range(1, 6):
print(i)
# Iterating through a list
fruits = ['Apple', 'Banana', 'Orange']
for fruit in fruits:
print(fruit)
# Iterating through a string
for ch in 'Python':
print(ch)
Explanation
The while loop repeatedly executes a block of code as long as the specified condition remains True. Unlike the for
Code:
count = 1
while count <= 5:
print('Count:', count)
count += 1
password = ''
while password != 'python123':
password = input('Enter password: ')
print('Access Granted')
Explanation
The break statement immediately terminates the nearest enclosing loop, regardless of whether the loop condition is still True. It is
Code:
numbers = [12, 45, 67, 89, 23]
search = int(input('Enter number to search: '))
for number in numbers:
if number == search:
print('Number Found')
break
else:
print('Number Not Found')
for i in range(1, 11):
if i == 6:
break
print(i)
Explanation
The continue statement skips the remaining statements in the current iteration and moves to the next iteration of the loop.
Code:
print('Using continue')
for i in range(1, 11):
if i % 2 == 0:
continue
print(i)
print('\nUsing pass')
for i in range(1, 6):
if i == 3:
pass
print(i)
if True:
pass
Explanation
A nested loop is a loop inside another loop. The inner loop completes all of its iterations for each iteration
Code:
# Multiplication Table
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end='\t')
print()
print('\nStar Pattern')
for i in range(1, 6):
for j in range(i):
print('*', end=' ')
print()