Start learning free

LESSON 72 OF 410 · CONDITIONAL STATEMENTS

If Statements in Python

Lesson

TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    is_rainy = True
    if is_rainy:
      print("I bring an umbrella")
    

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

    am_hungry = False
    if am_hungry:
    print("I have breakfast") # this produces an error
    

    would throw an IndentationError.



Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast
  
I I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if conditions:
  # instructions

The keyword if tells Python to execute the indented code coming after the colon : (where we have our Python comment) only if the conditions are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be True or False.

If the boolean condition evaluates to True, the program executes the indented code coming after the colon. If it evaluates to False, that code will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

is_rainy = True
if is_rainy:
  print("I bring an umbrella")

The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to True

But this code:

am_hungry = False
if am_hungry:
  print("I have breakfast")

prints nothing since amHungry evaluates to False.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check