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..

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

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

Ad