In this section, we will use how to use if-else statement with a loop. If-else is used when conditional iteration is needed. For example, print studetn names who got more than 80 percent.
The if-else statement checks the condition and if the condition is True it executes the block of code present inside the if block and if the condition is False, it will execute the block of code present inside the else block.
When the if-else condition is used inside the loop, the interpreter checks the if condition in each iteration, and the correct block gets executed depending on the result.
if condition:
block of statements
else:
block of statements
Example: Print all even and odd numbers
In this progaram, for loop statement first iterates all the elements from 0 to 20.
Next, the if statement checks whether the currect number is even or not. If yes, it prints it. Else, the else block gets executed.
for i in range(1, 11):
if i % 2 == 0:
print("Even number:", i)
else:
print("Odd number:", i)
Output:
Odd number: 1
Even number: 2
Odd number: 3
Even number: 4
Odd number: 5
Even number: 6
Odd number: 7
Even number: 8
Odd number: 9
Even number: 10