Conditionals I

Introduction to Python Conditionals

In this lecture, you'll learn how to use Python conditional statements to make decisions and control the flow of your programs.


Imagine we have the following variable:

temperature = 75
Python

The value of this variable will most likely change over time.

Assume that we want to print a message if's is warm outside – let's say if the temperature is above 70.

That's where we use our first if statement. Run the code to see what happens:

temp = 75 print('The temperature is ', temp) if temp > 70: print("It's warm outside")
Python
Output

That's right, because the temperature is above 70, our program prints that it's warm outside.

Now, the temperature has changed. Let's see what happens:

temp = 60 print('The temperature is ', temp) if temp > 70: print("It's warm outside")
Python
Output

Since the temperature is not above 70, the print statement is not executed.

But how does it work?

The if-statement executes a block of code if a certain condition is true. It starts with the if keyword followed by a condition and a colon, and finally, an indented block of code.

if condition: # indented block of code
Python

Note that the indentation is crucial. The code inside the if block must be indented consistently. Typically, four spaces are used for indentation. I personally prefer to just hit the tab button once to indent a line of code.

Let's see what happens if we don't indent:

if 2 > 1: print('2 is greater than 1')
Python
Output

Let's check if you understood.


What will be the output?

num = 10 if num >= 10: num = num + 5 print(num)
Python

What will be the output?

is_true = False if is_true: is_true = True print(is_true)
Python

What will be the output?

is_true = False if is_true: is_true = True print(is_true)
Python