01. Control flow if-elif-else statement

Control flow is how your program determines the flow of executed commands. With it, your program is able to repsond dynamically depending on user controls and other variables.

if statements

The if statement is the most basic of all control flow. It starts with one if, followed by any number of elifstatements. These keywords take in a conditional to evaluate and executes one chunk of code if the results are True, and moves onto the next statement if False. The if-statements may be terminated with an else.

if guess < 5:
  print("Too low.")
elif guess > 5:
  print("Too high.")
  print("Correct! The number was 5.")

Control flow syntax

Notice a few things that are different from other programming languages such as Java and C++.

  • There are no parantheses that wrap around the logical tests.
  • A colon (:) is placed at the end of if, elif and else statements.
  • There are indents instead of curly braces to group blocks of code.

It's very important that you indent properly in Python, as that is how the interpreter knows which block of code corresponds to which if-else block. Additionally, make sure to place colons at the end of any expression in Python!

Switch statements

Coming from Java or C++, you may be wondering if Python has a switch/case statements. Unfortunately, it does not, but we can get around this by using a dictionary mapping.

def numeral_to_roman(number):
  roman_numerals = {
    1: "I",
    2: "II",
    3: "III",
    4: "IV",
    5: "V",
  return roman_numerals(number, "Not found.")

This would be similar to a switch-case statement with cases 1, 2, 3, 4, 5, and a default value of Not found..

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Learning Python

Learn to be a Pythonista! Try Python

Get a comprehensive, in-depth introduction to the core Python language with this hands-on book. Based on author Mark Lutz's popular training course, this updated fifth edition will help you quickly write efficient, high-quality code with Python. It's an ideal way to begin, whether you're new to programming or a professional developer versed in other languages.

$ Check price
64.9964.99Amazon 4 logo(279+ reviews)

More Python resources