Control Flow I: if, elif, else, match

শর্ত ও সিদ্ধান্ত — if, elif, else, match

Read: ~25 min Beginner 5 practice problems Live code runner

1. Branching — Making Decisions in Code

A program that always does the same thing is not very useful. Control flow is how a program takes different paths based on the data it sees. The most fundamental tool is the if statement: do this if the condition is true; otherwise do something else.

যে প্রোগ্রাম সবসময় একই কাজ করে, সেটি বিশেষ কাজে আসে না। Control flow দিয়েই প্রোগ্রাম ডেটা অনুযায়ী বিভিন্ন পথ বেছে নেয়। সবচেয়ে মৌলিক টুল হলো if statement — শর্ত সত্য হলে এটি করো, না হলে ওটি।

2. The if / elif / else Chain

Python uses indentation — not {} braces — to group the body of a branch. The style guide (PEP 8) requires exactly 4 spaces. Never mix tabs and spaces.

grade.py
marks = int(input("Enter marks (0-100): "))

if marks >= 80:
    grade = "A+"
elif marks >= 70:
    grade = "A"
elif marks >= 60:
    grade = "A-"
elif marks >= 50:
    grade = "B"
elif marks >= 40:
    grade = "C"
else:
    grade = "F"

print(f"Marks {marks} → Grade {grade}")
Tip: Conditions are evaluated top to bottom. Place the most likely branch first for faster and more readable code. Use positive conditions when possible — if user.is_active reads better than if not user.is_inactive.

3. Truthy and Falsy Values

Any object can be used in an if. Python converts it to a bool using these rules:

Falsy (act as False)Truthy (act as True)
False, NoneAny other object
0, 0.0, 0jNon-zero numbers
"" (empty string)Non-empty strings
[], {}, (), set()Non-empty containers
truthy.py
items = []

# Pythonic — rely on truthiness
if items:
    print("has items")
else:
    print("empty")

# Not Pythonic — works but verbose
if len(items) == 0:
    print("empty (verbose)")

4. Ternary (Conditional) Expression

Python has a one-line conditional expression: x if cond else y.

ternary.py
age = 17
status = "adult" if age >= 18 else "minor"
print(status)

# In an f-string
n = -5
print(f"{n} is {'positive' if n > 0 else 'non-positive'}")

5. match / case — Structural Pattern Matching (Python 3.10+)

Added in Python 3.10 (PEP 634), match is far more powerful than C's switch — it can match shapes (tuples, dicts, classes), not just equal values. Use it when you have many cases to dispatch.

match_demo.py
def describe(point):
    match point:
        case (0, 0):
            return "Origin"
        case (0, y):
            return f"On Y-axis at y={y}"
        case (x, 0):
            return f"On X-axis at x={x}"
        case (x, y):
            return f"Point at ({x}, {y})"
        case _:
            return "Not a point"

for p in [(0, 0), (3, 0), (0, 4), (5, 6)]:
    print(describe(p))

6. Common Pitfalls

  • Comparing with == not =: Python raises SyntaxError for if x = 5 — unlike C where it silently assigns.
  • Dangling else: the else belongs to the nearest if at the same indent level.
  • Checking against None: use if x is None:, never if x == None:.
  • Empty blocks: Python does not allow empty blocks — use pass.

7. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
BranchA path the program can take.প্রোগ্রামের একটি সম্ভাব্য পথ।
ConditionAn expression that evaluates to True or False.True বা False-এ evaluated হওয়া expression।
TernaryOne-line conditional expression.এক-লাইনের conditional expression।
Pattern matchingMatching by structure, not just equality.শুধু মান নয়, গঠন অনুযায়ী মিলানো।
passA do-nothing statement to keep syntax valid.কিছুই করে না, কিন্তু syntax বৈধ রাখে।

8. Practice Problems

  1. Write a program that prints "positive", "negative", or "zero" based on an integer input.
    Integer input নিয়ে "positive", "negative" বা "zero" প্রিন্ট করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans1.py
    n = int(input())
    if n > 0:
        print("positive")
    elif n < 0:
        print("negative")
    else:
        print("zero")
  2. Given a year, check if it is a leap year.
    একটি বছর leap year কি না চেক করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans2.py
    y = int(input())
    leap = (y % 4 == 0 and y % 100 != 0) or y % 400 == 0
    print(f"{y} is {'a leap year' if leap else 'not a leap year'}")
  3. Using match, translate HTTP status codes (200, 404, 500) into messages.
    match ব্যবহার করে HTTP status code-কে message-এ অনুবাদ করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans3.py
    def describe(code):
        match code:
            case 200: return "OK"
            case 404: return "Not Found"
            case 500: return "Server Error"
            case _:   return "Unknown"
    
    for c in [200, 404, 500, 418]:
        print(c, describe(c))
  4. Explain in two sentences the difference between x = 5 if cond else 10 and a full if/else block.
    ব্যাখ্যা করুন — x = 5 if cond else 10 এবং সম্পূর্ণ if/else ব্লকের পার্থক্য।
    ✨ Show Answer (উত্তর দেখুন)

    Answer: The ternary 5 if cond else 10 is an expression that produces a value — it can appear anywhere a value can, including inside f-strings, function calls, and list comprehensions. A full if/else block is a statement — it performs actions but does not produce a value.

    Ternary একটি expression — একটি মান তৈরি করে, তাই যেকোনো জায়গায় ব্যবহার করা যায় (f-string, function call, comprehension-এর ভেতরেও)। if/else block একটি statement — কাজ করে কিন্তু মান return করে না।

  5. Categorize a character as 'vowel', 'consonant', 'digit', or 'other'.
    একটি character কে 'vowel', 'consonant', 'digit', বা 'other' — এই চার শ্রেণিতে ভাগ করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans5.py
    c = input().lower()
    
    if c in "aeiou":
        print("vowel")
    elif c.isalpha():
        print("consonant")
    elif c.isdigit():
        print("digit")
    else:
        print("other")

Summary — Module 09

Python's branching centers on if / elif / else with indentation defining blocks. Embrace truthy/falsy values for clean conditions. Use the ternary x if cond else y for short value-producing branches. For multi-case dispatch on structure, Python 3.10's match / case is a powerful modern tool.

Python-এর decision-making-এর ভিত্তি if / elif / else; indentation দিয়ে block চেনানো হয়। Truthy/falsy-র সুবিধা নিয়ে clean condition লিখুন। ছোট value-producing শাখার জন্য ternary, আর multi-case dispatch-এর জন্য match / case ব্যবহার করুন।

Next Module → Control Flow II — while, for, break, continue।