Mastering Decision Making in Python: if, else, and elif

O

Ohidur Rahman Bappy

MAR 22, 2025

Mastering Decision Making in Python: if, else, and elif

In programming, decision-making is essential to directing the flow of execution based on conditions. Python provides a straightforward way to achieve this using if, else, and elif statements. Let's delve into how these work and see them in action!

What is an if Statement?

The if statement evaluates a condition. If the condition is True, the indented block of code runs. Here's a basic example:

x = 10
if x > 5:
    print("x is greater than 5")

Using else

The else statement provides an alternative set of instructions when the if condition evaluates to False.

x = 3
if x > 5:
    print("x is greater than 5")
else:
    print("x is 5 or less")

Introducing elif

When you have multiple conditions to check, you can use elif, which stands for "else if." It comes in handy for evaluating multiple expressions.

x = 5
if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is exactly 5")
else:
    print("x is less than 5")

Practical Example

Let's look at a more complex example that uses all three statements:

age = 18

if age < 13:
    print("Child")
elif 13 <= age < 18:
    print("Teenager")
elif 18 <= age < 65:
    print("Adult")
else:
    print("Senior")

In this example, the code checks age categories and prints out the appropriate label.

Conclusion

Understanding and utilizing if, else, and elif statements allow you to build more dynamic and adaptable programs. Mastering these concepts is fundamental to your journey in Python programming!