Loops are used to execute a block of code repeatedly. Python supports two types of loops:
for
loopwhile
loopfor
LoopThe for
loop in Python is used to iterate over a sequence (e.g., list, tuple, string) or other iterable objects.
for variable in sequence:
# Code to execute in each iteration
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
range()
The range()
function generates a sequence of numbers.
for i in range(5):
print(i) # Output: 0, 1, 2, 3, 4
You can also specify a start, stop, and step:
for i in range(1, 10, 2):
print(i) # Output: 1, 3, 5, 7, 9
while
LoopThe while
loop executes as long as the condition is True
.
while condition:
# Code to execute while the condition is True
count = 5
while count > 0:
print(count)
count -= 1
while...else
ConstructIn Python, a while
loop can have an else
clause that executes after the loop condition becomes False
(unless the loop is terminated by a break
statement).
while condition:
# Code to execute while the condition is True
else:
# Code to execute when the loop ends naturally
num = 29
is_prime = True
if num > 1:
i = 2
while i < num:
if num % i == 0:
is_prime = False
break
i += 1
else:
print(f"{num} is a prime number.")
if not is_prime:
print(f"{num} is not a prime number.")
You can use the break
statement to exit a loop prematurely.
for i in range(10):
if i == 5:
break
print(i) # Output: 0, 1, 2, 3, 4
The continue
statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.
for i in range(5):
if i == 2:
continue
print(i) # Output: 0, 1, 3, 4
pass
StatementThe pass
statement is a placeholder used in situations where a loop or block of code is syntactically required but no action is desired.
for variable in sequence:
pass
for i in range(5):
pass # Placeholder for future implementation
This is useful during development when you are outlining the structure of your code but haven’t implemented specific logic yet.
else
Clause with LoopsLoops in Python can have an else
clause, which executes after the loop completes normally (i.e., not terminated by break
).
for i in range(5):
print(i)
else:
print("Loop completed.")
You can place one loop inside another to iterate over multi-dimensional data structures or perform repeated operations.
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
A while
loop can become infinite if the condition never becomes False
. Use caution to avoid such cases.
while True:
print("This is an infinite loop")
break # Use break to exit the loop
Objective: Write Python scripts using for
and while
loops to solve problems.
Create a Python Script:
Create a file named loops.py
.
Print Multiplication Table:
Write a program that prints the multiplication table for numbers 1 to 10 using nested for
loops.
for i in range(1, 11):
for j in range(1, 11):
print(f"{i} x {j} = {i * j}")
while
loop.total = 0
num = 1
while num <= 100:
total += num
num += 1
print(total)
Guessing Game: Write a program where the user has to guess a random number between 1 and 50. The program should keep asking until the user guesses correctly or chooses to quit.
Pattern Printing: Write a program to print the following pattern using nested loops:
*
**
***
****
*****