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.")
else:
  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?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Python Programming

Learn to be a Pythonista! Try Python

This book is designed to be used as the primary textbook in a college-level first course in computing. It takes a fairly traditional approach, emphasizing problem solving, design, and programming as the core skills of computer science. However, these ideas are illustrated using a non-traditional language, namely Python.

$ Check price
45.9945.99Amazon 4.5 logo(211+ reviews)

More Python resources

Ad