Contents

Python Quick Guide - Step 2 Control Flow (1) - Conditional Statements (1): if Statements

Info
  • This course is designed to help you learn the basics of Python programming as quickly as possible through hands-on practice.
  • The “Style Guide” sections primarily cover guidelines from PEP8 for writing clean Python code.
  • You can run and see the results of each code example.
    Feel free to experiment with the code - reloading the page will reset the content.

In the previous lessons under “Step 1 Basic Syntax and Data Types,” we learned about data types and their operations.
From this lesson onwards, we’ll explore “Step 2 Control Flow” - methods to control the flow of program execution.

Programs typically execute from top to bottom in sequence.
However, in real applications, there are processes we want to execute only when specific conditions are met, or processes we want to repeat.
The mechanisms that control such “program flow” are called control flow.

Conditional statements are control flow structures that execute specific processes only when certain conditions are met.

The if statement executes the code block only when the specified condition is True.

if statement
if condition: if-block
  • The indented block (above: print("Adult")) is executed only when the condition expression (above: age >= 18) evaluates to True
  • If the condition expression evaluates to False, that block is skipped
flowchart TD
    START[Start] --> IF{"if age >= 18"}

    %% Arrows from IF
    IF -->|False| NEXT[Next process]
    IF -->|True| IF_BLK["if block process\n(print('Adult'))"]

    IF_BLK --> NEXT
    
    linkStyle 1 stroke:red,stroke-width:2px;
    linkStyle 2 stroke:green,stroke-width:2px;
Style Guide
  • Add a line break immediately after the colon (:)
  • Standard indentation is 4 spaces
  • Add spaces before and after comparison operators (<, <=, etc.) in condition expressions
Column: Python Indentation

In Python, indentation is a crucial element that determines code structure.

While many other programming languages use curly braces {} to represent blocks,
Python treats code with the same indentation level as one block.

This makes code appearance neat and readable, but indentation mistakes can also cause errors.

Using the else clause, you can specify processes to execute when the condition is not met.

if-else statement
if condition: if-block else: else-block
  • When the condition expression is True, the if block is executed; when False, the else block is executed
  • Either if or else is always executed
flowchart TD
    START[Start] --> IF{"if age >= 18"}

    %% Arrows from IF
    IF -->|False| ELSE{"else"}
    IF -->|True| IF_BLK["if block process\n(print('Adult'))"]

    %% Arrows from ELSE
    ELSE --> ELSE_BLK["else block process\n(print('Minor'))"]


    ELSE_BLK --> NEXT[Next process]
    IF_BLK --> NEXT
    
    linkStyle 1 stroke:red,stroke-width:2px;
    linkStyle 2 stroke:green,stroke-width:2px;
    linkStyle 3 stroke:green,stroke-width:2px;
📚Exercise

Set a temperature value in the variable temperature, and create a program that outputs “Hot” if it’s 25 degrees or higher,
otherwise outputs “Cool”.

Sample Answer

When you want to check multiple conditions sequentially, use elif (short for else if).

if-elif-else statement
if condition1: if-block elif condition2: elif-block (1) elif condition3: elif-block (2) else: else-block
  • Conditions are evaluated from top to bottom, and only the block of the first True condition is executed
  • Even if multiple conditions become True, only the first True condition is adopted
  • The else block is executed only when all conditions are False
  • The else clause is optional (if omitted, nothing is executed when all conditions are False)
flowchart TD
    START["Start"] --> IF{"if [condition]"}

    %% Arrows from IF
    IF -->|False| ELIF{"elif [condition]"}
    IF -->|True| IF_BLK["if block process"]
  
    %% Arrows from ELIF
    ELIF -->|False| ELIF2{"elif [condition2]"}
    ELIF -->|True| ELIF_BLK["elif block process"]

    %% Arrows from ELIF2
    ELIF2 -->|False| ELSE{else}
    ELIF2 -->|True| ELIF2_BLK["elif block(2) process"]

    %% Arrows from ELSE
    ELSE --> ELSE_BLK["else block process"]

    %% Arrows to Next process
    ELSE_BLK --> NEXT["Next process"]
    ELIF2_BLK --> NEXT
    ELIF_BLK --> NEXT
    IF_BLK --> NEXT

    %% Arrow color specification
    linkStyle 1 stroke:red,stroke-width:2px
    linkStyle 2 stroke:green,stroke-width:2px
    linkStyle 3 stroke:red,stroke-width:2px
    linkStyle 4 stroke:green,stroke-width:2px
    linkStyle 5 stroke:red,stroke-width:2px
    linkStyle 6 stroke:green,stroke-width:2px
    linkStyle 7 stroke:green,stroke-width:2px
Order of Conditions

When using elif, the order of conditions is important.
If you place more restrictive conditions later, those conditions will be ignored.

📚Exercise

BMI (Body Mass Index) is a value calculated by dividing weight (kg) by the square of height (m).
Create a program that determines the BMI category based on BMI value.

Set a BMI value in the variable bmi and output the BMI category according to the following conditions:

  • Below 18.5: “Underweight”
  • 18.5 to under 25: “Normal weight”
  • 25 to under 30: “Obesity (Grade 1)”
  • 30 and above: “Obesity (Grade 2 or higher)”
Sample Answer

You can nest conditional statements inside other conditional statements.

  • Inner conditional statements are evaluated only when the outer condition is True
  • It’s important that indentation at each level is set correctly
flowchart TD
    START[Start] --> IF{"if age >= 18"}
    
    %% Outer if statement
    IF -->|False| ELSE{"else"}
    IF -->|True| IF_BLK["if block process\n(print('Adult'))"]

    ELSE --> ELSE_OUTER["else block process\n(print('Minors cannot enter'))"]
    
    %% Inner if statement
    IF_BLK --> INNER_IF{"if has_id"}
    INNER_IF -->|False| ELSE_INNER{"else"}
    INNER_IF -->|True| INNER_TRUE["inner if block process\n(print('ID verified. Entry allowed'))"]

    ELSE_INNER --> INNER_FALSE["inner else block process\n(print('No ID. Entry denied'))"]
    
    %% To next process
    ELSE_OUTER --> NEXT[Next process]
    INNER_FALSE --> NEXT
    INNER_TRUE --> NEXT
    
    %% Arrow color specification
    linkStyle 1 stroke:red,stroke-width:2px
    linkStyle 2 stroke:green,stroke-width:2px
    linkStyle 3 stroke:green,stroke-width:2px
    linkStyle 5 stroke:red,stroke-width:2px
    linkStyle 6 stroke:green,stroke-width:2px
    linkStyle 7 stroke:green,stroke-width:2px
Watch Nesting Depth
Deep nesting reduces code readability
Try to keep code as flat as possible (PEP20 (The Zen of Python))
📚Exercise: Simplifying Conditional Statements

You need to implement a discount system for a cafe. The conditions are as follows:

  • Members always get 10% discount
  • Orders of $10 or more get an additional 5% discount

Rewrite the following code to make it flatter.

Sample Answer

Related Content