Conditional Statements in Python: Hidden Logic for Smart Decisions
By Rohit Sharma
Updated on Jul 11, 2025 | 10 min read | 10.24K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Jul 11, 2025 | 10 min read | 10.24K+ views
Share:
Table of Contents
Did you know? With 92% of data professionals and 80% of AI developers preferring Python for its simplicity and efficiency, it’s the top choice for many industries. Python plays a central role in data science, AI, machine learning, automation, web development, finance, and scientific computing. |
Conditional statements in Python enable your programs to make decisions based on specific conditions, allowing you to control the flow of execution with precision and accuracy.
From simple if checks to complex if-elif-else structures, these statements are fundamental to writing flexible, intelligent, and efficient code. Knowing them is key to building real-world applications that respond dynamically to user input and program state.
In this blog, you will find the types of conditional statements in Python. It includes clear and practical examples that help reinforce your understanding and prepare you for hands-on development.
Popular Data Science Programs
Conditional statements in Python help you control the flow of your code by making decisions based on specific conditions. They come in handy when you're validating input, handling different outcomes, or building logic that reacts to user actions or data.
You’ll choose from types of conditional statements depending on what your program needs to do. if, if-else, if-elif-else, nested if statements, and conditional expressions (also called ternary operators). These structures enable you to control the behavior of your code in response to different values or situations.
Planning to enhance your Python programming skills and understand how conditional statements in Python work? The following courses simplify the concept and set you on a path to becoming a confident Python developer.
Here’s a quick breakdown of the types of conditional statements in Python:
Conditional Type |
Description |
Example |
if statement | Executes a block if the condition is true | if score > 50: |
if-else statement | Chooses between two blocks based on a condition | if age >= 18: else: |
if-elif-else chain | Handles multiple conditions in sequence | if x > 0: elif x == 0: else: |
Nested if | An if inside another if to handle complex logic | if user: if user.is_active: |
Conditional expression | A one-line if-else to assign or return values | status = "OK" if flag else "NO" |
Also Read: Python Cheat Sheet: From Fundamentals to Advanced Concepts for 2025
Let’s see each type of conditional statement in Python in detail with practical examples to help you understand how and when to use them effectively.
The if statement is the most basic form of a conditional statement in Python. It allows you to execute a block of code only when a specific condition is true.
Syntax:
if condition:
# code to execute if condition is true
Sample Code:
num = 5
if num > 0:
print("The number is positive.")
Code Explanation: In this conditional statement in Python, the condition num > 0 is evaluated. Since num is 5, the condition is true, so the code inside the if block executes and prints a message. If the condition were false, the block would be skipped entirely.
Output:
The number is positive.
Also Read: 12 Incredible Applications of Python You Should Know About
The else statement is used when you want to define an alternative block of code to execute if the if condition is false. It complements an if conditional statement in Python.
The condition in the if statement can be any valid expression, but it must evaluate to a boolean (True or False); otherwise, Python will raise an error. If the if condition is not true, the interpreter skips the entire if block and executes the else block instead.
Syntax:
if condition:
# code to execute if condition is true
else:
# code to execute if condition is false
Sample Code:
num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is negative.")
Code Explanation: This conditional statement in Python checks whether num is greater than 0. Since num is -5, the condition is false, and the else block executes, printing that the number is negative.
Output:
The number is negative.
Also Read: Exception Handling in Python: Handling Exception Using Try Except
The elif (short for "else if") statement lets you check multiple conditions in sequence. It’s used when you need to evaluate more than two outcomes in a conditional statement in Python.
Syntax:
if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition1 is false and condition2 is true
elif condition3:
# code to execute if condition1 and condition2 are false, and condition3 is true
else:
# code to execute if all conditions are false
Sample Code:
num = 0
if num > 0:
print("The number is positive.")
elif num == 0:
print("The number is zero.")
else:
print("The number is negative.")
Code Explanation: In this conditional statement in Python, three possible outcomes are handled. The first condition checks if num is positive. If not, the second check is to see if it’s equal, which is indeed true. However, if both are false, the else block assumes the number is zero. This structure makes your logic clear and avoids deeply nested code.
Output:
The number is zero.
Also Read: Python Challenges for Beginners
Nested if statements let you place one if (or if-else) block inside another. You use them when decisions depend on multiple layers of conditions that must be evaluated in a specific order.
Syntax:
if condition1:
if condition2:
# code executes if both conditions are true
Sample Code:
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed.")
else:
print("ID required for entry.")
else:
print("Entry denied. Must be 18 or older.")
Code Explanation: This nested if-conditional statement in Python first checks if the person is at least 18 years old. If true, it then checks whether they have an ID. If both conditions are true, entry is allowed. If the age condition is false, the outer else executes immediately.
Output:
Entry allowed.
Also Read: Data Analysis Using Python [Everything You Need to Know]
A conditional expression, also known as the ternary operator, lets you write simple if-else logic in a single line. It’s best used when assigning a value based on a condition.
Syntax:
value_if_true if condition else value_if_false
Sample Code:
score = 76
result = "Pass" if score >= 60 else "Fail"
print("Result:", result)
Code Explanation: This conditional statement in Python uses a one-liner to assign "Pass" or "Fail" to the result variable based on whether the score meets the passing threshold. It’s concise and readable for simple checks.
Output:
Result: Pass
Also Read: Object Oriented Programming Concept in Python
Now that you understand the different types of conditional statements in Python, let’s explore some practical use cases where they help control your code’s logic in real-world scenarios.
You’ll frequently use conditional statements in Python when your program needs to react to user input, check for specific values, or guide flow based on logic. Below are practical, real-world examples to illustrate how these conditionals are applied in everyday use cases.
You can use an if-else structure to verify login credentials before granting access. You have seen it on almost every website and app.
Sample Code:
password = "admin123"
user_input = input("Enter your password: ")
if user_input == password:
print("Access granted.")
else:
print("Access denied.")
Code Explanation: This conditional statement in Python checks if the entered password matches the stored one. If it does, access is granted. If not, the user is denied access.
Output (when correct):
Access granted.
You can use if-elif-else to display greetings based on the current hour.
Sample Code:
hour = 14 # 24-hour format
if hour < 12:
print("Good morning!")
elif hour < 18:
print("Good afternoon!")
else:
print("Good evening!")
Code Explanation: This conditional statement in Python uses multiple conditions to display different messages depending on the time. It branches the logic cleanly based on the value of hour.
Output:
Good afternoon!
Before processing an order, verify that the item is in stock.
Sample Code:
stock = 0
if stock > 0:
print("Order confirmed.")
else:
print("Sorry, item out of stock.")
Code Explanation: This simple if-else conditional statement in Python checks if there's stock available. If the condition is true, the order is processed; otherwise, a message is shown.
Output:
Sorry, item out of stock.
A conditional expression (ternary) is great for quick value assignments.
Sample Code:
dark_mode = True
theme = "Dark" if dark_mode else "Light"
print("Selected theme:", theme)
Code Explanation: This conditional statement in Python uses a one-line if-else to assign a value based on the state of dark_mode. It’s concise and improves readability for simple decisions.
Output:
Selected theme: Dark
Also Read: Top 10 Python Framework for Web Development
Now that you've explored how conditional statements in Python work, ranging from if, if else, and if elif else to nested structures and ternary operators. It’s time to test your understanding with some hands-on practice.
These exercises and quizzes will help you solidify your understanding of conditional statements in Python by applying concepts to real-world scenarios. By actively engaging with these questions, you'll develop the problem-solving skills needed to write clear, efficient decision-making code.
Here are some fun and practical questions to get you started:
Question 1: What is the correct syntax for a basic if statement in Python?
A. if (condition) then:
B. if condition:
C. if condition then:
D. if: condition
Question 2: Which of the following will raise an error in a conditional statement?
A. if 5 > 3:
B. if "hello":
C. if None:
D. if 10 = 5:
Question 3: What is the output of this code?
x = 10
if x > 5:
print("High")
else:
print("Low")
A. High
B. Low
C. Error
D. Nothing
Exercise 4: Age Verifier
Ask the user for their age and print whether they are a child (age < 13), a teenager (13–19), or an adult (20 and above). Use if elif else conditional statements in Python.
Exercise 5: Product Discount Checker
Prompt the user to enter the price of a product and a discount code.
Exercise 6: Temperature Status (Ternary Operator)
Take the current temperature as input. Use a conditional expression (ternary operator) to print "Too Hot" if the temperature is over 35°C, else print "Comfortable".
Exercise 7: Number Category Checker
Write a program to check if a number is prime and has a perfect square root.
upGrad’s Exclusive Data Science Webinar for you –
ODE Thought Leadership Presentation
Conditional statements in Python help you build programs that think and respond. From simple if conditions to nested logic and ternary expressions, they’re what let your code make smart decisions based on different inputs.
But knowing the syntax isn't enough. To get confident with conditional logic, you need to practice, write code, solve problems, and build real projects.
That’s where upGrad can help. If you're just getting started with Python or want to sharpen your skills, upGrad’s software development courses walk you through conditional statements, data structures, and more.
Here are some additional courses that can boost your programming journey and prepare you for real-world development:
Not sure how conditional statements in Python are applied in real-world projects? Connect with upGrad’s expert counselors or drop by your nearest upGrad offline center to discover a personalized learning path aligned with your goals.
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
Reference:
https://www.agileinfoways.com/blogs/python-in-it-industry-2025/
763 articles published
Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources