Sitemap

Conditional statements in Python

2 min readFeb 16, 2026

--

Conditional statements allow a program to execute certain code based on whether a condition is True or False. They are fundamental to controlling the flow of a program.

The Basics: if, elif, else

Python has three main conditional keywords:

  • if — checks a condition
  • elif — stands for “else if”, checks another condition if the previous if was False
  • else — runs if all previous conditions are False.

syntax

if condition1:
# code executes if condition1 is True
elif condition2:
# code executes if condition2 is True
else:
# code executes if all above conditions are False

Example:

age = 20

if age < 13:
print("Child")
elif age < 20:
print("Teenager")
else:
print("Adult")

Conditional Expressions / Ternary Operator

Python allows inline conditions using a ternary operator:

Syntax:

<value_if_true> if <condition> else <value_if_false>

# here:
# condition → a Boolean expression (True or False)
# value_if_true → returned/evaluated if the condition is True
# value_if_false → returned/evaluated if the condition is False

Example 1 :

age = 20
status = ”adult” if age>=18 else “minor”
print(status)

Example 2 : Inline with print

score=85
print(“pass” if score >=50 else “fail” )

Example 3 : Nested ternary operators

num=0
result = “positive” if num >=0 else “Negative” if num < 0 else “Zero”

Nested if Statements

You can nest if statements inside another if:

num = 15

if num > 0:
if num % 2 == 0:
print("Positive Even")
else:
print("Positive Odd")
else:
print("Non-positive number")

Advanced Conditional Patterns

1. if with any() and all()

scores = [70, 85, 90]

if all(score >= 50 for score in scores):
print("Passed all exams")

if any(score >= 90 for score in scores):
print("At least one top score")

2. Conditional Execution with match (Python 3.10+)

Get Saurabh Gandhi’s stories in your inbox

Join Medium for free to get updates from this writer.

Python 3.10 introduced Structural Pattern Matching, which can replace multiple elif conditions.

command = "start"

match command:
case "start":
print("Starting")
case "stop":
print("Stopping")
case _:
print("Unknown command")

3. Short-circuiting

Logical operators in Python short-circuit, meaning evaluation stops once the result is known:

def check():
print("Checked")
return True

if False and check(): # check() is never called
print("Hello")

Summary Table

Questions

  1. What are conditional statements in Python?
  2. What is the syntax of an if statement in Python?
  3. What is the difference between if and elif?
  4. Is else mandatory in Python conditional statements?
  5. Can we write multiple if statements instead of elif?

--

--

Saurabh Gandhi
Saurabh Gandhi

Written by Saurabh Gandhi

Python • AI • Tech Learning Writing simple guides that make coding easy for everyone.