BASIC Python (Beginner Level) 📂 Basic Python Programming · 5 of 15 152 min read

Python Control Flow — if, elif, else, Truthiness, Logical Operators & Match Statement

Master Python control flow from the ground up. This tutorial covers the if statement with animated flowcharts, if/else two-path decisions, if/elif/else cascades, complete truthiness rules (what counts as True and False), comparison operators with chained comparisons, logical operators (and, or, not) with short-circuit evaluation, nested if vs guard clauses, ternary expressions, the modern match statement, common traps, and a full smart-grader practice program.

🌐
SectionSection第 01 节

The Story That Explains Control Flow 🛣️Control Flow समझाने वाली कहानी 🛣️一个解释控制流的故事 🛣️

The Fork in the Roadसड़क का दोराहा岔路口
You're driving to a friend's house and reach a fork in the road. A sign says "If it's raining, take the left road; otherwise, take the right." You look at the sky, decide, and keep going. That moment — look at a condition, choose a path, keep going — is exactly what control flow is in programming.

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.
आप एक दोस्त के घर जा रहे हैं और एक दोराहे पर पहुँचते हैं। Board पर लिखा है "अगर बारिश हो रही है, तो बाईं सड़क लें; वरना दाईं।" आप आसमान देखते हैं, फ़ैसला करते हैं, और आगे बढ़ते हैं। वह पल — एक condition देखो, रास्ता चुनो, आगे बढ़ो — programming में ठीक यही control flow है।

इसके बिना 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 来写。

掌握这三个关键字,你几乎能看懂任何程序的结构。循环和函数也建立在同样的思想上:决定什么代码执行、何时执行。
❓
if
The conditionCondition条件
Ask a yes/no question. If the answer is True, run the block underneath. If False, skip it. Every decision starts with an if.
हाँ/ना वाला सवाल पूछें। जवाब True हो तो नीचे का block चलाएँ। False हो तो छोड़ दें। हर फ़ैसला if से शुरू होता है।
提出一个是/否问题。答案为 True 就执行下面的代码块;为 False 就跳过。每个决定都从 if 开始。
🔁
elif
The next questionअगला सवाल下一个问题
Short for "else if". Ask a follow-up question, but only if every earlier one was False. Chain as many as you need.
"else if" का छोटा रूप। अगला सवाल पूछें, पर तभी जब पहले के सारे False हों। जितने चाहिए उतने जोड़ें।
“else if”的缩写。只有在前面所有条件都为 False 时,才会问这个后续问题。可以按需串联任意多个。
🛟
else
The fallbackआख़िरी सहारा兜底
Runs only if every if and elif above was False. Optional, but often used as the default case.
तभी चलता है जब ऊपर के सारे if और elif False हों। ज़रूरी नहीं, पर अक्सर default case के रूप में इस्तेमाल होता है।
只有上面所有的 if 和 elif 都为 False 时才执行。可选,但常用作默认情况。
▶️
How to Use the "Try It" Boxes"ख़ुद आज़माएँ" boxes कैसे इस्तेमाल करें如何使用“动手试试”框

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。结束时,从未执行的行和方框会变淡。


SectionSection第 02 节

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.")
OUTPUT
You can vote. You can sign a contract. Program continues here.

The Anatomy of an if Statementif Statement की बनावटif 语句的结构

Four Required Partsचार ज़रूरी हिस्से四个必需部分
1
The keyword if
Keyword if
关键字 if
2
A condition — any expression that Python can treat as True or False
एक condition — कोई भी expression जिसे Python True या False मान सके
一个条件 —— Python 能当作 True 或 False 处理的任何表达式
3
A colon : at the end of the line
Line के अंत में एक colon :
行尾的冒号 :
4
An indented block of code (4 spaces by convention)
Code का एक indented block (परंपरा से 4 spaces)
一个缩进的代码块(按惯例 4 个空格)
⚠️
Indentation Is Syntax, Not Just StyleIndentation syntax है, सिर्फ़ style नहीं缩进是语法,不只是风格

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 和空格),让编辑器帮你缩进。


SectionSection第 03 节

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!")
OUTPUT
Pass Your name: Hello, stranger! Pass Your name: Asha Hello, Asha!

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。


SectionSection第 04 节

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}")
OUTPUT
Score: 85 → Grade: B
🔑
Order Matters — Check the Strictest Firstक्रम मायने रखता है — सबसे सख़्त पहले顺序很重要 —— 最严格的放在最前

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!
OUTPUT
Score: 95 → Grade: D

SectionSection第 05 节

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: 这样简短的判断。

❌ Falsy values (act as False)Falsy मान (False जैसे)假值(相当于 False)
Valueमान值Type
Falsebool
NoneNoneType
0, 0.0, 0jnumeric zeroसंख्यात्मक शून्य数值零
""empty stringख़ाली string空字符串
[]empty listख़ाली list空列表
()empty tupleख़ाली tuple空元组
{}empty dictख़ाली dict空字典
set()empty setख़ाली set空集合
✅ Truthy values (act as True)Truthy मान (True जैसे)真值(相当于 True)
Valueमान值Whyक्यों原因
Truethe constant itselfख़ुद constant常量本身
1, -1, 42, 3.14any 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)}")
OUTPUT
No name given Nothing to do. bool(0) = False bool('') = False bool([]) = False bool(None) = False bool(-1) = True bool('False') = True bool(' ') = True bool([0]) = True
LIVELIVE互动Truthiness CheckerTruthiness जाँचक真值检查器

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 上实际运行代码。

⚠️
The Sneakiest Truthiness BugTruthiness का सबसे चालाक bug最隐蔽的真值 bug

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":。


SectionSection第 06 节

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 == 5True
!=Not equal toबराबर नहीं不等于5 != 3True
>Greater thanसे बड़ा大于7 > 3True
<Less thanसे छोटा小于7 < 3False
>=Greater or equalबड़ा या बराबर大于等于5 >= 5True
<=Less or equalछोटा या बराबर小于等于4 <= 5True
inMembershipMembership成员3 in [1, 2, 3]True
not inNon-membershipNon-membership非成员"x" not in "abc"True
isIdentity (same object)Identity (वही object)身份(同一对象)a is Noneuse 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")
OUTPUT
Working age Working age in range True 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")
OUTPUT
File "f5b.py", line 2 if age = 18: ^^^^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
x = 5
if x > 0
    print("positive")
OUTPUT
File "f5c.py", line 2 if x > 0 ^ SyntaxError: expected ':'

SectionSection第 07 节

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 取反)。

➕
and — ALL must be Trueand — सब True होंand —— 全部为真
Both requiredदोनों ज़रूरी两者都需要
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 —— 这叫短路求值。
🔀
or — ANY must be Trueor — कोई एक True होor —— 任一为真
Either worksकोई भी चलेगा任一即可
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।
任一边为 True,A or B 就为 True。如果 A 为 True,Python 跳过 B。用于“满足其一即可”的情况,比如周末或节假日。
❌
not — flip the resultnot — नतीजा उलटेंnot —— 取反
NegationNegation否定
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")
OUTPUT
Can drive Day off! Day off! Please log in 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)
OUTPUT
No user Anonymous 8080 AttributeError: 'NoneType' object has no attribute 'name'
💡
Operator Precedence ReminderOperator Precedence की याद运算符优先级提醒

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 比靠记忆更清楚。


SectionSection第 08 节

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")
OUTPUT
Welcome back! Standard user view

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 处理不正常的情况。

❌ Deeply nested (hard to read)गहरी nesting (पढ़ना कठिन)深层嵌套(难读)
CodeCode代码
if user:
    if user.active:
        if user.role == "admin":
            grant_access()
Three levels of indentation just to grant access.सिर्फ़ access देने के लिए तीन level का indentation।仅仅为了授权就缩进了三层。
✅ Flat with and (readable)and से सपाट (पढ़ने योग्य)用 and 展平(易读)
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"]))
OUTPUT
No order Not paid No items Shipping 2 item(s)

SectionSection第 09 节

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 提供了紧凑的条件表达式(常称为三元运算符)。它写在一行内并返回一个值,因此可以用在赋值和函数调用中。

Ternary syntaxTernary syntax三元语法
value_if_true if condition else value_if_false
Reads like English: "give me A if the condition holds, else B."
English की तरह पढ़ें: "condition सही हो तो A दो, वरना B।"
读起来像英语:“条件成立则给 A,否则给 B。”
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")
OUTPUT
adult You are an adult. 0 Hello, stranger Hello, Asha
⚠️
Ternaries Are for SIMPLE Decisions OnlyTernary सिर्फ़ सरल फ़ैसलों के लिए三元表达式只用于简单判断

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 —— 下周再读会容易得多。三元表达式只适合快速的二选一。


SectionSection第 10 节

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))
OUTPUT
200 OK 404 Not Found 418 Unknown Sunday weekend Monday weekday Funday unknown

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))
OUTPUT
(0, 0) → origin (0, 5) → on the y-axis at 5 (3, 0) → on the x-axis at 3 (4, 4) → on the diagonal at 4 (2, 7) → somewhere else: (2, 7)
LIVELIVE互动match Explorermatch Explorermatch 探索器

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,✓ 表示实际执行的那个。结果来自实际运行代码。

💡
When to Use Whichकब कौन सा何时用哪个

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 或更高版本。


SectionSection第 11 节

Common Traps and How to Avoid Them 🪤आम जाल और उनसे कैसे बचें 🪤常见陷阱及如何避免 🪤

Using = instead of ==== की जगह =把 == 写成 =
if age = 18: is a SyntaxError — Python even suggests ==. Remember: == compares, = assigns.
if age = 18: SyntaxError है — Python ख़ुद == सुझाता है। याद रखें: == तुलना करता है, = assign करता है।
if age = 18: 是语法错误 —— Python 还会提示用 ==。记住:== 比较,= 赋值。
Missing the colonColon छूटना漏写冒号
if x > 0 → SyntaxError: expected ':'. Every if, elif and else line ends with :.
if x > 0 → SyntaxError: expected ':'। हर if, elif और else line : पर ख़त्म होती है।
if x > 0 → SyntaxError: expected ':'。每个 if、elif、else 行都以 : 结尾。
Inconsistent indentationअसंगत indentation缩进不一致
Mixing tabs and spaces or shifting alignment breaks the block boundaries. Use 4 spaces everywhere and turn on "show whitespace" in your editor.
Tabs और spaces मिलाना या alignment खिसकाना block की सीमाएँ तोड़ देता है। हर जगह 4 spaces रखें और editor में "show whitespace" चालू करें।
混用 tab 和空格或对齐错位会破坏代码块的边界。统一使用 4 个空格,并在编辑器中开启“显示空白字符”。
Overlapping elif conditionsएक-दूसरे पर चढ़ी elif conditionselif 条件重叠
if x > 60: … elif x > 70: … — the second branch never runs, because x > 60 already catches everything it would. Order strictest to loosest.
if x > 60: … elif x > 70: … — दूसरी शाखा कभी नहीं चलती, क्योंकि x > 60 वह सब पहले ही पकड़ लेता है। सबसे सख़्त से सबसे ढीली के क्रम में रखें।
if x > 60: … elif x > 70: … —— 第二个分支永远不会执行,因为 x > 60 已经捕获了它的所有情况。按从严到宽的顺序排列。
Comparing with == True or == False== True या == False से तुलना与 == True 或 == False 比较
if active == True: works but is wordy. Write if active:, and if not active: instead of if active == False:.
if active == True: चलता है पर लंबा है। if active: लिखें, और if active == False: की जगह if not active:।
if active == True: 能用但啰嗦。写 if active:,用 if not active: 代替 if active == False:。
Using 'is' for value comparisonमान की तुलना के लिए 'is'用 'is' 比较值
if x is 1000: may give True in one place and False in another, and Python prints a SyntaxWarning. Use == for values and is for None.
if x is 1000: एक जगह True और दूसरी जगह False दे सकता है, और Python SyntaxWarning छापता है। मानों के लिए == और None के लिए is लगाएँ।
if x is 1000: 可能在一处为 True、另一处为 False,并且 Python 会打印 SyntaxWarning。比较值用 ==,判断 None 用 is。

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
OUTPUT
over 60 True f12.py:8: SyntaxWarning: "is" with 'int' literal. Did you mean "=="? print(x is 1000) # True here — but Python warns, and the REPL may say False

SectionSection第 12 节

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()
OUTPUT
───────────────────────────────────────────── Alice Score: 96 Grade: A Status: Passed Attendance: 98% Honors: Highest Honors Note: Excellent work! ───────────────────────────────────────────── Bob Score: 72 Grade: C Status: Passed Attendance: 85% Honors: Regular Note: Solid effort — room to grow ───────────────────────────────────────────── Carol Score: 58 Grade: F Status: Failed Attendance: 70% Honors: Regular Note: Needs improvement ───────────────────────────────────────────── Dan Score: 88 Grade: B Status: Passed Attendance: 92% Honors: Regular Note: Solid effort — room to grow ───────────────────────────────────────────── Erin Error: score out of range

SectionSection第 13 节

Golden Rules 🏆सुनहरे नियम 🏆黄金法则 🏆

🐍 Python Control Flow — 8 RulesPython Control Flow — 8 नियमPython 控制流 —— 8 条法则
1
Every if, elif and else line ends with a colon. The block that follows is indented (4 spaces). Miss either and Python raises SyntaxError or IndentationError.
हर if, elif और else line colon पर ख़त्म होती है। उसके बाद का block indented (4 spaces) होता है। इनमें से कोई छूटा तो Python SyntaxError या IndentationError देता है।
每个 if、elif 和 else 行都以冒号结尾。后面的代码块要缩进(4 个空格)。漏掉任何一个,Python 都会报 SyntaxError 或 IndentationError。
2
Exactly one branch of an if/elif/else chain runs. Python checks top to bottom and stops at the first True. Put the strictest conditions first.
if/elif/else chain की ठीक एक शाखा चलती है। Python ऊपर से नीचे जाँचता है और पहले True पर रुकता है। सबसे सख़्त conditions पहले रखें।
if/elif/else 链中恰好执行一个分支。Python 从上到下检查,在第一个 True 处停止。把最严格的条件放在最前面。
3
Use == to compare and = to assign. Keep is for None — never for numbers or strings.
तुलना के लिए == और assign के लिए =। is को None के लिए रखें — numbers या strings के लिए कभी नहीं।
比较用 ==,赋值用 =。is 留给 None —— 绝不用于数字或字符串。
4
Prefer truthiness checks. if items: beats if len(items) > 0:, and if not name: beats if name == "":. But remember that 0 and "False" follow the same rules.
Truthiness जाँच को प्राथमिकता दें। if items:, if len(items) > 0: से बेहतर है, और if not name:, if name == "": से। पर याद रखें 0 और "False" भी इन्हीं नियमों पर चलते हैं।
优先使用真值判断。if items: 优于 if len(items) > 0:,if not name: 优于 if name == "":。但要记住 0 和 "False" 也遵循同样的规则。
5
Chain comparisons for ranges. 18 <= age <= 65 means the same as age >= 18 and age <= 65 and reads like maths.
Ranges के लिए comparisons chain करें। 18 <= age <= 65 का मतलब age >= 18 and age <= 65 जैसा ही है और गणित जैसा पढ़ता है।
范围判断用链式比较。18 <= age <= 65 与 age >= 18 and age <= 65 含义相同,读起来像数学式。
6
Use guard clauses to reduce nesting. Handle the failure cases first with an early return or continue, and keep the happy path flat.
Nesting कम करने के लिए guard clauses लगाएँ। असफल मामलों को पहले जल्दी वाले return या continue से संभालें, और सही रास्ता सपाट रखें।
用守卫子句减少嵌套。先用提前 return 或 continue 处理失败情况,让正常流程保持扁平。
7
Short-circuiting is a feature. user and user.name is safe when user is None — but only in that order. value or default is a handy fallback, as long as 0 or "" are not valid values.
Short-circuiting एक feature है। user None होने पर user and user.name सुरक्षित है — पर सिर्फ़ इसी क्रम में। value or default एक काम का fallback है, बशर्ते 0 या "" सही मान न हों।
短路是一项特性。user 为 None 时,user and user.name 是安全的 —— 但只能是这个顺序。value or default 是方便的兜底写法,前提是 0 或 "" 不是有效值。
8
Use the ternary only for simple two-way choices. "adult" if age >= 18 else "minor" is fine; nested ternaries are not.
Ternary सिर्फ़ सरल दो-तरफ़ा फ़ैसलों के लिए। "adult" if age >= 18 else "minor" ठीक है; nested ternaries नहीं।
三元表达式只用于简单的二选一。"adult" if age >= 18 else "minor" 没问题;嵌套的三元表达式就不行。
LIVELIVE互动Quick Checkछोटी जाँच小测验

Six questions on the traps in this lesson. Pick an answer to see why.

इस lesson के जालों पर छह सवाल। जवाब चुनें और कारण देखें।

六道关于本课陷阱的题目。选择答案查看解释。

🧮
Key Takeawayमुख्य सीख核心要点

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。

🐍 Try Python Yourself

Write, run and visualize Python step by step. No install needed.