There are many occasions when we need to execute one or more statements multiple times until a condition is met. In programming, running a condition multiple times is done using loops. In this article, I’ll show you some examples of loops with Python.
What are Loops in Python?
Suppose we want to calculate the salary of several employees considering the number of hours each worked. Although the salary calculation is the same for each employee, it must be done for multiple employees. Thus, we can ask the computer to repeat the extraction and calculation of data for each employee until the data has been processed for all employees. Python has two types of loops called while and for a loop.
Loops can generally be classified as count controlled or event controlled. In a count-controlled loop, the body of the loop is executed a given number of times based on known values before the loop is executed for the first time. With event-controlled loops, the body is executed until an event occurs. The number of iterations cannot be determined until the program is executed.
Examples of Loops with Python
Now, in this section, I will take you through some examples of loops with Python.
While Loop with Python to Count Grades:
total = 0 count = 0 value = int( input("Enter the first grade: ") ) while value > 0 : total += value count += 1 value = int( input("Enter the next grade (or 0 to quit): ") ) avg = total / count print( "The average grade is %4.2f" % avg )
Enter the first grade: 67
Enter the next grade (or 0 to quit): 67
Enter the next grade (or 0 to quit): 89
Enter the next grade (or 0 to quit): 0
The average grade is 74.33
For Loop with Python to Print Table of any number:
n=int(input("Enter n :")) for i in range(1,11): print(n,"x",i,"=",i*n)
Enter n :5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
I hope you liked this article on examples of loops with Python programming language. Feel free to ask your valuable questions in the comments section below.