We can use a Python while loop to execute a set of statements again and again under a certain condition. For example, let’s say we want to find out all the factors of a positive integer. We can implement that easily using the following piece of code:
n = 21 i = 1 while i <= 21: if n % i == 0: print(i) i += 1
Here, we are iterating over all integers less than or equal to n. If the integer divides n, then we are printing the integer as a factor of n.
The above program will print the following output:
1 3 7 21
Now, let’s say we want to print all factors of n excepting 3. For example, if n = 21, then we want to print only 1, 7, and 21. We can modify the above code and implement it easily in the following way:
n = 21 i = 1 while i <= 21: if i == 3: i += 1 continue if n % i == 0: print(i) i += 1
Please note the usage of the continue statement. Here, we are taking all numbers between 1 and n. If the number is 3, then we …
0 Comments