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?

Foam Seat Cushion

Aching back from coding all day? Try Back Problems

This foam seat cushion relieves lowerback pain, numbness and pressure sores by promoting healthy weight distribution, posture and spine alignment. Furthermore, it reduces pressure on the tailbone and hip bones while sitting. Perfect for sitting on the computer desk for long periods of time.

$ Check price
99.9599.95Amazon 4.5 logo(9,445+ 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