The Loops in Python
What is the purpose of loops in Python?
Loops are used when you need to repeat a block of code multiple times without writing
the same instructions again and again.
In many situations, we want to perform a repetitive task, such as displaying numbers
from 1 to 100. Writing 100 separate print() statements would be inefficient and
impractical. A loop allows Python to do this automatically and efficiently.
Without a loop:
print(1)
print(2)
print(3)
# ... up to 100
I – The for Loop
The for loop is used to iterate over a sequence (numbers, characters, etc.).
1-The range() function
range() is a built-in Python function used to generate a sequence of numbers. It takes
three forms
Example 1
Write a Python program that displays the numbers from 1 to 10.
1-1 range(stop)
Starts from 0
Ends at stop − 1
for i in range(11):
print(i)
1-2 range(start, stop)
Starts from start
Ends at stop − 1
for i in range(1,11):
print(i)
1-3 range(start, stop, step)
The step controls how much the number increases each time.
for i in range(1,11,1):
print(i)
Example 2
Write a Python program that reads a number, then prints all even numbers less than that
number.
Num=int(input('enter an integer'))
for i in range(0,Num,2):
if i%2==0:
print(i)
Num=int(input('enter an integer'))
for i in range(0,Num,2):
print(i)
Example 3
Write a Python program that prints each character in a string entered by the user.
Solution 1
Text=input('enter a text')
for ch in Text:
print(ch)
Solution 2
Text=input('enter a text')
for i in range(len(Text)):
print(Text[i])
II – The while Loop
The while loop repeats a block of code as long as a condition is true.
while condition:
# code to repeat if condition is true
Example 4
Write a Python program that asks the user to enter a positive integer. Then display all
numbers from that integer down to 0.
Num=int(input('enter an integer positive'))
for i in range(Num,-1,-1):
print(i)
print('===========')
i=Num
while i>=0:
print(i)
i-=1