Start learning free

LESSON 73 OF 410 · CONDITIONAL STATEMENTS

If-else Statements in Python

Lesson

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