Sitemap
Bollavaram Harshavardhan Reddy

Bollavaram Harshavardhan Reddy

Software Engineer - 3+ years experienced

Python — Conditionals

2 min readOct 17, 2024

In programming decision making is essential and python provides conditional statements to control the flow of the program.

Conditional statements allow you to execute certain block of code based on certain conditions.

A condition can be True or False , based on the outcome we can execute blocks of code.

Here is how to use conditional statements in python.

“if” condition

If condition is basic conditional statement in python, If the written condition is true it executes the code block inside the if condition.

Example : There a two persons with name A and B , and their ages 23 ,32 find out who is elder using if statement.

a,b = 23,32
if a>b:
print(a,"a is elder")
if b>a:
print(b,"b is elder")

In the above case age of B is greater than A, Here only the second if condition is satisfied hence second if block print statement executes.

Get Bollavaram Harshavardhan Reddy’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s rewrite the above program is “else”

a,b = 23,32
if a>b:
print(a,"a is elder")
else:
print(b,"b is elder")

else is used along with ‘if’ in case ‘if’ condition is not true else block executes without checking another condition.

What if you want to check another condition without using another if condition? For that purpose we have “elif” condition.

Example : Let's say now you have three people A,B,C with ages 13,32,23 and now you want to find the elder among them.

a,b,c = 13,32,23
if a>b and a>c:
print("a is elder")
elif b>a and b>c:
print("b is elder")
else:
print("c is elder")

Ternary Operator

In Python if, else can be written in single line

print("a is elder") if a>b else print("b is greater")

The match-case statement was introduced in Python 3.10 and is used for pattern matching, similar to switch-case in other programming languages

age = 23
match(age):
case age if age<18:
print("not allowed")
case age if age>=18:
print("allowed")
case _:
print("invalid")

The match is power feature that allows pattern matching, while it can be used for many other purposes.

Thank you for Reading , Have a great day!

--

--

Bollavaram Harshavardhan Reddy
Bollavaram Harshavardhan Reddy

Written by Bollavaram Harshavardhan Reddy

Software Engineer - 3+ years experienced