More on Loops with Python
Subject: Python Programming
Loop can be logically and creatively use to make programming more useful and interactive.
Example 1
You are ask to write a program to calculate the average score of n number of students.
Because the number of students is unknown you can ask the user to input the number of students you want to process there score, and use this to execute the loop to compute the average.
#prompt use to enter number
n=int(input("Enter the number of students you want to compute their result "))
totalscore=0
averagescore=0
count=1
while count<=n:
print ("Student ",count)
score = int(input("Enter score "))
totalscore=totalscore+score
count=count+1
averagescore=totalscore/n
print ("Total number of student (s): ",n)
print ("Total score: ", totalscore)
print ("There average score of the students: ", averagescore)
Nexted Loop
This simply means having a loop inside another look. Use for creating a 2 dimensional table like data structure. With the outerloop being the rows and inner loop the columns.
Example 2
#12 rows by 20 columns multiplication table
#outer loop or rows (1 to 20)
for r in range(1,21):
#inner loop or columns (1 to 13)
for c in range(1,13):
#e.g 2x1=2... 2x12=24
print (r,"x",c,"=",r*c)
By:
Benjamin Onuorah
Comments
Joshua Fasinu (learner)
Date commented: 13-Aug-2024 08:08:45am
I need material for looping, i don't get it
Login to comment or ask question on this topic
Previous Topic Next Topic