Menu
Courses / python basic / Control Flow

Control Flow

05 / 10 Part of python basic




 

    🔀 Topic 04 · Decisions
 

 


    Control Flow
 


 


    Use if/elif/else, match statements, and boolean logic to make your programs intelligent and responsive to data.
 


 

    ⏱ ~35 min
    🟢 Beginner
    🧠 Logic
 


 
 

   

     
     

if / elif / else


   

   

The most fundamental control structure: execute code only when a condition is true.


   

     

        if_else.py
     

     
score = 78

if score >= 90:
    print("Grade: A")
elif score >= 75:
    print("Grade: B"# ← This runs
elif score >= 60:
    print("Grade: C")
else:
    print("Grade: F")

   

   

      ⚠️ Indentation is the syntax
     

Python uses 4 spaces to define blocks — there are no curly braces. Inconsistent indentation causes an IndentationError.


   

 


 
 

   

     
     

Ternary (Inline) if


   

   

Write simple conditions on a single line using the ternary expression.


   

     

        ternary.py
     

     
age    = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult

   

 


 
 

   

     
     

match Statement (Python 3.10+)


   

   

Python's structural pattern matching is similar to switch/case in other languages, but far more powerful.


   

     

        match.py
     

     
command = "quit"

match command:
    case "start":
        print("Starting...")
    case "stop" | "quit":
        print("Stopping..."# ← Runs
    case _:
        print("Unknown command")

   

 


 
 

   

     
     

Nested Conditions


   

   

Conditions can be nested, but keep it shallow (max 2–3 levels) to preserve readability.


   

     

        nested.py
     

     
has_account = True
is_verified = False

if has_account:
    if is_verified:
        print("Welcome back!")
    else:
        print("Please verify your email")
else:
    print("Please sign up")