If-else Statements in Python


TL ; DR:






Full lesson:

Many times in our life, not only we choose to do something if a condition is met, but also choose to do something different if that condition is not met. For example:

If I'm tired:
    I take a nap
Otherwise:
    I start coding

If-else Statements:

When a condition for an if statement is True, the block of code following it is executed. What about when that condition is False? Normally nothing would happen.

With an else statement, we can have an alternate block of code to be executed. For example:

am_tired = False
if am_tired:
    print("I take a nap")
else:
    print("I start coding")

The code above prints "I start coding" since the expression inside the if evaluates to False and so Python will enter the else statement and execute the code inside it.

An else statement cannot exist without a corresponding if statement. This combination is refered to as an if-else statement.


Assignment
Follow the Coding Tutorial and let's practice with if-else statements!


Hint
Look at the examples above if you get stuck.


Introduction

If-else statements are a fundamental part of programming that allow you to execute different blocks of code based on certain conditions. They are essential for making decisions in your code, enabling your program to react differently under varying circumstances. This concept is widely used in scenarios such as user authentication, data validation, and game development.

Understanding the Basics

At its core, an if-else statement evaluates a condition. If the condition is true, the code block under the if statement is executed. If the condition is false, the code block under the else statement is executed. Here is a simple example:

am_hungry = True
if am_hungry:
    print("I eat food")
else:
    print("I continue working")

In this example, since am_hungry is True, the output will be "I eat food".

Main Concepts

The key concepts in if-else statements include:

Here is a more detailed example:

temperature = 30
if temperature > 25:
    print("It's hot outside")
else:
    print("It's cool outside")

In this case, since temperature is greater than 25, the output will be "It's hot outside".

Examples and Use Cases

Let's look at some practical examples:

# Example 1: Checking if a number is positive or negative
number = -5
if number >= 0:
    print("The number is positive")
else:
    print("The number is negative")

# Example 2: User authentication
user_logged_in = False
if user_logged_in:
    print("Welcome back!")
else:
    print("Please log in")

In the first example, the output will be "The number is negative" because the number is less than 0. In the second example, the output will be "Please log in" because user_logged_in is False.

Common Pitfalls and Best Practices

Here are some common mistakes to avoid:

Best practices include:

Advanced Techniques

For more complex decision-making, you can use nested if-else statements or elif (else if) statements:

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: F")

In this example, the output will be "Grade: B" because the score is between 80 and 89.

Code Implementation

Here is a well-commented code snippet demonstrating the use of if-else statements:

# Check if a person is eligible to vote
age = 20

# If the person's age is 18 or older, they can vote
if age >= 18:
    print("You are eligible to vote")
else:
    # If the person's age is less than 18, they cannot vote
    print("You are not eligible to vote")

Debugging and Testing

When debugging if-else statements, consider the following tips:

For testing, you can write test cases to cover different scenarios:

def test_voting_eligibility():
    age = 20
    if age >= 18:
        assert "You are eligible to vote" == "You are eligible to vote"
    else:
        assert "You are not eligible to vote" == "You are not eligible to vote"

test_voting_eligibility()

Thinking and Problem-Solving Tips

When approaching problems involving if-else statements:

Conclusion

Mastering if-else statements is crucial for making decisions in your code. They are the building blocks for more complex logic and are widely used in various applications. Practice regularly to become proficient in using if-else statements effectively.

Additional Resources

For further reading and practice, consider the following resources: