Control Flow I: if, elif, else, match
শর্ত ও সিদ্ধান্ত — if, elif, else, match
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.
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.
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}")
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, None | Any other object |
0, 0.0, 0j | Non-zero numbers |
"" (empty string) | Non-empty strings |
[], {}, (), set() | Non-empty containers |
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.
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.
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 forif x = 5— unlike C where it silently assigns. - Dangling
else: theelsebelongs to the nearestifat the same indent level. - Checking against None: use
if x is None:, neverif x == None:. - Empty blocks: Python does not allow empty blocks — use
pass.
7. Vocabulary (শব্দভাণ্ডার)
| Term | Meaning | বাংলায় |
|---|---|---|
| Branch | A path the program can take. | প্রোগ্রামের একটি সম্ভাব্য পথ। |
| Condition | An expression that evaluates to True or False. | True বা False-এ evaluated হওয়া expression। |
| Ternary | One-line conditional expression. | এক-লাইনের conditional expression। |
| Pattern matching | Matching by structure, not just equality. | শুধু মান নয়, গঠন অনুযায়ী মিলানো। |
pass | A do-nothing statement to keep syntax valid. | কিছুই করে না, কিন্তু syntax বৈধ রাখে। |
8. Practice Problems
-
Write a program that prints "positive", "negative", or "zero" based on an integer input.Integer input নিয়ে "positive", "negative" বা "zero" প্রিন্ট করুন।
✨ Show Answer (উত্তর দেখুন)
ans1.pyn = int(input()) if n > 0: print("positive") elif n < 0: print("negative") else: print("zero") -
Given a year, check if it is a leap year.একটি বছর leap year কি না চেক করুন।
✨ Show Answer (উত্তর দেখুন)
ans2.pyy = 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'}") -
Using
match, translate HTTP status codes (200, 404, 500) into messages.matchব্যবহার করে HTTP status code-কে message-এ অনুবাদ করুন।✨ Show Answer (উত্তর দেখুন)
ans3.pydef 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)) -
Explain in two sentences the difference between
x = 5 if cond else 10and a full if/else block.ব্যাখ্যা করুন —x = 5 if cond else 10এবং সম্পূর্ণ if/else ব্লকের পার্থক্য।✨ Show Answer (উত্তর দেখুন)
Answer: The ternary
5 if cond else 10is an expression that produces a value — it can appear anywhere a value can, including inside f-strings, function calls, and list comprehensions. A fullif/elseblock is a statement — it performs actions but does not produce a value.Ternary একটি expression — একটি মান তৈরি করে, তাই যেকোনো জায়গায় ব্যবহার করা যায় (f-string, function call, comprehension-এর ভেতরেও)।
if/elseblock একটি statement — কাজ করে কিন্তু মান return করে না। -
Categorize a character as 'vowel', 'consonant', 'digit', or 'other'.একটি character কে 'vowel', 'consonant', 'digit', বা 'other' — এই চার শ্রেণিতে ভাগ করুন।
✨ Show Answer (উত্তর দেখুন)
ans5.pyc = 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.
if / elif / else; indentation দিয়ে block চেনানো হয়। Truthy/falsy-র সুবিধা নিয়ে clean condition লিখুন। ছোট value-producing শাখার জন্য ternary, আর multi-case dispatch-এর জন্য match / case ব্যবহার করুন।