How To Use Conditional Statements in Python?

Published On: Fri, 04 Apr 2025 Updated On: Fri, 04 Apr 2025

Decision making is part of our life. At any point in time, we take decisions based on certain conditions. For example, every month I take decision how much money I need to spend and how much I need to save. I almost make curcial decision each day so that the monthly expense does not breach the upper limit threshold. If the upper limit has been hit then I need to stop the expense immediately. This is how life goes on day-to-day decision making. Any wrong decision can lead to a significant impact on our lives. That's what the decision making is and it is true for any programming language exists today.

ghibli-of-a-programmer-learning-if-else-elif-conditions-in-pythonIn programming, conditional statements play a pivotal role in decision-making. These statements empower developers to create dynamic and responsive code, enabling programs to adapt to distinct situations and user inputs. One commonly used conditional construct is the if-else statement, which allows programmers to execute two different code blocks based on one or more  expected conditions. In this chapter, we will explore how we should use conditional statements in Python. We will thoroughly absorb Python's if, else, and elif statements and the significance how nested conditions play a critical role in decision making when a complex situations arise. So, let's begin.

The Importance of Conditional Statements

Conditional statements are fundamental building blocks of any programming language, as they allow programmers to control the flow of the written program. Developers can make their code more intelligent, interactive and robust by utilizing if-else constructs. These statements are beneficial when dealing with scenarios where multiple outcomes are possible based on specific conditions.

Imagine you are developing a weather application that provides users with recommendations for outdoor activities. Using conditional statements, you can tailor the application's response based on the current weather conditions, suggesting activities like going to the beach on a sunny day or staying indoors during heavy rainfall. Using the conditional statements, developer can make their application more user friendly which users like to interact with. Let's dig into the syntax of the conditional statements.

Syntax

The basic syntax of an if-else statement in most programming languages is as follows:

Code Example
if condition1:
  # code block
elif condition2:
  # code block
else:
  # code block

Remember, conditions use the python operators that evaluates to boolean(True or False) value which eventually gets the intended code block to be executed. You can check the Learn and Master Operators and Expressions in Python blog if you want to brush up everything about python operators.

Usage of if, else, and elif Statements

Here's a simple Python example to illustrate the usage:

Code Example
weather = "rainy"

if weather == "sunny":
    print("It's a great day for outdoor activities!")
else:
    print("You might want to stay indoors today.")

In this example, if the variable weather holds the value "sunny," the first block of code will be executed, printing the corresponding message. Otherwise, the second block will be executed, suggesting indoor activities.

Sometimes, we may have more than two possible outcomes based on different conditions. For such cases, the elif (short for "else if") statement comes into play. To understand this scenario, think about the below discount slabs given for amount in specific range as shown below:

Order Amount Applicable Discount
0 < AMOUNT < 100 0%
100 < AMOUNT <200 10%
200 < AMOUNT 20%
How would you implement this logic?

Let's see the solution below:

Code Example
order_amount = 150

if order_amount > 200:
    print("You get a 20% discount!")
elif order_amount > 100:
    print("You get a 10% discount!")
else:
    print("No discount applicable.")

Was it simple?

Nested Conditions

When we develop production application, decision making is often not straightforward. It may require evaluating multiple conditions simultaneously. This is where nested conditions prove invaluable. Nested conditions are if-else statements placed inside if or else block, allowing for intricate decision-making.

Let's examine a scenario where a shipping company calculates shipping fees based on the destination and weight of the package:

Code Example
destination = "domestic"
weight = 4

if destination == "international":
    if weight > 10:
        shipping_fee = 30
    else:
        shipping_fee = 15
else:
    if weight > 5:
        shipping_fee = 10
    else:
        shipping_fee = 5

print(f"The shipping fee is ${shipping_fee}.")

In this example, the outer condition checks whether the destination is international or domestic. The code then enters the corresponding nested conditional based on the goal of determining the shipping fee, considering the package's weight.

You can check multiple conditions together in a single if statement as well by making use of python operators.

Try to use multiple conditions yourself and let me know in comments.
Code Example
# Both conditions must be true to execute the
# Code block
if condition1 and condition2:
  # Code block

# Either of the conditions can be true to execute the
# Code block
if condition3 or condition4:
  # Code block

Remember, when using and operator, all conditions must be true. So in above example, if condition1 is True and condition2 is false, the code block will not be executed. Vice vesra, in the second if condition if condition3 is false then also the condition4 will be checked, if it is true then code block will be executed.

You can experiment with the possible scenarios by adding multiple conditions and let me know your research in the comments.

Conclusion

Conditional statements are essential tools for developers to create dynamic and adaptive code. The if-else construct allows for different code paths based on specific conditions, while the elif statement facilitates handling multiple situations. Moreover, nested conditionals enable programmers to manage complex decision-making scenarios effectively. By mastering conditional statements, programmers can significantly enhance the functionality and interactivity of their programs, providing users with a seamless experience. So, embrace the power of conditional statements and unlock the true potential of your code!

How To Use Conditional Statements in Python?

Reader Comments


Add a Comment