
The if else statement executes a group of statements when a condition is True otherwise, it will execute another group of statements.
The syntax of if else statement is given below
if condition:
statement 1
else:
statement 2
If the condition is True, then it will execute statement 1 and if the condition is False, then it will execute statement 2. It is advised to use 4 spaces as indentation before statement 1 and statement 2.
Let’s write a program to test whether a number is even or odd.
x = 10
if x % 2 == 0:
print(x, " is even number.")
else:
print(x, " is odd number.")
#output
10 is even number.
In this program, we are trying to display whether a given number if even or odd. The logic is simple. If the number is divisible by 2 then it is an even number otherwise it is an odd number. To know whether a number is divisible by 2 or not, we can use the modulus operator ( % ). This operator gives remainder of division. if the remainder is 0 then the number is divisible otherwise not.
We can also make the above program more interactive by asking the number from the user then decide whether it is even or odd. To ask the number from the user, we can use the input() function in python.
x = int(input("Enter a number: "))
if x % 2 == 0:
print(x, " is even number.")
else:
print(x, " is odd number.")
#output
Enter a number: 35
35 is odd number.