The Story That Explains Control Flow 🛣️Control Flow समझाने वाली कहानी 🛣️一个解释控制流的故事 🛣️
Without it, a program is one straight line: instruction 1, instruction 2, instruction 3, done. Real programs need to decide. Should I send this email or wait? Is the user logged in or a guest? Is this number positive, negative or zero? Every decision is a fork, and every fork is written with if, elif and else.
Master this trio and you can read the shape of almost any program. Loops and functions build on the same idea: they decide what runs, and when.
इसके बिना program एक सीधी रेखा है: instruction 1, instruction 2, instruction 3, ख़त्म। असली programs को फ़ैसला करना होता है। यह email अभी भेजूँ या रुकूँ? User logged in है या guest? यह संख्या positive है, negative या zero? हर फ़ैसला एक दोराहा है, और हर दोराहा if, elif और else से लिखा जाता है।
इस तिकड़ी में माहिर हो जाइए, तो आप लगभग किसी भी program का ढाँचा पढ़ सकते हैं। Loops और functions भी इसी विचार पर बने हैं: वे तय करते हैं कि क्या और कब चले।
没有它,程序就是一条直线:指令 1、指令 2、指令 3,结束。真正的程序需要做决定:这封邮件现在发还是等一等?用户已登录还是游客?这个数是正数、负数还是零?每个决定都是一个岔路口,而每个岔路口都用 if、elif 和 else 来写。
掌握这三个关键字,你几乎能看懂任何程序的结构。循环和函数也建立在同样的思想上:决定什么代码执行、何时执行。
ifif.if से शुरू होता है।if 开始。elifelseif and elif above was False. Optional, but often used as the default case.if और elif False हों। ज़रूरी नहीं, पर अक्सर default case के रूप में इस्तेमाल होता है।if 和 elif 都为 False 时才执行。可选,但常用作默认情况。This lesson has five live "Try It" runners. Type a value in the yellow box, then press Step to run one line at a time, Play to watch it run by itself, or Run to jump to the end. The highlighted line is the one Python is running now. Watch VARIABLES and OUTPUT change, and follow the coloured path in the flowchart: green = True, red = False. At the end, the lines and boxes that never ran fade out.
इस lesson में पाँच live "ख़ुद आज़माएँ" runners हैं। पीले box में एक मान लिखें, फिर एक-एक line चलाने के लिए Step, अपने आप चलते देखने के लिए Play, या सीधे अंत तक जाने के लिए चलाएँ दबाएँ। Highlighted line वह है जिसे Python अभी चला रहा है। VARIABLES और OUTPUT को बदलते देखें, और flowchart में रंगीन रास्ता देखें: हरा = True, लाल = False। अंत में जो lines और boxes कभी नहीं चले, वे धुंधले हो जाते हैं।
本课有五个“动手试试”运行器。在黄色框中输入一个值,然后点击单步逐行运行,点击播放观看自动运行,或点击运行直接跳到结尾。高亮的行就是 Python 正在执行的行。观察变量和输出的变化,并跟随流程图中的彩色路径:绿色 = True,红色 = False。结束时,从未执行的行和方框会变淡。
The Simple if Statement ❓साधारण if Statement ❓简单的 if 语句 ❓
The simplest control-flow structure is a single if. You write a condition. If it is True, the indented block runs. If it is False, the block is skipped and the program continues below.
सबसे सरल control-flow ढाँचा एक अकेला if है। आप एक condition लिखते हैं। अगर वह True है, तो indented block चलता है। अगर False है, तो block छूट जाता है और program नीचे जारी रहता है।
最简单的控制流结构是单个 if。你写一个条件:为 True 时执行缩进的代码块;为 False 时跳过该块,程序继续往下执行。
age = 21
if age >= 18:
print("You can vote.")
print("You can sign a contract.")
print("Program continues here.")
The Anatomy of an if Statementif Statement की बनावटif 语句的结构
Unlike C or Java, Python uses indentation to define code blocks — not braces. Everything indented under an if belongs to it. Break the indentation and the meaning changes. Use 4 spaces (never mix tabs and spaces), and let your editor indent for you.
C या Java के उलट, Python code blocks तय करने के लिए braces नहीं, indentation इस्तेमाल करता है। if के नीचे indented सब कुछ उसी का है। Indentation बिगाड़ें तो अर्थ बदल जाता है। 4 spaces इस्तेमाल करें (tabs और spaces कभी न मिलाएँ), और editor को indent करने दें।
与 C 或 Java 不同,Python 用缩进而不是花括号来界定代码块。if 下面缩进的内容都属于它。缩进一乱,含义就变了。使用 4 个空格(绝不混用 tab 和空格),让编辑器帮你缩进。
Two Paths — if / else 🔀दो रास्ते — if / else 🔀两条路 —— if / else 🔀
Real decisions almost always have a "what if not?" branch. That is what else is for. Exactly one of the two blocks runs — never both, never neither.
असली फ़ैसलों में लगभग हमेशा "अगर नहीं तो?" वाली शाखा होती है। else इसी के लिए है। दोनों में से ठीक एक block चलता है — कभी दोनों नहीं, और कभी ऐसा नहीं कि कोई न चले।
真实的决定几乎总有“如果不是呢?”这一分支,else 就是为此而设的。两个代码块中恰好执行一个 —— 不会两个都执行,也不会一个都不执行。
score = 75
if score >= 60:
print("Pass")
else:
print("Fail")
# common pattern: a default when the input is empty
name = input("Your name: ")
if name:
print(f"Hello, {name}!")
else:
print("Hello, stranger!")
The second part was run twice: once pressing Enter with no name (empty string → falsy → else), once typing Asha.
दूसरा हिस्सा दो बार चलाया गया: एक बार बिना नाम Enter दबाकर (ख़ाली string → falsy → else), एक बार Asha लिखकर।
第二部分运行了两次:一次不输入名字直接回车(空字符串 → 假值 → else),一次输入 Asha。
Many Paths — if / elif / else 🪜कई रास्ते — if / elif / else 🪜多条路 —— if / elif / else 🪜
Life rarely fits into two boxes. A test score is not just "pass or fail" — it is A, B, C, D or F. That is where elif shines: a chain of decisions checked in order, top to bottom. The first condition that is True runs its block, and Python skips the rest.
ज़िंदगी शायद ही दो खानों में बँटती है। Test score सिर्फ़ "pass या fail" नहीं — वह A, B, C, D या F है। यहीं elif काम आता है: फ़ैसलों की एक chain जो क्रम से, ऊपर से नीचे जाँची जाती है। जो condition पहली True हो, उसका block चलता है, और Python बाक़ी छोड़ देता है।
生活很少只分成两类。考试成绩不只是“及格或不及格”,而是 A、B、C、D 或 F。这正是 elif 的用武之地:一串按从上到下顺序检查的判断。第一个为 True 的条件执行它的代码块,Python 跳过其余的。
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Score: {score} → Grade: {grade}")
Python stops at the first True. With score = 95, the test score >= 90 matches first, so it gets "A" and Python never checks score >= 80. Reverse the order and 95 gets a "D" — as this real run shows:
Python पहले True पर रुक जाता है। score = 95 होने पर score >= 90 पहले मेल खाता है, इसलिए "A" मिलता है और Python score >= 80 कभी नहीं जाँचता। क्रम उलट दें तो 95 को "D" मिलता है — जैसा यह असली run दिखाता है:
Python 在第一个 True 处停止。score = 95 时,score >= 90 最先匹配,所以得到 "A",Python 根本不会检查 score >= 80。把顺序反过来,95 就会得到 "D" —— 如下面的真实运行所示:
# the SAME checks in the wrong order: loosest first
score = 95
if score >= 60:
grade = "D"
elif score >= 70:
grade = "C"
elif score >= 90:
grade = "A"
else:
grade = "F"
print(f"Score: {score} → Grade: {grade}") # wrong!
Truthiness — What Counts as True? ✅Truthiness — True क्या गिना जाता है? ✅真值 —— 什么算作 True?✅
The condition after if does not have to be True or False itself. Python treats every value as true or false using rules called truthiness. This lets you write short checks like if name: or if items:.
if के बाद की condition का ख़ुद True या False होना ज़रूरी नहीं। Python truthiness नाम के नियमों से हर मान को true या false मानता है। इससे आप if name: या if items: जैसी छोटी जाँचें लिख सकते हैं।
if 后面的条件本身不必是 True 或 False。Python 按照名为真值(truthiness)的规则,把每个值当作真或假。这样你就能写出 if name:、if items: 这样简短的判断。
| Valueमान值 | Type |
|---|---|
| False | bool |
| None | NoneType |
| 0, 0.0, 0j | numeric zeroसंख्यात्मक शून्य数值零 |
| "" | empty stringख़ाली string空字符串 |
| [] | empty listख़ाली list空列表 |
| () | empty tupleख़ाली tuple空元组 |
| {} | empty dictख़ाली dict空字典 |
| set() | empty setख़ाली set空集合 |
| Valueमान值 | Whyक्यों原因 |
|---|---|
| True | the constant itselfख़ुद constant常量本身 |
| 1, -1, 42, 3.14 | any non-zero numberकोई भी non-zero संख्या任何非零数 |
| "hello" | non-empty stringnon-empty string非空字符串 |
| " " | even a space is non-empty!एक space भी non-empty है!一个空格也是非空! |
| [0] | a list with any itemकोई भी item वाली list含任意元素的列表 |
| {"a": 1} | non-empty dictnon-empty dict非空字典 |
| (0,) | a tuple with any itemकोई भी item वाला tuple含任意元素的元组 |
name = ""
if name: # "" is falsy → skip
print(f"Hi, {name}")
else:
print("No name given")
items = []
if items: # empty list → False → skip
print("Processing items...")
else:
print("Nothing to do.")
for value in [0, "", [], None, -1, "False", " ", [0]]:
print(f"bool({value!r}) = {bool(value)}")
Pick a value for x and see which branch of the if/else runs. Each result comes from running the code on Python 3.13.16.
x के लिए एक मान चुनें और देखें if/else की कौन सी शाखा चलती है। हर नतीजा Python 3.13.16 पर code चलाकर मिला है।
为 x 选择一个值,看看 if/else 的哪个分支会执行。每个结果都来自在 Python 3.13.16 上实际运行代码。
bool("False") is True, because "False" is a five-letter string, not the boolean. If you read user input and check if answer:, typing anything at all counts as True — even "no". Compare explicitly: if answer.strip().lower() == "yes":.
bool("False") True है, क्योंकि "False" पाँच अक्षरों वाली string है, boolean नहीं। अगर आप user input पढ़कर if answer: जाँचते हैं, तो कुछ भी लिखना True गिना जाता है — "no" भी। साफ़ तुलना करें: if answer.strip().lower() == "yes":।
bool("False") 为 True,因为 "False" 是一个五个字母的字符串,而不是布尔值。如果读取用户输入后判断 if answer:,那么输入任何内容都算 True —— 连 "no" 也是。请显式比较:if answer.strip().lower() == "yes":。
Building Conditions — Comparison Operators ⚖️Conditions बनाना — Comparison Operators ⚖️构建条件 —— 比较运算符 ⚖️
The heart of every if is a condition, and conditions are built from comparison operators. They compare two values and give True or False.
हर if का दिल एक condition है, और conditions comparison operators से बनती हैं। ये दो मानों की तुलना करके True या False देते हैं।
每个 if 的核心是条件,而条件由比较运算符构成。它们比较两个值,得出 True 或 False。
| OperatorOperator运算符 | Meaningअर्थ含义 | Exampleउदाहरण例子 | Resultनतीजा结果 |
|---|---|---|---|
| == | Equal toबराबर等于 | 5 == 5 | True |
| != | Not equal toबराबर नहीं不等于 | 5 != 3 | True |
| > | Greater thanसे बड़ा大于 | 7 > 3 | True |
| < | Less thanसे छोटा小于 | 7 < 3 | False |
| >= | Greater or equalबड़ा या बराबर大于等于 | 5 >= 5 | True |
| <= | Less or equalछोटा या बराबर小于等于 | 4 <= 5 | True |
| in | MembershipMembership成员 | 3 in [1, 2, 3] | True |
| not in | Non-membershipNon-membership非成员 | "x" not in "abc" | True |
| is | Identity (same object)Identity (वही object)身份(同一对象) | a is None | use for NoneNone के लिए用于 None |
Chained Comparisons — Python's Sweet TrickChained Comparisons — Python की प्यारी trick链式比较 —— Python 的妙招
age = 25
if age >= 18 and age <= 65:
print("Working age")
if 18 <= age <= 65: # chained: same meaning, reads like maths
print("Working age")
x = 42
if 0 < x < 100: # between 0 and 100 (both ends excluded)
print("in range")
print("abc" == "abc") # == compares values
value = None
if value is None: # the correct way to test for None
print("no value")
Two classic mistakes stop the program before it starts. Python even tells you how to fix the first one:
दो पुरानी ग़लतियाँ program को शुरू होने से पहले ही रोक देती हैं। पहली का सुधार तो Python ख़ुद बताता है:
两个经典错误会让程序在开始前就停止。第一个错误 Python 甚至会告诉你怎么改:
age = 18
if age = 18:
print("adult")
x = 5
if x > 0
print("positive")
Combining Conditions — and, or, not 🧠Conditions जोड़ना — and, or, not 🧠组合条件 —— and、or、not 🧠
Real decisions often depend on more than one thing. Python's three logical operators combine conditions: and (both must be True), or (at least one must be True) and not (flip True ↔ False).
असली फ़ैसले अक्सर एक से ज़्यादा बातों पर निर्भर होते हैं। Python के तीन logical operators conditions जोड़ते हैं: and (दोनों True हों), or (कम से कम एक True हो) और not (True ↔ False उलटें)।
真实的决定往往取决于不止一件事。Python 的三个逻辑运算符用来组合条件:and(两边都要为 True)、or(至少一边为 True)和 not(True ↔ False 取反)。
A and B is True only when both are True. If A is False, Python does not even check B — this is short-circuit evaluation.A and B तभी True है जब दोनों True हों। अगर A False है, तो Python B को जाँचता ही नहीं — इसे short-circuit evaluation कहते हैं।A and B 只有两边都为 True 时才为 True。如果 A 为 False,Python 根本不检查 B —— 这叫短路求值。A or B is True when either side is True. If A is True, Python skips B. Use it for "any of these will do", like weekend or holiday.A or B तब True है जब कोई भी तरफ़ True हो। A True हो तो Python B छोड़ देता है। "इनमें से कोई भी चलेगा" के लिए इस्तेमाल करें, जैसे weekend या holiday।A or B 就为 True。如果 A 为 True,Python 跳过 B。用于“满足其一即可”的情况,比如周末或节假日。not A gives the opposite. if not user.active: reads better than if user.active == False:.not A उल्टा देता है। if not user.active:, if user.active == False: से बेहतर पढ़ता है।not A 得到相反的值。if not user.active: 比 if user.active == False: 更易读。age = 25
has_license = True
if age >= 18 and has_license:
print("Can drive")
day = "Saturday"
is_holiday = False
if day == "Saturday" or day == "Sunday" or is_holiday:
print("Day off!")
if day in ("Saturday", "Sunday") or is_holiday: # cleaner with 'in'
print("Day off!")
logged_in = False
if not logged_in:
print("Please log in")
if (age >= 18 and age < 65) or not is_holiday:
print("Working hours apply")
Short-Circuit Evaluation — A Free Safety NetShort-Circuit Evaluation — एक मुफ़्त सुरक्षा जाल短路求值 —— 免费的安全网
Python stops as soon as it knows the answer. That makes the order of your checks important: put the safe check first. The last part of this program shows what happens when you get the order wrong:
जवाब पता चलते ही Python रुक जाता है। इसलिए जाँचों का क्रम ज़रूरी है: सुरक्षित जाँच पहले रखें। इस program का आख़िरी हिस्सा दिखाता है कि क्रम ग़लत होने पर क्या होता है:
Python 一旦知道答案就会停止。因此检查的顺序很重要:把安全的检查放在前面。这个程序的最后一部分展示了顺序写错时会发生什么:
class User:
def __init__(self, name):
self.name = name
user = None
if user and user.name == "Asha": # safe: user.name is never read when user is None
print("Hi Asha")
else:
print("No user")
name = ""
display = name or "Anonymous" # "" is falsy → use the default
print(display)
config = {"host": "localhost"}
port = config.get("port") or 8080 # fallback when the key is missing
print(port)
try:
if user.name == "Asha" and user: # wrong order: reads user.name first
pass
except AttributeError as err:
print("AttributeError:", err)
When mixing operators: comparisons happen first, then not, then and, then or. When in doubt, add brackets — (a > 0 and b > 0) or c > 0 reads better than relying on memory.
Operators मिलाते समय: पहले comparisons, फिर not, फिर and, फिर or। शक हो तो brackets लगाएँ — (a > 0 and b > 0) or c > 0 याद पर भरोसे से बेहतर पढ़ता है।
混用运算符时:先比较,再 not,再 and,最后 or。拿不准就加括号 —— (a > 0 and b > 0) or c > 0 比靠记忆更清楚。
Nested if — Decisions Inside Decisions 🪆Nested if — फ़ैसलों के अंदर फ़ैसले 🪆嵌套 if —— 决定中的决定 🪆
You can put an if inside another if. This is nesting. It is useful when the second question only makes sense after the first one has been answered.
आप एक if को दूसरे if के अंदर रख सकते हैं। इसे nesting कहते हैं। यह तब काम आता है जब दूसरा सवाल पहले का जवाब मिलने के बाद ही समझ में आता हो।
你可以把一个 if 放进另一个 if 里,这叫嵌套。当第二个问题只有在第一个问题有了答案之后才有意义时,嵌套就很有用。
logged_in = True
is_admin = False
if logged_in:
print("Welcome back!")
if is_admin:
print("Admin panel available")
else:
print("Standard user view")
else:
print("Please log in first")
When to Flatten Nested ConditionsNested Conditions को कब सपाट करें何时把嵌套条件展平
Deep nesting is hard to read and easy to get wrong. You can often flatten it with and, or use guard clauses — early returns that handle the bad cases first.
गहरी nesting पढ़ने में कठिन और ग़लती करने में आसान है। अक्सर आप इसे and से सपाट कर सकते हैं, या guard clauses इस्तेमाल कर सकते हैं — जल्दी वाले return जो बुरे मामलों को पहले संभालते हैं।
深层嵌套难读又容易出错。通常可以用 and 把它展平,或使用守卫子句 —— 先用提前 return 处理不正常的情况。
| CodeCode代码 |
|---|
| if user: |
| if user.active: |
| if user.role == "admin": |
| grant_access() |
| Three levels of indentation just to grant access.सिर्फ़ access देने के लिए तीन level का indentation।仅仅为了授权就缩进了三层。 |
| CodeCode代码 |
|---|
| if user and user.active and user.role == "admin": |
| grant_access() |
| One level, one condition, clear intent. Short-circuiting keeps it safe.एक level, एक condition, साफ़ इरादा। Short-circuiting इसे सुरक्षित रखता है।一层缩进、一个条件、意图清晰。短路求值保证了安全。 |
from types import SimpleNamespace as Order
def ship(order):
print(f"Shipping {len(order.items)} item(s)")
def process(order):
if not order:
print("No order")
return
if not order.paid:
print("Not paid")
return
if not order.items:
print("No items")
return
ship(order) # the "happy path" stays flat
process(None)
process(Order(paid=False, items=["pen"]))
process(Order(paid=True, items=[]))
process(Order(paid=True, items=["pen", "book"]))
The Ternary Expression — if in One Line ⚡Ternary Expression — एक line में if ⚡三元表达式 —— 一行写 if ⚡
For simple two-way choices, Python has a compact conditional expression (often called the ternary operator). It fits on one line and gives back a value, so you can use it in assignments and function calls.
सरल दो-तरफ़ा फ़ैसलों के लिए Python में एक छोटा conditional expression है (जिसे अक्सर ternary operator कहते हैं)। यह एक line में आता है और एक मान लौटाता है, इसलिए assignments और function calls में इस्तेमाल हो सकता है।
对于简单的二选一,Python 提供了紧凑的条件表达式(常称为三元运算符)。它写在一行内并返回一个值,因此可以用在赋值和函数调用中。
age = 20
if age >= 18:
status = "adult"
else:
status = "minor"
status = "adult" if age >= 18 else "minor" # the same, in one line
print(status)
print(f"You are an {'adult' if age >= 18 else 'minor'}.")
total, count = 0, 0
avg = total / count if count > 0 else 0 # never divides by zero
print(avg)
def greet(name=None):
display = name if name else "stranger"
print(f"Hello, {display}")
greet()
greet("Asha")
Do not nest ternaries. If you find yourself writing a if x else b if y else c, stop and use a proper if-elif-else — it will be much easier to read next week. The ternary is for quick two-way choices.
Ternaries को nest न करें। अगर आप a if x else b if y else c लिखने लगें, तो रुकें और सही if-elif-else इस्तेमाल करें — अगले हफ़्ते पढ़ना कहीं आसान होगा। Ternary झटपट दो-तरफ़ा फ़ैसलों के लिए है।
不要嵌套三元表达式。如果你发现自己在写 a if x else b if y else c,请停下来改用完整的 if-elif-else —— 下周再读会容易得多。三元表达式只适合快速的二选一。
The match Statement — Python’s Modern Alternative 🧩match Statement — Python का आधुनिक विकल्प 🧩match 语句 —— Python 的现代替代方案 🧩
Since Python 3.10, there is another decision tool: match. It compares one value against several patterns — like a switch statement in other languages, but more powerful. For fixed values it is cleaner than a long elif chain. case _: is the default, like else.
Python 3.10 से फ़ैसले का एक और औज़ार है: match। यह एक मान को कई patterns से मिलाता है — दूसरी भाषाओं के switch statement जैसा, पर ज़्यादा ताक़तवर। तय मानों के लिए यह लंबी elif chain से साफ़ है। case _: default है, else की तरह।
从 Python 3.10 起,有了另一个决策工具:match。它把一个值与多个模式比较 —— 类似其他语言的 switch 语句,但更强大。对于固定值,它比长长的 elif 链更清晰。case _: 是默认分支,类似 else。
def http_status(code):
match code:
case 200:
return "OK"
case 301:
return "Moved"
case 404:
return "Not Found"
case 500:
return "Server Error"
case _: # the default case
return "Unknown"
def day_kind(day):
match day:
case "Saturday" | "Sunday":
return "weekend"
case "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday":
return "weekday"
case _:
return "unknown"
for code in (200, 404, 418):
print(code, http_status(code))
for day in ("Sunday", "Monday", "Funday"):
print(day, day_kind(day))
Patterns and GuardsPatterns और Guards模式与守卫
match can also look inside data. A pattern like (0, y) checks the shape of a tuple and pulls out a value into y. A guard — an if after the pattern — adds an extra condition.
match data के अंदर भी देख सकता है। (0, y) जैसा pattern tuple का आकार जाँचता है और एक मान निकालकर y में रखता है। Guard — pattern के बाद एक if — एक अतिरिक्त condition जोड़ता है।
match 还能查看数据内部。(0, y) 这样的模式会检查元组的形状,并把一个值取出放进 y。守卫 —— 模式后面的 if —— 再增加一个条件。
def describe(point):
match point:
case (0, 0):
return "origin"
case (0, y):
return f"on the y-axis at {y}"
case (x, 0):
return f"on the x-axis at {x}"
case (x, y) if x == y: # a guard: an extra if inside a case
return f"on the diagonal at {x}"
case (x, y):
return f"somewhere else: ({x}, {y})"
for p in [(0, 0), (0, 5), (3, 0), (4, 4), (2, 7)]:
print(p, "→", describe(p))
Pick a point. Python tries each case from the top: ✗ marks cases it tried and rejected, ✓ is the one that ran. Results come from running the code.
एक point चुनें। Python ऊपर से हर case आज़माता है: ✗ वे cases हैं जो आज़माकर छोड़े गए, ✓ वह जो चला। नतीजे code चलाकर मिले हैं।
选择一个点。Python 从上往下尝试每个 case:✗ 表示尝试过但被排除的 case,✓ 表示实际执行的那个。结果来自实际运行代码。
Use if / elif / else for ranges and boolean logic (score >= 90, a and b). Use match when you compare one value against a fixed set of options, or when you want to take data apart by its shape. match needs Python 3.10 or newer.
Ranges और boolean logic (score >= 90, a and b) के लिए if / elif / else लगाएँ। जब एक मान को तय विकल्पों से मिलाना हो, या data को उसके आकार से खोलना हो, तब match लगाएँ। match के लिए Python 3.10 या नया चाहिए।
处理范围和布尔逻辑(score >= 90、a and b)时用 if / elif / else。把一个值与一组固定选项比较,或按结构拆解数据时,用 match。match 需要 Python 3.10 或更高版本。
Common Traps and How to Avoid Them 🪤आम जाल और उनसे कैसे बचें 🪤常见陷阱及如何避免 🪤
Here are traps 4 and 6 for real:
जाल 4 और 6 असल में:
陷阱 4 和 6 的真实演示:
x = 75
if x > 60:
print("over 60")
elif x > 70: # never reached: x > 60 already caught it
print("over 70")
x = 1000
print(x is 1000) # True here — but Python warns, and the REPL may say False
Complete Practice Program — Smart Grader 🎓पूरा अभ्यास Program — Smart Grader 🎓完整练习程序 —— 智能评分器 🎓
This program uses every idea from the lesson: an elif chain, a ternary, and, guard clauses and a chained comparison.
यह program lesson का हर विचार इस्तेमाल करता है: elif chain, ternary, and, guard clauses और chained comparison।
这个程序用到了本课的所有内容:elif 链、三元表达式、and、守卫子句和链式比较。
# grader.py — every control-flow concept in one program
def letter_grade(score):
"""Convert numeric score to letter grade using elif chain."""
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"
def is_passing(score):
"""Ternary expression — one-line if/else."""
return "Passed" if score >= 60 else "Failed"
def honors_status(score, attendance):
"""Combine multiple conditions with 'and'."""
if score >= 95 and attendance >= 95:
return "Highest Honors"
elif score >= 90 and attendance >= 90:
return "Honors"
else:
return "Regular"
def validate(score):
"""Guard clauses — early exits."""
if not isinstance(score, (int, float)):
return "Error: score must be a number"
if score < 0 or score > 100:
return "Error: score out of range"
return None # no error
def analyze(student):
name, score, attendance = student
line = "─" * 45
print(f"{line}\n {name}")
# Guard clause — validate first
error = validate(score)
if error:
print(f" {error}")
return
grade = letter_grade(score)
status = is_passing(score)
honors = honors_status(score, attendance)
# Chained comparison
if 70 <= score <= 89:
note = "Solid effort — room to grow"
elif score >= 90:
note = "Excellent work!"
else:
note = "Needs improvement"
print(f" Score: {score}")
print(f" Grade: {grade}")
print(f" Status: {status}")
print(f" Attendance: {attendance}%")
print(f" Honors: {honors}")
print(f" Note: {note}")
def main():
students = [
("Alice", 96, 98),
("Bob", 72, 85),
("Carol", 58, 70),
("Dan", 88, 92),
("Erin", 150, 95), # invalid — guard catches this
]
for student in students:
analyze(student)
if __name__ == "__main__":
main()
Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆
Six questions on the traps in this lesson. Pick an answer to see why.
इस lesson के जालों पर छह सवाल। जवाब चुनें और कारण देखें।
六道关于本课陷阱的题目。选择答案查看解释。
Control flow is how a program decides. if asks a question, elif asks the next one only when needed, and else catches the rest — and exactly one branch runs. Conditions can be any value (truthiness), combined with and/or/not, which stop early. Keep decisions flat with and and guard clauses, use the ternary for quick choices, and reach for match when one value has many fixed options.
Control flow वह तरीक़ा है जिससे program फ़ैसला करता है। if सवाल पूछता है, elif ज़रूरत होने पर ही अगला पूछता है, और else बाक़ी सब पकड़ता है — और ठीक एक शाखा चलती है। Conditions कोई भी मान हो सकती हैं (truthiness), जिन्हें and/or/not से जोड़ा जाता है, जो जल्दी रुक जाते हैं। and और guard clauses से फ़ैसले सपाट रखें, झटपट फ़ैसलों के लिए ternary लगाएँ, और जब एक मान के कई तय विकल्प हों तो match इस्तेमाल करें।
控制流就是程序做决定的方式。if 提出问题,elif 只在需要时问下一个,else 兜底其余情况 —— 并且恰好执行一个分支。条件可以是任何值(真值规则),可用 and/or/not 组合,并会提前停止。用 and 和守卫子句让判断保持扁平,快速二选一用三元表达式,一个值有多个固定选项时用 match。