Start learning free

LESSON 73 OF 410 · CONDITIONAL STATEMENTS

If-else Statements in Python

Lesson Read the full explanation

TL ; DR:

  • With an else statement, we can have an alternate block of code to be executed if the condition is not met. For example:

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

  • It is mandatory to start the line after the if and else statements with a tab! For example, this code:

    am_tired = False
    if am_tired:
        print("I take a nap")
    else:
    print("I start coding") # this produces an error
    

    would throw an IndentationError.



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.


STEP 1 OF 1
    Ctrl + Enter to check

    PYTHON · CONDITIONAL STATEMENTS

    If Else in Python, explained

    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:

    • Condition: A boolean expression that evaluates to either True or False.
    • If Block: The block of code that executes if the condition is true.
    • Else Block: The block of code that executes if the condition is false.

    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:

    • Indentation Errors: Python relies on indentation to define code blocks. Make sure your if and else blocks are properly indented.
    • Unreachable Code: Ensure that your conditions are logically sound so that all code paths are reachable.

    Best practices include:

    • Keep your conditions simple and readable.
    • Use comments to explain complex logic.
    • Test your code with different inputs to ensure all paths are working correctly.

    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:

    • Print the values of variables involved in the condition to ensure they are what you expect.
    • Use a debugger to step through your code and observe the flow of execution.

    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:

    • Break down the problem into smaller parts and tackle each condition individually.
    • Use flowcharts or pseudocode to visualize the decision-making process.
    • Practice with different scenarios to build a strong understanding of conditional logic.

    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:

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free