DEV Community

pulkitgovrani
pulkitgovrani

Posted on

2 3 2 1 1

If Else In Python

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:

Conditional Statement Basic Example

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:

Conditional Statement Advanced Example

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:

Checking basic condition

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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more