Loop in Python
Subject: Python Programming
In programming a loop or iteration is a set of instructions or command that is continuously repeated until a condition is satisfied. Repitition of action is one reason we reply on computers. For example when there is a large amounts of data, it is very convenient to use a loop statement such as For loop or While loop to repeatedly execute such task.
For Loop
Example 1
#program to display my name 10 times using for loop
for n in range(10):
print ("Ben Onuorah")
Note: only the indented code will be affected by the for loop, code not indented will not be affected by the loop, see example 2
Example 2
#print Ben Onuorah 10 times and Welcome once
for n in range(10):
#within the loop
print ("Ben Onuorah")
#outside the loop, not indented
print ("Welcome")
Example 3
#this program will display 0 to 9
for n in range(10):
print (n)
Example 4
#this program will display 1 to 10
for n in range(1,11):
print (n)
Example 5
#this program will display 1 to 10
for n in range(1,11):
print (n)
For the program to count in 2s we will introduce a third parameter (increment) to the range function of the For loop, which if not specified will be interesting by 1.
Syntax: range(initial, limit, increment)
Example 6
#will display odd number from 1 to 100
for n in range(1,101,2):
print (n)
Example 7
#will will count down from 10 to 1
for n in range(10,0,-1):
print (n)
While Loop
Example 8
#will display 1 to 10
count=1
while count<= 10:
print (count)
count=count+1
Example 9
#will display even number 2 to 20
count=2
while count<= 20:
print (count)
count=count+2
By:
Benjamin Onuorah
Comments
Joshua Fasinu (learner)
Date commented: 13-Aug-2024 08:08:04am
I understood the For loop but i'm having problem with While loop, i wish i could get a material that i can use to understand better
Login to comment or ask question on this topic
Previous Topic Next Topic