Python Conditional Statements: If, Else, Elif

Python Conditional Statements: If, Else, Elif

Let’s talk about one of the most fundamental concepts in programming: conditional statements. In Python, these are the tools we use to make decisions in our code. Whether you're just starting out or looking to deepen your understanding, mastering conditionals is key to writing dynamic and responsive applications.


What Are Conditional Statements?

Conditional statements allow your program to execute certain pieces of code only when specific conditions are met. Think of it like giving your code the ability to choose a path based on the situation. The main keywords you'll use are if, else, and elif.

Let’s start with a simple example:

age = 18

if age >= 18:
    print("You are an adult.")

In this case, if age is 18 or above, the message "You are an adult." will be printed. Otherwise, nothing happens.


The If Statement

The if statement is your go-to when you want to check a condition. The syntax is straightforward:

if condition:
    # code to run if condition is True

Remember: - The condition must be an expression that evaluates to True or False. - The code block under the if must be indented (usually by 4 spaces).

Example:

temperature = 30

if temperature > 25:
    print("It's a hot day!")

If the temperature is above 25, Python will print the message.


Adding an Else Clause

What if you want to do something when the condition is not met? That’s where else comes in.

if condition:
    # code if condition is True
else:
    # code if condition is False

Let’s expand our temperature example:

temperature = 20

if temperature > 25:
    print("It's a hot day!")
else:
    print("It's not too hot today.")

Now, if the temperature is 25 or below, the second message will be printed.


Using Elif for Multiple Conditions

Sometimes you have more than two possible outcomes. Instead of nesting multiple if statements, you can use elif (short for "else if").

if condition1:
    # code if condition1 is True
elif condition2:
    # code if condition2 is True
else:
    # code if neither condition is True

Here’s a practical example:

score = 85

if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
else:
    grade = 'D'

print(f"Your grade is {grade}")

This code assigns a grade based on the score. Notice that the conditions are checked in order, and as soon as one is true, the rest are skipped.


Combining Conditions

You can make more complex conditions using logical operators: and, or, and not.

  • and: Both conditions must be true.
  • or: At least one condition must be true.
  • not: Inverts the condition.

Example:

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive.")
else:
    print("You cannot drive.")

Only if both conditions are true will the person be allowed to drive.


Nested Conditionals

You can also place conditionals inside other conditionals. This is called nesting.

num = 10

if num > 0:
    if num % 2 == 0:
        print("Positive and even.")
    else:
        print("Positive and odd.")
else:
    print("Number is not positive.")

While nesting can be useful, overusing it can make your code hard to read. Often, using elif or combining conditions is cleaner.


Truthy and Falsy Values

In Python, conditions aren’t limited to boolean expressions. Many values are considered "truthy" or "falsy" in a boolean context.

Falsy values include: - False - None - Zero of any numeric type: 0, 0.0 - Empty sequences: "", [], () - Empty mappings: {}

Everything else is truthy.

Example:

name = ""

if name:
    print(f"Hello, {name}!")
else:
    print("Name is empty.")

Since name is an empty string (falsy), the else block runs.


One-Line If Statements

For very simple conditionals, you can use a one-liner:

x = 5
message = "Even" if x % 2 == 0 else "Odd"
print(message)

This is called a conditional expression (or ternary operator). It’s concise but best used for straightforward cases.


Common Pitfalls and Best Practices

When working with conditionals, watch out for these common mistakes:

  • Forgetting the colon : at the end of the condition.
  • Incorrect indentation (use 4 spaces consistently).
  • Using = (assignment) instead of == (equality check).
  • Overcomplicating conditions—sometimes breaking them into multiple lines or variables improves readability.

Also, keep your conditions simple. If a condition is too long, consider storing parts of it in variables:

# Instead of this:
if (user.age > 18 and user.has_license and not user.is_banned and user.insurance_valid):
    allow_driving()

# Do this:
is_eligible = (user.age > 18 and 
               user.has_license and 
               not user.is_banned and 
               user.insurance_valid)

if is_eligible:
    allow_driving()

Real-World Example: User Access Control

Let’s apply what we’ve learned to a practical scenario: controlling access based on user role and subscription.

user_role = "admin"
is_subscribed = True

if user_role == "admin":
    print("Full access granted.")
elif user_role == "user" and is_subscribed:
    print("Standard access granted.")
elif user_role == "user" and not is_subscribed:
    print("Please subscribe to access content.")
else:
    print("Access denied.")

This checks the user’s role and subscription status to determine the level of access.


Comparing Conditionals Across Scenarios

Here’s a table summarizing how different values are evaluated in conditions:

Value Boolean Evaluation Type
True True bool
False False bool
0 False int
1 (or any non-zero) True int
"" False str
"hello" True str
[] False list
[1, 2] True list
None False NoneType

Understanding these truthy/falsy evaluations helps you write more concise conditionals.


Using In for Membership Tests

Another useful tool in conditionals is the in keyword, which checks for membership in a sequence.

fruits = ["apple", "banana", "cherry"]

if "banana" in fruits:
    print("Yes, banana is in the list.")

You can also use not in:

if "orange" not in fruits:
    print("Orange is missing.")

This is much cleaner than writing a loop to check for membership.


Pattern Matching in Python 3.10+

Starting with Python 3.10, we have structural pattern matching using match and case. While it’s more powerful than traditional conditionals for certain use cases, it’s important to know the basics first.

Here’s a quick comparison:

# Using if-elif-else
status = 404

if status == 200:
    print("OK")
elif status == 404:
    print("Not Found")
else:
    print("Unknown status")

# Using match-case (Python 3.10+)
match status:
    case 200:
        print("OK")
    case 404:
        print("Not Found")
    case _:
        print("Unknown status")

While match is great, you’ll use if, elif, and else most of the time.


Practice Exercises

To reinforce your learning, try these exercises:

  1. Write a program that checks if a number is positive, negative, or zero.
  2. Create a login system that checks a username and password.
  3. Determine if a year is a leap year.
  4. Assign a discount based on purchase amount: 10% off over $100, 5% off over $50.

Experiment with these, and don’t be afraid to make mistakes—that’s how you learn!


Key Takeaways

  • Use if for single conditions, else for alternatives, and elif for multiple conditions.
  • Combine conditions with and, or, and not.
  • Remember truthy and falsy values to write concise code.
  • Avoid deep nesting; use elif or break conditions into variables.
  • Practice! The more you use conditionals, the more natural they become.

Conditional statements are the building blocks of decision-making in your code. With these tools, you can create programs that respond intelligently to different situations. Happy coding