if

Now that you know about booleans, you can use them along with the if keyword to make decisions:

bufday_today = True
if bufday_today:
    print("happy bufday!")
else:
    print("go away")
happy bufday!

NOTE


The two print statements are indented. If the end of the current line ends in : and you press Enter, Thonny will automatically indent the following lines. When you type else:, you’ll have to first manually unindent that line by pressing Backspace. You can manually indent lines by pressing Tab.

print("happy bufday!") was ran because the expression after if (bufday_today in this case) evaluated to True. If bufday_today had been False, then print("go away") would’ve been run.

The simplest if statement goes like this:

if True:
	print("hello world!")
hello world!

As mentioned, the indented block of code only runs if the expression that comes after if is true:

if False:
	print("hello world!")
 

You can have as many lines of code in the block as you like:

if True:
    print("hello world!")
    foo = 7 + 9
    print(foo)
hello world!
16

You can use else to run a different block of code if the statement is false:

age = 15
if age >= 16:
    print("abc")
    print("you're old enough to drive.")
else:
    print(123)
    print("go away")
123
go away

NOTE


This section is the first time you’ve seen indented code. Whenever you see a : at the end of a line, it means one or more lines following will be indented. We do this a lot to organize code.

The empty space that comes before each indented line is important. Python uses it to know when a block of code ends. For example, notice the difference between this:

if 3 > 4:
    print('abc')
    print(123)
print('wow')

and this:

if 3 > 4:
    print('abc')
print(123)
print('wow')

(If you don’t see it, try running the code).


previous: boolean expressions next: exercises