Skip to content

Flow Control#

When we talked about flow control in Bash script, we looked at how you can change the direction of your code. Obviously, Python has the same features in the form of the if statement, but the syntax is a bit different:

1
2
3
4
5
6
>>> i_am_mike = True
>>> i_am_mike
True
>>> if i_am_mike: print("HEY MIKE!")
...
HEY MIKE!

That's an inline example (online meaning the whole if statement is on one line.) Multiple lines are obviously possibly:

1
2
3
4
5
6
7
8
9
i_am_mike = False
i_am_josh = True

if i_am_mike:
  print("HEY MIKE!")
elif i_am_josh:
  print("Hey it's Josh...!")
else:
  print("Oh... it's you... hi.")

We can use elif to include an else clause, allowing us to check multiple expressions in a single statement.

The expression between if and the final : is called an expression. You can use any valid expression here that resolves to true (True):

1
2
3
4
5
6
7
8
if 1 == 1:
  print("1 == 1")

if 1 <= 0:
  print("1 <= 0")

if i_am_mike == True and 1 > 0:
  print("Mike is here, and 1 is greater than 0! What a time to be alive.")

Simple, eh?