If-else in Python is one of the decision making statements, which is the most important aspect of almost all programming languages. Decision making allows us to run a particular block of codes for a particular decision. Decisions are based on the particular conditions. Condition checking is the backbone of decision making.
In Python decision making is performed by following statements:
Statement |
Description |
If Statement |
The if statement is used to test a
specific condition, if the condition is true, a block of code will be executed. |
If-else Statement |
The if-else statement is similar to if
statement except the fact that it also executes the block of codes for false case
of condition. If the condition provided will be false, the else statement
will be executed. |
Nested if Statement |
Here more than one if-else statement is found. If condition matches then inner if statement is executed, otherwise outer (else) statement is executed. |
The if statement
The if condition is used to test a particular condition and if the condition is true, it executes the block of code, known as if-block. The condition of if statement may be any logical expression, which can either be evaluated or be true/false.
if expression: statement |
---|
num = int(input("Enter the number:")) if num%2==0: print("The given number is an even number") |
---|
Enter the number: The given number is an even number |
---|
a = int(input("Enter a:")) b = int(input("Enter b:")) c = int(input("Enter c:")) if a>b and a>c: print("Here a is the largest number") if b>a and b>c: print("Here b is the largest number") if c>b and c>a: print("Here c is the largest number") |
---|
Enter a: 100 Enter b: 90
|
---|
The if-else statement
The if-else statement gives another block of codes, the else block of codes with if block of codes. It is executed in false case of if statements.
Syntax of the if else statement is given below:
if condition: #block of statements
|
---|
age=int(input("Enter your age:")) #if block of statement if age>=18:
|
---|
Enter your age: 19
|
---|
num=int(input("Enter any number:")) #if block of statement if num%2==0:
|
---|
Enter any number: 19
|
---|
if expression1: #block of styatements elif expression 2: #block of styatements elif expression3: #block of styatements
|
---|
num=int(input("enter the num:")) if num%7==0: print("The number is multiple of 7") elif num%10==0: print("The number is multiple of 5 and 10"); elif num%9==0: print("The number is multiple of 3 and 9");
|
---|
enter the num: 81 The number is multiple of 3 and 9 |
---|
marks=int(input("enter the marks:")) if marks>89 and marks<=100: print("Congrates! You scored Grade A") elif marks>74 and marks<=89: print("You scored Grade B"); elif marks>59 and marks<=74: print("You scored Grade C"); elif marks>44 and marks<=59: print("You scored Grade D"); elif marks>32 and marks<=44: print("You scored Grade E");
|
---|
enter the marks: 56 You scored Grade D |
---|