If we want to execute a set of statements, again and again, let’s say under certain conditions, then we can use a loop. In Python, we have two types of loops – for loops and while loops. In this article, we will discuss Python for loops.
Let’s say we are given a positive integer n and we want to print all factors of the integer. One simple way to do this is to take all numbers between 1 and n and divide n with the numbers. If the number x divides n, then x is a factor of the integer n.
We can implement this very easily using Python for loop in the following way:
n = 21 for x in range(1, n + 1): if n % x == 0: print(x)
The output will be:
1 3 7 21
The range(a) function in Python iterates over all integers between 0 and a – 1. And, range (a, b) function iterates over a to b – 1. In this program, we want to iterate over all numbers between 1 and n both inclusive, and so, we are using range(1, n + 1).
And, as we discussed in our previous article, in is a membership operator. It checks whether x is present in range(1, n + 1). If we have a list, tuple, or set, we can use the for loop and the in operator, and execute the statements within a for loop once for each item of the list, tuple, set, etc.
For example, let’s say we have a list of numbers. And, we want to print all the numbers of the list. We can do so easily using a for loop.
0 Comments