We require decision making whenever we want to execute certain part of code only if the condition is satisfied. So if, elif and else are used for decision making in python.
Basic Example
A person is allowed to drive a car if he/she is more than 18 years old else he cannot drive the car.
Code:
Input 1:
18
Output 1:
You are eligible to drive a car
Input 2:
16
Output 2:
You cannot drive a car
More Complex Example
Assume that if a student’s age is less than 6 then he has to play only, if the age is between 6 to 14 then he has to study and play, if the age is greater than 14 then he can do anything.
Code:
Input 1:
5
Output 1:
You can play
Input 2:
14
Output 2:
You can study and play also
Checking Single Statement
Note: If we want just to check a condition that it exists or not then it can be done by using only if condition.
Code:
Input 1:
13
Output 1:
You are a teenager
Input 2:
11
Output 2:
No Output
I hope you have understood the functionality of if & else conditional statements in python.
Top comments (0)