If, elif and if.. else statements are used to make decisions in the python programming. The code executes only if particular condition is satisfied. For the if statement program executes only if the test expression is satisfied. The program executes only if the ‘test expression’ is true. If the ‘test expression’ is false the statements under the syntax will not get executed. In the following program two integer numbers are taken from the user as input and the test expression for the if statement needs to be satisfied for the program to get executed.
Use of If statement :
number1 = int(input('Enter first number :'))
number2 = int(input('Enter second number :'))
if number2 > number1:
print("Second number is greater than first number")
Output :
Enter first number : 15 Enter second number : 35 Second number is greater than first number
The following program makes the use of ‘if’ and ‘elif’ statement. ‘elif’ statement can be used to check multiple test expressions. ‘elif ‘ statement is executed if ‘if’ statement test expression is not true. ‘elif’ statement is to try the statement if ‘if’ test expression is false. In the following program two integer numbers are taken from the user as input. ‘elif’ statement is executed if both the numbers are true.
Use of if and elif statement:
number1 = int(input('Enter first number :'))
number2 = int(input('Enter second number :'))
if number1 > number2:
print("number1 is greater than number2")
elif number1 == number2:
print("number1 is equal to number2")
Output:
Output 1:
Enter first number : 15 Enter second number : 15 number1 is equal to number2
Output 2:
Enter first number : 7 Enter second number : 2 number1 is greater than number2
The following program makes the use of ‘if’,’elif’ and ‘else’ statement. When the program is executed it first executes the ‘if statement’ , if the test expression is not satisfied, it will check the expression for ‘elif’ statement. If no ‘test expression’ is satisfied then test expression of ‘else’ will be executed.
The ‘if, elif, else’ body may have multiple ‘elif’ statements but will have only one ‘if’ and ‘else’ statement. In the following program two integer numbers are taken as input and the output value is printed on execution of test expression.
Use of if, elif, and else statements:
number1 = int(input('Enter first number :'))
number2 = int(input('Enter second number :'))
if number1 > number2:
print("number1 is greater than number2")
elif number1 == number2:
print("number1 is equal to number2")
else:
print("number1 is less than number2")
Output:
OUTPUT 1
Enter first number : 7 Enter second number : 15 number1 is less than number2
OUTPUT 2:
Enter first number : 7 Enter second number : 7 number1 is equal to number2
OUTPUT 3:
Enter first number : 18 Enter second number : 5 number1 is greater than number2