For… Else in python
If you are a beginner you might have learned about if…else and a match-case conditional statement which controls the flow of the program based on the if the conditional statement is true or false.
You might have also learned about for and while loops which iterate over a list a execute a statement over and over again.
But what if you can combine both, many beginner python programmers don’t know that they can combine else statement with loops.
Below is the explanation of how you can combine else condition with a loop in python.
let’s write a program to check if the number is prime or not using for else statement.
#input list of numbers for n in range(2, 10): #check if the input number is divided by any number between 2 to input number for x in range(2, n): if n % x == 0: print( n, 'equals', x, '*', n/x) break else: # loop fell through without finding a factor print(n, 'is a prime number') #Result #2 is a prime number #3 is a prime number #4 equals 2 * 2 #5 is a prime number #6 equals 2 * 3 #7 is a prime number #8 equals 2 * 4 #9 equals 3 * 3
In the above program, we check all the prime numbers between 2 to 10.
Considering if the number is 5, we check if the number is divided by any number between 2 to 5 by using the condition if n%x==0 modulus operator which gives the remainder upon dividing the two number.
Since for any number between 2 and 5 the if condition never becomes true. So the loop does not break and the else condition in the for loop is executed hence printing 5 is a prime number.
Similarly, you can combine else with a while loop.
You can read more about control flow on python docs