BASIC Python (Beginner Level) 📂 Basic Python Programming · 3 of 15 174 min read

Python Operators — Complete Guide with Precedence

Master every Python operator: arithmetic, comparison, logical, assignment, bitwise, membership, and identity. Covers real code examples for each operator, the complete precedence table (BODMAS-style), common traps like float equality and -2**2, hands-on exercises including a leap-year detector and password checker, plus a full operators sandbox program that ties every concept together.

🌐
SectionSection第 01 节

The Story That Explains Operators 🍳Operators समझाने वाली कहानी 🍳一个解释运算符的故事 🍳

The Kitchen Tools of ProgrammingProgramming के रसोई औज़ार编程的厨房工具
Walk into a busy kitchen. The chef has a knife for chopping, a whisk for mixing, a scale for weighing and a thermometer for checking heat. Each tool does one job. Together they turn raw ingredients into a meal.

In Python, your data — numbers, text, True and False — are the ingredients. Operators are the tools. They add, compare, combine and check values. Without them your data just sits there. With them it becomes a working program: every calculation, every if and every loop uses operators.
एक व्यस्त रसोई में जाइए। Chef के पास काटने के लिए चाकू, मिलाने के लिए whisk, तौलने के लिए तराज़ू और गर्मी जाँचने के लिए thermometer है। हर औज़ार एक काम करता है। साथ मिलकर वे कच्ची सामग्री को खाने में बदलते हैं।

Python में आपका data — संख्याएँ, text, True और False — सामग्री है। Operators औज़ार हैं। वे मानों को जोड़ते, तुलना करते, मिलाते और जाँचते हैं। इनके बिना data बस पड़ा रहता है। इनके साथ वह चलता program बनता है: हर गणना, हर if और हर loop operators इस्तेमाल करता है।
走进一间忙碌的厨房。厨师有切菜的刀、搅拌的打蛋器、称重的秤和测温的温度计。每种工具只做一件事,合在一起就能把食材变成一道菜。

在 Python 中,你的数据 —— 数字、文本、True 和 False —— 就是食材,运算符就是工具。它们对值进行相加、比较、组合和检查。没有运算符,数据只是静静地放着;有了运算符,它就成了能运行的程序:每次计算、每个 if、每个循环都离不开运算符。

An operator is a symbol or keyword that does something with one or more values, called operands. In 5 + 3, the + is the operator and 5 and 3 are the operands. An operator with one operand (like -x or not x) is called unary; one with two operands is binary.

Operator एक symbol या keyword है जो एक या ज़्यादा मानों पर कुछ करता है, जिन्हें operands कहते हैं। 5 + 3 में + operator है और 5 और 3 operands हैं। एक operand वाला operator (जैसे -x या not x) unary कहलाता है; दो operands वाला binary।

运算符是对一个或多个值(称为操作数)进行操作的符号或关键字。在 5 + 3 中,+ 是运算符,5 和 3 是操作数。只有一个操作数的运算符(如 -x 或 not x)叫一元运算符;有两个操作数的叫二元运算符。

💡
The Big Pictureबड़ी तस्वीर全局视图

Python's operators fall into seven families: arithmetic, comparison, logical, assignment, bitwise, membership and identity. When one line mixes several operators, precedence decides which runs first. This lesson covers each family, then precedence, then the traps that catch beginners.

Python के operators सात परिवारों में बँटते हैं: arithmetic, comparison, logical, assignment, bitwise, membership और identity। जब एक line में कई operators हों, तो precedence तय करता है कि पहले कौन चले। यह lesson हर परिवार, फिर precedence, फिर beginners को फँसाने वाले जाल सिखाता है।

Python 的运算符分为七个家族:算术、比较、逻辑、赋值、位运算、成员和身份。一行中混用多个运算符时,由优先级决定谁先执行。本课依次讲解每个家族、优先级,以及初学者常踩的陷阱。


SectionSection第 02 节

The Seven Families of Operators 🗂️Operators के सात परिवार 🗂️运算符的七个家族 🗂️

🧩 PICTURE 1 — ONE EXPRESSION, SEVEN FAMILIESतस्वीर 1 — एक EXPRESSION, सात परिवार图 1 —— 一个表达式,七个家族
Anatomy of an expression and the seven operator families 5+3→ 8 operandoperand操作数 operatoroperator运算符 operandoperand操作数 result (a new value)नतीजा (नया मान)结果(新值) ArithmeticArithmetic算术+ − * /// % ** ComparisonComparison比较== !=< > <= >= LogicalLogical逻辑and ornot AssignmentAssignment赋值= += -=:= … BitwiseBitwise位运算& | ^ ~<< >> MembershipMembership成员innot in IdentityIdentity身份isis not
➕
ArithmeticArithmetic算术
Do the mathsगणित करें做数学
Add, subtract, multiply, divide, floor-divide, remainder and power. + and * also join and repeat strings and lists.
जोड़, घटाव, गुणा, भाग, floor-division, शेष और power। + और * strings और lists को जोड़ते और दोहराते भी हैं।
加、减、乘、除、整除、取余和乘方。+ 和 * 还能拼接和重复字符串与列表。
⚖️
ComparisonComparison比较
Ask questionsसवाल पूछें提出问题
Compare two values and give True or False. They drive every if and while.
दो मानों की तुलना करके True या False देते हैं। हर if और while इन्हीं से चलता है।
比较两个值并得到 True 或 False。每个 if 和 while 都依赖它们。
🧠
LogicalLogical逻辑
Combine conditionsशर्तें जोड़ें组合条件
and, or, not — English words instead of &&, ||, ! used in C and Java.
and, or, not — C और Java के &&, ||, ! की जगह English शब्द।
and、or、not —— 用英文单词代替 C 和 Java 中的 &&、||、!。
📝
AssignmentAssignment赋值
Store and updateरखें और बदलें存储与更新
= binds a name to a value. +=, -= and friends update it. := assigns inside an expression.
= नाम को मान से बाँधता है। +=, -= वग़ैरह उसे बदलते हैं। := expression के अंदर assign करता है।
= 把名字绑定到值上。+=、-= 等用来更新。:= 在表达式内部赋值。
🔢
BitwiseBitwise位运算
Work on bitsBits पर काम操作二进制位
Work on the binary digits of integers. Used for flags, permissions, networking and fast tricks.
Integers के binary अंकों पर काम करते हैं। Flags, permissions, networking और तेज़ tricks में काम आते हैं।
直接操作整数的二进制位。用于标志位、权限、网络和高效技巧。
🔍
MembershipMembership成员
Is it inside?क्या अंदर है?在不在里面?
in and not in check whether a value is inside a string, list, set or dictionary.
in और not in जाँचते हैं कि मान string, list, set या dictionary के अंदर है या नहीं।
in 和 not in 检查某个值是否在字符串、列表、集合或字典中。
🪪
IdentityIdentity身份
Same object?वही object?是同一个对象吗?
is and is not check whether two names point to the very same object — not whether the values are equal.
is और is not जाँचते हैं कि दो नाम बिल्कुल उसी object की ओर हैं या नहीं — मान बराबर हैं या नहीं, यह नहीं।
is 和 is not 检查两个名字是否指向同一个对象 —— 而不是值是否相等。

SectionSection第 03 节

Arithmetic Operators — The Maths Toolkit ➕Arithmetic Operators — गणित के औज़ार ➕算术运算符 —— 数学工具箱 ➕

OperatorOperator运算符Nameनाम名称Exampleउदाहरण例子Resultनतीजा结果Notesटिप्पणी说明
+Additionजोड़加法10 + 313Also joins strings and listsStrings और lists भी जोड़ता है也可拼接字符串和列表
-Subtractionघटाव减法10 - 37Also negates: -xNegate भी करता है: -x也可取负:-x
*Multiplicationगुणा乘法10 * 330Repeats strings/lists: "ab" * 3Strings/lists दोहराता है: "ab" * 3重复字符串/列表:"ab" * 3
/Divisionभाग除法10 / 33.3333333333333335Always a floatहमेशा float总是浮点数
//Floor divisionFloor division整除10 // 33Rounds down (−7 // 2 is −4)नीचे round करता है (−7 // 2 = −4)向下取整(−7 // 2 为 −4)
%ModuloModulo取模10 % 31Remainder; takes the sign of the divisorशेष; भाजक का चिह्न लेता है余数;符号与除数相同
**PowerPower乘方10 ** 31000Right-to-left: 2 ** 3 ** 2 is 512दाएँ से बाएँ: 2 ** 3 ** 2 = 512从右向左:2 ** 3 ** 2 为 512
a, b = 17, 5
print(f"a + b  = {a + b}")
print(f"a - b  = {a - b}")
print(f"a * b  = {a * b}")
print(f"a / b  = {a / b}")       # true division: always a float
print(f"a // b = {a // b}")      # floor division
print(f"a % b  = {a % b}")       # remainder
print(f"a ** b = {a ** b}")      # power: 17 to the 5th

print("Ha" * 3)
print("Hello, " + "World!")
print([1, 2] + [3, 4])
print([0] * 5)

print(14 % 2 == 0, 15 % 2 == 0)  # even? odd?
total_min = 150
print(f"{total_min // 60}h {total_min % 60}min")
print((23 + 3) % 24)             # 23:00 + 3 hours on a 24-hour clock
print(divmod(150, 60))           # quotient and remainder together
OUTPUT
a + b = 22 a - b = 12 a * b = 85 a / b = 3.4 a // b = 3 a % b = 2 a ** b = 1419857 HaHaHa Hello, World! [1, 2, 3, 4] [0, 0, 0, 0, 0] True False 2h 30min 2 (2, 30)

// and % always fit together: a == (a // b) * b + a % b. divmod(a, b) gives both at once. With negative numbers, Python rounds down, not toward zero — so the results differ from C and Java:

// और % हमेशा साथ बैठते हैं: a == (a // b) * b + a % b। divmod(a, b) दोनों एक साथ देता है। Negative संख्याओं में Python शून्य की ओर नहीं, नीचे round करता है — इसलिए नतीजे C और Java से अलग आते हैं:

// 和 % 总是配套的:a == (a // b) * b + a % b。divmod(a, b) 一次返回两者。遇到负数时,Python 向下取整而不是向零取整 —— 所以结果与 C 和 Java 不同:

# floor division and modulo with negative numbers
print(7 // 2, -7 // 2)        # rounds DOWN, toward minus infinity
print(7 % 3, -7 % 3, 7 % -3)  # result takes the sign of the divisor
print(7.5 // 2, 7.5 % 2)      # works on floats too, result is a float
print(int(-7 / 2))            # int() cuts toward zero instead
print(2 ** -1, 4 ** 0.5)      # negative and fractional powers give floats
print(pow(2, 10, 1000))       # 2**10 % 1000, computed efficiently
OUTPUT
3 -4 1 2 -2 3.0 1.5 -3 0.5 2.0 24
LIVELIVE互动Modulo ClockModulo घड़ी取模时钟

Move a and m. The hand walks a steps around a clock with m positions. Full laps are a // m; where it stops is a % m. Try a negative a.

a और m बदलें। सुई m positions वाली घड़ी पर a क़दम चलती है। पूरे चक्कर a // m हैं; जहाँ रुकती है वह a % m है। Negative a आज़माएँ।

调整 a 和 m。指针在有 m 个位置的时钟上走 a 步。走完的整圈数是 a // m,停下的位置是 a % m。试试负数 a。

🔑
Modulo Is Secretly PowerfulModulo छुपा हुआ ताक़तवर है取模其实很强大

% shows up everywhere: even/odd checks (n % 2 == 0), clock maths ((23 + 3) % 24 is 2), wrapping a list index (i % len(items)), splitting minutes into hours (divmod(150, 60)), and spreading work across servers.

% हर जगह मिलता है: even/odd जाँच (n % 2 == 0), घड़ी का गणित ((23 + 3) % 24 = 2), list index घुमाना (i % len(items)), मिनटों को घंटों में बाँटना (divmod(150, 60)), और servers में काम बाँटना।

% 无处不在:判断奇偶(n % 2 == 0)、时钟运算((23 + 3) % 24 为 2)、循环列表下标(i % len(items))、把分钟换算成小时(divmod(150, 60)),以及在服务器之间分配任务。


SectionSection第 04 节

Comparison Operators — Asking Questions ⚖️Comparison Operators — सवाल पूछना ⚖️比较运算符 —— 提出问题 ⚖️

Comparison operators compare two values and always give a boolean: True or False.

Comparison operators दो मानों की तुलना करते हैं और हमेशा boolean देते हैं: True या False।

比较运算符比较两个值,结果总是布尔值:True 或 False。

OperatorOperator运算符Meaningअर्थ含义Exampleउदाहरण例子Resultनतीजा结果
==equal toबराबर等于5 == 5True
!=not equal toबराबर नहीं不等于5 != 3True
>greater thanसे बड़ा大于7 > 4True
<less thanसे छोटा小于3 < 8True
>=greater than or equalबड़ा या बराबर大于等于5 >= 5True
<=less than or equalछोटा या बराबर小于等于4 <= 3False
print(10 == 10)
print(10 == "10")             # int vs str: never equal
print(10 == 10.0)             # int vs float: compared by value
print(10 != 7)
print("apple" < "banana")     # strings compare letter by letter
print("Apple" < "apple")      # 'A' (65) comes before 'a' (97)
print("10" < "9")             # text comparison, not numeric!
print([1, 2, 3] < [1, 3])     # lists compare item by item

age = 25
print(age >= 18 and age < 65)
print(18 <= age < 65)         # chained: same meaning, easier to read
x = 50
print(0 < x < 100 < 1000)

score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"
print(f"Score {score} → Grade {grade}")

try:
    print(5 < "6")
except TypeError as err:
    print("TypeError:", err)
OUTPUT
True False True True True True True True True True True Score 85 → Grade B TypeError: '<' not supported between instances of 'int' and 'str'

Three things to notice. Strings compare character by character using Unicode code points, so "10" < "9" is True — convert text to numbers before comparing. Comparisons can be chained: 18 <= age < 65 means 18 <= age and age < 65. And ordering values of unrelated types, such as 5 < "6", raises a TypeError.

तीन बातें ध्यान दें। Strings की तुलना Unicode code points से अक्षर-दर-अक्षर होती है, इसलिए "10" < "9" True है — तुलना से पहले text को संख्या में बदलें। Comparisons chain हो सकते हैं: 18 <= age < 65 का मतलब 18 <= age and age < 65। और असंबंधित types को क्रम में रखना, जैसे 5 < "6", TypeError देता है।

注意三点。字符串按 Unicode 码点逐字符比较,所以 "10" < "9" 为 True —— 比较前先把文本转成数字。比较可以链式书写:18 <= age < 65 等价于 18 <= age and age < 65。对无关类型排序(如 5 < "6")会引发 TypeError。

⚠️
Never Confuse = with === और == को कभी न मिलाएँ切勿混淆 = 与 ==

= stores a value; == asks whether two values are equal. Python refuses if x = 5: and even suggests the fix:

= मान रखता है; == पूछता है कि दो मान बराबर हैं या नहीं। Python if x = 5: नहीं मानता और सुधार भी सुझाता है:

= 用于存值;== 用于判断两个值是否相等。Python 拒绝 if x = 5:,还会提示正确写法:

x = 5
if x = 5:
    print("five")
OUTPUT
File "o3b.py", line 2 if x = 5: ^^^^^ SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

SectionSection第 05 节

Logical Operators — Combining Conditions 🧠Logical Operators — शर्तें जोड़ना 🧠逻辑运算符 —— 组合条件 🧠

∧
and
A and B
True only when both sides are true.
तभी True जब दोनों तरफ़ true हों।
只有两边都为真时才为 True。
∨
or
A or B
True when at least one side is true.
कम से कम एक तरफ़ true हो तो True।
至少一边为真时为 True。
¬
not
not A
Flips the value. It always returns a real True or False.
मान उलट देता है। यह हमेशा असली True या False लौटाता है।
取反。它总是返回真正的 True 或 False。
⚡
Short-circuitShort-circuit短路
A and B / A or B
Python stops as soon as the answer is known. In False and X, X never runs.
जवाब पता चलते ही Python रुक जाता है। False and X में X कभी नहीं चलता।
一旦结果确定,Python 就停止计算。在 False and X 中,X 根本不会执行。

Truth TablesTruth Tables真值表

✅ AND truth tableAND truth tableAND 真值表
ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
✅ OR truth tableOR truth tableOR 真值表
ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
age = 25
has_license = True
has_car = False

can_drive = age >= 18 and has_license
print(f"Can drive: {can_drive}")
needs_transport = not has_car or age < 16
print(f"Needs transport: {needs_transport}")
is_minor = not (age >= 18)
print(f"Is minor: {is_minor}")

username, password, is_locked = "asha", "secret123", False
can_login = (username == "asha" and
             password == "secret123" and
             not is_locked)
print(f"Can login: {can_login}")

# short-circuit: the right side is skipped when the left side decides
x = 0
if x == 0 or (10 / x) > 1:
    print("Safe — 10 / x never ran")


def check(name, value):
    print(f"  checking {name}")
    return value


print(check("A", False) and check("B", True))
print(check("A", True) or check("B", False))
OUTPUT
Can drive: True Needs transport: True Is minor: False Can login: True Safe — 10 / x never ran checking A False checking A True

The last two lines prove short-circuiting: only "checking A" is printed, because A alone decides the answer. This is why x == 0 or 10 / x > 1 never divides by zero.

आख़िरी दो lines short-circuiting साबित करती हैं: सिर्फ़ "checking A" छपता है, क्योंकि अकेले A से जवाब तय हो जाता है। इसीलिए x == 0 or 10 / x > 1 कभी शून्य से भाग नहीं करता।

最后两行证明了短路:只打印了 "checking A",因为仅凭 A 就能决定结果。这就是 x == 0 or 10 / x > 1 永远不会除以零的原因。

LIVELIVE互动and / or Flowand / or का प्रवाहand / or 执行流程

Pick A, B and the operator. The green or red path shows what Python really did, and which value it returned. All 128 results were produced by Python.

A, B और operator चुनें। हरा या लाल रास्ता दिखाता है कि Python ने सच में क्या किया, और कौन सा मान लौटाया। सारे 128 नतीजे Python से बने हैं।

选择 A、B 和运算符。绿色或红色路径显示 Python 实际做了什么、返回了哪个值。全部 128 个结果都由 Python 生成。

So and and or return one of the original values, not always True/False. This gives a handy default-value pattern — with one trap:

तो and और or मूल मानों में से एक लौटाते हैं, हमेशा True/False नहीं। इससे default-value का एक काम का तरीक़ा मिलता है — एक जाल के साथ:

所以 and 和 or 返回的是原来的某个值,而不一定是 True/False。这带来一个方便的默认值写法 —— 但有一个陷阱:

print(5 and 10)          # both truthy → the last value
print(0 and 10)          # stops at the first falsy value
print(5 or 10)           # stops at the first truthy value
print(0 or 10)
print("" or "default")
print(None or [] or 0)   # all falsy → the last value
print(not "hello", not "")

name = ""
display = name or "Anonymous"
print(display)
count = 0
print(count or 10)       # careful: 0 is a real value but counts as falsy!
print(10 if count is None else count)
OUTPUT
10 0 5 10 default 0 False True Anonymous 10 0
🪤
The "or default" Trap"or default" का जाल“or 默认值”陷阱

count or 10 replaces every falsy value — including a real 0, an empty string or an empty list. If 0 is a valid answer, test for None instead: 10 if count is None else count.

count or 10 हर falsy मान को बदल देता है — असली 0, ख़ाली string या ख़ाली list भी। अगर 0 एक सही जवाब है, तो None की जाँच करें: 10 if count is None else count।

count or 10 会替换所有假值 —— 包括真实的 0、空字符串或空列表。如果 0 是有效值,请改为检查 None:10 if count is None else count。


SectionSection第 06 节

Assignment Operators — Store and Update 📝Assignment Operators — रखना और बदलना 📝赋值运算符 —— 存储与更新 📝

OperatorOperator运算符Exampleउदाहरण例子Same asइसके बराबर等价于Meaningअर्थ含义
=x = 5—Bind the name x to 5नाम x को 5 से बाँधें把名字 x 绑定到 5
+=x += 3x = x + 3Add and storeजोड़ें और रखें相加并存回
-=x -= 3x = x - 3Subtract and storeघटाएँ और रखें相减并存回
*=x *= 3x = x * 3Multiply and storeगुणा करें और रखें相乘并存回
/=x /= 3x = x / 3Divide and store (gives a float)भाग करें और रखें (float देता है)相除并存回(得到浮点数)
//=x //= 3x = x // 3Floor-divide and storeFloor-divide करें और रखें整除并存回
%=x %= 3x = x % 3Remainder and storeशेष निकालें और रखें取余并存回
**=x **= 3x = x ** 3Power and storePower करें और रखें乘方并存回
&= |= ^= <<= >>=flags |= 4flags = flags | 4Bitwise versionsBitwise रूप位运算版本
:=(n := 10)walruswalrus海象Assign inside an expression (Python 3.8+)Expression के अंदर assign (Python 3.8+)在表达式中赋值(Python 3.8+)
score = 0
score += 10        # score = score + 10
score += 25
score -= 5
score *= 2
score //= 3
print(f"Final score: {score}")

message = "Hello"
message += ", "
message += "World!"
print(message)

tasks = ["wake up"]
tasks += ["eat", "code"]
tasks *= 2
print(tasks)

# a += b on a list changes the SAME list; a = a + b builds a new one
a = [1]
alias = a
a += [2]
print(alias)
a = a + [3]
print(alias, a)

numbers = [3, 7, 15, 22, 31]
if (n := len(numbers)) > 3:          # walrus: assign inside an expression (3.8+)
    print(f"List has {n} items")
OUTPUT
Final score: 20 Hello, World! ['wake up', 'eat', 'code', 'wake up', 'eat', 'code'] [1, 2] [1, 2] [1, 2, 3] List has 5 items

One subtle point, shown by alias: for a list, a += [2] changes the list in place, so every name for that list sees the change. a = a + [3] builds a new list and only moves a. For numbers and strings there is no difference, because they cannot be changed in place. Also, Python has no ++ or --:

एक बारीक बात, जो alias दिखाता है: list के लिए a += [2] list को अपनी जगह बदलता है, इसलिए उस list के हर नाम को बदलाव दिखता है। a = a + [3] एक नई list बनाता है और सिर्फ़ a को उस पर ले जाता है। Numbers और strings में कोई अंतर नहीं, क्योंकि वे अपनी जगह नहीं बदलते। साथ ही, Python में ++ या -- नहीं है:

alias 揭示了一个细节:对列表来说,a += [2] 是原地修改,所以指向该列表的所有名字都能看到变化;a = a + [3] 则创建一个新列表,只移动 a。对数字和字符串没有区别,因为它们不能原地修改。另外,Python 没有 ++ 或 --:

x = 5
x++
OUTPUT
File "o6b.py", line 2 x++ ^ SyntaxError: invalid syntax

SectionSection第 07 节

Bitwise Operators — Working with Binary 🔢Bitwise Operators — Binary के साथ काम 🔢位运算符 —— 操作二进制 🔢

Every integer is stored as bits (0s and 1s). Bitwise operators work on those bits directly. You will not need them every day, but they matter for permissions, network masks, file formats and hardware.

हर integer bits (0 और 1) के रूप में store होता है। Bitwise operators सीधे उन bits पर काम करते हैं। रोज़ इनकी ज़रूरत नहीं पड़ेगी, पर permissions, network masks, file formats और hardware में ये मायने रखते हैं।

每个整数都以二进制位(0 和 1)存储。位运算符直接操作这些位。日常编程不常用,但在权限、网络掩码、文件格式和硬件编程中很重要。

OperatorOperator运算符Nameनाम名称Exampleउदाहरण例子In binaryBinary में二进制Resultनतीजा结果
&AND12 & 101100 & 10108 (1000)
|OR12 | 101100 | 101014 (1110)
^XOR12 ^ 101100 ^ 10106 (0110)
~NOT (invert)NOT (उलटें)取反~12always -x - 1हमेशा -x - 1总是 -x - 1-13
<<Left shiftLeft shift左移3 << 211 → 110012
>>Right shiftRight shift右移12 >> 21100 → 113
a, b = 12, 10
print(f"{a:04b} & {b:04b} = {a & b:04b} = {a & b}")
print(f"{a:04b} | {b:04b} = {a | b:04b} = {a | b}")
print(f"{a:04b} ^ {b:04b} = {a ^ b:04b} = {a ^ b}")
print(f"~{a} = {~a}  (always -x - 1)")
print(5 << 1, 5 << 3, 40 >> 2, 41 >> 2)   # shifts multiply / floor-divide by powers of 2
print(bin(12), bin(10), bin(12 & 10))

# real use: Unix file permissions (rwx bits)
mode = 0o754
for who, shift in [("owner", 6), ("group", 3), ("others", 0)]:
    bits = (mode >> shift) & 0b111
    print(f"{who:<6} {bits:03b} ", "r" if bits & 4 else "-", "w" if bits & 2 else "-", "x" if bits & 1 else "-", sep="")
OUTPUT
1100 & 1010 = 1000 = 8 1100 | 1010 = 1110 = 14 1100 ^ 1010 = 0110 = 6 ~12 = -13 (always -x - 1) 10 40 10 10 0b1100 0b1010 0b1000 owner 111 rwx group 101 r-x others 100 r--
LIVELIVE互动Bitwise LabBitwise Lab位运算实验室

Pick an operator and click the bits of a and b to flip them. The bottom row is the result. The column headings show each bit’s value.

Operator चुनें और a और b के bits पर click करके उन्हें पलटें। नीचे की row नतीजा है। ऊपर की headings हर bit का मान दिखाती हैं।

选择运算符,点击 a 和 b 的位来翻转。最下面一行是结果。列标题显示每一位代表的数值。

n

💡
Where You Will Actually Meet Themये असल में कहाँ मिलेंगे你实际会在哪里遇到它们

Unix file permissions (0o754 above is rwxr-xr--), feature flags stored in one integer, IP subnet masks (ip & mask), the bytes of UTF-8 text, hashing, and competitive-programming tricks such as n & 1 for odd/even. In normal app code they are rare — but you should recognise them.

Unix file permissions (ऊपर 0o754 = rwxr-xr--), एक integer में रखे feature flags, IP subnet masks (ip & mask), UTF-8 text के bytes, hashing, और odd/even के लिए n & 1 जैसी competitive-programming tricks। आम app code में ये कम दिखते हैं — पर इन्हें पहचानना चाहिए।

Unix 文件权限(上面的 0o754 就是 rwxr-xr--)、存在一个整数里的功能开关、IP 子网掩码(ip & mask)、UTF-8 文本的字节、哈希,以及用 n & 1 判断奇偶等竞赛技巧。普通应用代码中很少用到 —— 但你应该认得它们。


SectionSection第 08 节

Membership Operators — Is It Inside? 🔍Membership Operators — क्या अंदर है? 🔍成员运算符 —— 在不在里面?🔍

in and not in check whether a value is inside a collection. They work on strings (substring search), lists, tuples, sets, ranges and dictionaries.

in और not in जाँचते हैं कि मान किसी collection के अंदर है या नहीं। ये strings (substring खोज), lists, tuples, sets, ranges और dictionaries पर काम करते हैं।

in 和 not in 检查某个值是否在集合中。它们适用于字符串(子串查找)、列表、元组、集合、range 和字典。

fruits = ["apple", "banana", "cherry"]
print("apple" in fruits, "mango" in fruits, "mango" not in fruits)

sentence = "Python is awesome"
print("Python" in sentence, "python" in sentence, "awe" in sentence)

user = {"name": "Asha", "age": 30, "role": "admin"}
print("name" in user)             # dictionaries check KEYS
print("Asha" in user)
print("Asha" in user.values())

print(3 in range(0, 10, 3), 4 in range(0, 10, 3))

valid_roles = {"admin", "editor", "viewer"}   # a set: very fast lookups
current_role = input("Enter your role: ")
if current_role in valid_roles:
    print(f"Access granted as {current_role}")
else:
    print("Invalid role")
OUTPUT
True False True True False True True False True True False Enter your role: editor Access granted as editor
🔑
Two Things to Rememberदो बातें याद रखें记住两点

1. On a dictionary, in checks the keys. Use .values() to search values.
2. On a list, in checks items one by one. On a set or dictionary it uses hashing and stays fast even with millions of items — so use a set for "allowed values" lookups.

1. Dictionary पर in keys जाँचता है। Values खोजने के लिए .values() लगाएँ।
2. List पर in एक-एक item जाँचता है। set या dictionary पर यह hashing इस्तेमाल करता है और लाखों items में भी तेज़ रहता है — इसलिए "allowed values" जाँच के लिए set इस्तेमाल करें।

1. 对字典使用 in 检查的是键。要查值请用 .values()。
2. 对列表使用 in 会逐个比较元素;对 set 或字典则使用哈希,即使有上百万个元素也很快 —— 所以“允许值”的查找请用集合。


SectionSection第 09 节

Identity Operators — Same Object or Just Equal? 🪪Identity Operators — वही Object या सिर्फ़ बराबर? 🪪身份运算符 —— 同一对象还是仅仅相等?🪪

== asks "do these have the same value?". is asks "are these the very same object?". Two lists can hold equal values and still be two separate objects.

== पूछता है "क्या इनका मान एक है?"। is पूछता है "क्या ये बिल्कुल वही object हैं?"। दो lists में बराबर मान होकर भी वे दो अलग objects हो सकती हैं।

== 问的是“它们的值相同吗?”。is 问的是“它们是同一个对象吗?”。两个列表可以值相等,却仍是两个不同的对象。

⚖️ == (equality)== (समानता)==(相等)
Checksजाँचता है检查Howकैसे方式
Same value?मान एक?值相同?Calls the type’s __eq__ methodType का __eq__ method बुलाता है调用类型的 __eq__ 方法
Costलागत开销Can be slow: compares big lists item by itemधीमा हो सकता है: बड़ी lists को item-दर-item मिलाता है可能较慢:大列表要逐项比较
Use forकहाँ用于Numbers, strings, lists — almost everythingNumbers, strings, lists — लगभग सब कुछ数字、字符串、列表 —— 几乎所有情况
🪪 is (identity)is (पहचान)is(身份)
Checksजाँचता है检查Howकैसे方式
Same object?वही object?同一对象?Compares identities — id(a) == id(b)Identities मिलाता है — id(a) == id(b)比较身份 —— id(a) == id(b)
Costलागत开销Always instant; cannot be customisedहमेशा तुरंत; बदला नहीं जा सकता总是瞬间完成;不能被重载
Use forकहाँ用于None (and other single objects)None (और दूसरे इकलौते objects)None(以及其他单例对象)
a = [1, 2, 3]
b = [1, 2, 3]        # equal values, but a different list
c = a                # a second name for the same list
print(a == b, a is b, a is c)
print(id(a) == id(c), id(a) == id(b))

value = None
if value is None:    # the right way to test for None
    print("No value provided")

b.append(4)          # changes only b
c.append(99)         # changes a too — they are the same object
print(a, b)
OUTPUT
True False True True False No value provided [1, 2, 3, 99] [1, 2, 3, 4]

Comparing a number with is is a bug that Python now warns about at compile time. It even happened to print True here, because the compiler reused one 1000 object inside this file — the lab below shows the same code giving False in the REPL:

किसी संख्या की is से तुलना एक bug है जिस पर Python अब compile के समय चेतावनी देता है। यहाँ यह संयोग से True छाप गया, क्योंकि compiler ने इस file में 1000 का एक ही object दोबारा इस्तेमाल किया — नीचे का lab वही code REPL में False देते हुए दिखाता है:

用 is 比较数字是个 bug,Python 现在会在编译时发出警告。这里它碰巧打印了 True,因为编译器在这个文件中复用了同一个 1000 对象 —— 下面的实验显示同样的代码在 REPL 中得到 False:

x = 1000
print(x is 1000)
OUTPUT
True o9b.py:2: SyntaxWarning: "is" with 'int' literal. Did you mean "=="? print(x is 1000)
LIVELIVE互动== vs is Lab== बनाम is Lab== 与 is 实验室

Pick a scenario. Each one was really run on Python 3.13.16, either line by line in the REPL or as a script file.

एक स्थिति चुनें। हर एक Python 3.13.16 पर सच में चलाई गई — REPL में line-दर-line या script file के रूप में।

选择一个场景。每个场景都在 Python 3.13.16 上真实运行过 —— 要么在 REPL 中逐行输入,要么作为脚本文件运行。

⚠️
The Golden Rule for isis का सुनहरा नियमis 的黄金法则

Use is / is not for None (PEP 8 says so), and when you truly need to know two names share one object. For numbers, strings, lists and dictionaries, use ==. Avoid x == True and x is True too — just write if x:.

is / is not को None के लिए इस्तेमाल करें (PEP 8 यही कहता है), और तब जब सच में जानना हो कि दो नाम एक ही object साझा करते हैं। Numbers, strings, lists और dictionaries के लिए == लगाएँ। x == True और x is True से भी बचें — बस if x: लिखें।

is / is not 用于判断 None(PEP 8 的要求),以及确实需要知道两个名字是否共享同一对象时。数字、字符串、列表和字典请用 ==。也不要写 x == True 或 x is True —— 直接写 if x:。


SectionSection第 10 节

Operator Precedence — Who Goes First? 🪜Operator Precedence — पहले कौन? 🪜运算符优先级 —— 谁先算?🪜

BODMAS in the Wildअसल ज़िंदगी में BODMAS生活中的四则运算顺序
In school you learned BODMAS (or PEMDAS): brackets, then powers, then multiply and divide, then add and subtract. So 2 + 3 × 4 is 14, not 20.

Python follows the same idea and extends it to every operator. Each operator has a rank. Higher ranks run first. When two operators share a rank, associativity decides — usually left to right, but ** goes right to left. Get it wrong and Python does not complain: you just get a wrong number. That is why brackets are your friend.
स्कूल में आपने BODMAS (या PEMDAS) सीखा: brackets, फिर powers, फिर गुणा-भाग, फिर जोड़-घटाव। इसलिए 2 + 3 × 4 14 है, 20 नहीं।

Python यही विचार हर operator पर लागू करता है। हर operator की एक rank है। ऊँची rank पहले चलती है। दो operators की rank बराबर हो तो associativity तय करती है — अक्सर बाएँ से दाएँ, पर ** दाएँ से बाएँ। ग़लती हुई तो Python शिकायत नहीं करता: बस ग़लत संख्या मिलती है। इसीलिए brackets आपके दोस्त हैं।
上学时你学过四则运算顺序:先括号,再乘方,再乘除,最后加减。所以 2 + 3 × 4 是 14,不是 20。

Python 沿用这一思想并扩展到所有运算符。每个运算符都有一个级别,级别高的先算。同级时由结合性决定 —— 通常从左到右,但 ** 从右到左。弄错了 Python 也不会报错,你只会得到一个错误的数字。所以括号是你的好朋友。
🪜 PICTURE 2 — THE PRECEDENCE LADDERतस्वीर 2 — PRECEDENCE की सीढ़ी图 2 —— 优先级阶梯
Python operator precedence ladder ▲ binds tighter (runs first)▲ ज़्यादा कसकर बँधता है (पहले चलता है)▲ 结合更紧(先执行) 1( )bracketsbrackets括号 2**power — right to leftpower — दाएँ से बाएँ乘方 —— 从右向左 3+x -x ~xunaryunary一元 4* / // %multiply, divideगुणा, भाग乘、除 5+ -add, subtractजोड़, घटाव加、减 6<< >>shiftsshifts移位 7&bitwise ANDbitwise AND按位与 8^bitwise XORbitwise XOR按位异或 9|bitwise ORbitwise OR按位或 10== != < > <= >= is incomparisons, identity, membershipcomparisons, identity, membership比较、身份、成员 11notlogical NOTlogical NOT逻辑非 12andlogical ANDlogical AND逻辑与 13orlogical ORlogical OR逻辑或 14if – elseconditional expressionconditional expression条件表达式 15:=walrus (lowest)walrus (सबसे नीचे)海象运算符(最低) binds loosest (runs last) ▼सबसे ढीला (आख़िर में) ▼结合最松(最后执行)▼

Rows higher up bind tighter. Note that bitwise operators sit above comparisons in Python — the opposite of C.

ऊपर की rows ज़्यादा कसकर बँधती हैं। ध्यान दें Python में bitwise operators comparisons से ऊपर हैं — C का उल्टा।

越靠上的行结合越紧。注意在 Python 中位运算符高于比较运算符 —— 与 C 相反。

RankRank级别OperatorOperator运算符Meaningअर्थ含义GroupingGrouping结合性
1( )BracketsBrackets括号—
2**PowerPower乘方right to leftदाएँ से बाएँ从右向左
3+x -x ~xUnary plus, minus, bitwise NOTUnary plus, minus, bitwise NOT一元正、负、按位取反—
4* / // %Multiply, divide, remainderगुणा, भाग, शेष乘、除、取余left to rightबाएँ से दाएँ从左向右
5+ -Add, subtractजोड़, घटाव加、减left to rightबाएँ से दाएँ从左向右
6<< >>ShiftsShifts移位left to rightबाएँ से दाएँ从左向右
7&Bitwise ANDBitwise AND按位与left to rightबाएँ से दाएँ从左向右
8^Bitwise XORBitwise XOR按位异或left to rightबाएँ से दाएँ从左向右
9|Bitwise ORBitwise OR按位或left to rightबाएँ से दाएँ从左向右
10== != < > <= >= is is not in not inComparison, identity, membershipComparison, identity, membership比较、身份、成员chain: a < b < cchain: a < b < c链式:a < b < c
11notLogical NOTLogical NOT逻辑非—
12andLogical ANDLogical AND逻辑与left to rightबाएँ से दाएँ从左向右
13orLogical ORLogical OR逻辑或left to rightबाएँ से दाएँ从左向右
14x if c else yConditional expressionConditional expression条件表达式right to leftदाएँ से बाएँ从右向左
15:=Walrus (lowest)Walrus (सबसे नीचे)海象运算符(最低)—

One fine point: ** beats a minus on its left (-2 ** 2 is −4) but not a minus on its right (2 ** -1 is 0.5). Run them all:

एक बारीक बात: ** अपने बाएँ के minus से आगे है (-2 ** 2 = −4), पर दाएँ के minus से नहीं (2 ** -1 = 0.5)। सब चलाकर देखें:

一个细节:** 比其左边的负号优先(-2 ** 2 为 −4),但不比其右边的负号优先(2 ** -1 为 0.5)。全部运行看看:

print(2 + 3 * 4)                # * before +
print((2 + 3) * 4)              # brackets first
print(2 ** 3 ** 2)              # ** groups right to left: 2 ** 9
print((2 ** 3) ** 2)
print(-2 ** 2)                  # means -(2 ** 2)
print((-2) ** 2)
print(2 ** -1)                  # but a minus on the RIGHT of ** binds first
x = 10
print(x > 5 and x < 20 or x == 100)
print(10 + 20 + 30 / 3)         # / first: 10 + 20 + 10.0
print((10 + 20 + 30) / 3)
print(not 1 == 2)               # == first, then not
print(1 + 2 == 3 and 2 * 2 == 4)
print(6 & 3 == 2)               # & binds tighter than == here: (6 & 3) == 2 (C does the opposite)
OUTPUT
14 20 512 64 -4 4 0.5 True 40.0 20.0 True True True
LIVELIVE互动Precedence StepperPrecedence Stepper优先级单步演示

Pick an expression and press Step. Each step was produced by walking Python’s own parse tree in its real evaluation order, including short-circuits, and the final value matches what Python prints.

एक expression चुनें और Step दबाएँ। हर step Python के अपने parse tree को उसके असली evaluation क्रम में चलकर बना है, short-circuits समेत, और अंतिम मान वही है जो Python छापता है।

选择一个表达式并点击“单步”。每一步都是按 Python 真实的求值顺序遍历它自己的语法树生成的(包括短路),最终值与 Python 打印的一致。

🔑
The Golden Rule of PrecedencePrecedence का सुनहरा नियम优先级黄金法则

When in doubt, add brackets. They cost nothing at run time and make your intent clear: write (a * b) + c or (total / count) * 100 instead of trusting your memory of the table. Your future self — and your teammates — will thank you.

शक हो तो brackets लगाएँ। Run time पर इनकी कोई क़ीमत नहीं और ये आपका इरादा साफ़ करते हैं: table की याद पर भरोसा करने के बजाय (a * b) + c या (total / count) * 100 लिखें। भविष्य में आप — और आपके साथी — धन्यवाद देंगे।

拿不准就加括号。括号在运行时没有任何开销,还能让意图一目了然:写 (a * b) + c 或 (total / count) * 100,而不要依赖对优先级表的记忆。将来的你 —— 以及你的队友 —— 都会感谢你。


SectionSection第 11 节

Common Operator Traps 🪤Operators के आम जाल 🪤常见运算符陷阱 🪤

=
= vs === बनाम === 与 ==
if x = 5:
if x = 5: is a SyntaxError. Use == to compare.
if x = 5: SyntaxError है। तुलना के लिए == लगाएँ।
if x = 5: 是语法错误。比较请用 ==。
➗
/ vs /// बनाम /// 与 //
10 / 2 → 5.0
/ always gives a float; // rounds down (-7 // 2 is −4).
/ हमेशा float देता है; // नीचे round करता है (-7 // 2 = −4)।
/ 总是得到浮点数;// 向下取整(-7 // 2 为 −4)。
−
-2 ** 2-2 ** 2-2 ** 2
-2 ** 2 → -4
Power runs before the minus. Write (-2) ** 2 to get 4.
Power, minus से पहले चलता है। 4 के लिए (-2) ** 2 लिखें।
乘方先于负号。要得到 4 请写 (-2) ** 2。
🪪
is vs ==is बनाम ==is 与 ==
x is 1000
Gives a SyntaxWarning and depends on how the code was run. Use ==.
SyntaxWarning देता है और code कैसे चला इस पर निर्भर है। == लगाएँ।
会产生 SyntaxWarning,结果取决于代码的运行方式。请用 ==。
🔁
and/or return valuesand/or क्या लौटाते हैंand/or 的返回值
0 or "hi" → "hi"
They return an operand, not always a bool. count or 10 also replaces a real 0.
ये एक operand लौटाते हैं, हमेशा bool नहीं। count or 10 असली 0 को भी बदल देता है।
它们返回某个操作数,不一定是布尔值。count or 10 也会替换真实的 0。
≈
Float equalityFloat समानता浮点相等
0.1 + 0.2 == 0.3 → False
Use math.isclose(a, b) for floats.
Floats के लिए math.isclose(a, b) लगाएँ।
浮点数请用 math.isclose(a, b)。
🔤
Text vs numbersText बनाम संख्या文本与数字
"10" < "9" → True
Strings compare letter by letter. Convert with int() first.
Strings अक्षर-दर-अक्षर तुलना करती हैं। पहले int() से बदलें।
字符串逐字符比较。先用 int() 转换。
&
& is not and& और and अलग हैं& 不是 and
6 & 3 == 2
& works on bits and binds tighter than ==. For conditions use and.
& bits पर काम करता है और == से कसकर बँधता है। Conditions के लिए and लगाएँ।
& 作用于二进制位,且比 == 结合更紧。条件判断请用 and。
➕
No ++ in PythonPython में ++ नहींPython 没有 ++
x++
x++ is a SyntaxError, and ++x silently does nothing (it is +(+x)). Use x += 1.
x++ SyntaxError है, और ++x चुपचाप कुछ नहीं करता (यह +(+x) है)। x += 1 लगाएँ।
x++ 是语法错误,而 ++x 什么也不做(它是 +(+x))。请用 x += 1。
import math
print(0.1 + 0.2 == 0.3)
print(math.isclose(0.1 + 0.2, 0.3))
print(abs((0.1 + 0.2) - 0.3) < 1e-9)
print(10 / 2, 10 // 2)
print(True + True, True == 1)          # bool is a kind of int
OUTPUT
False True True 5.0 5 2 True

SectionSection第 12 节

Complete Practice Program — Operators Sandbox 🧪पूरा अभ्यास Program — Operators Sandbox 🧪完整练习程序 —— 运算符沙盒 🧪

This script uses every operator family in one small order system. Type it out, run it, then change the price, quantity or permissions and predict the new output first.

यह script एक छोटे order system में हर operator परिवार इस्तेमाल करती है। इसे टाइप करें, चलाएँ, फिर price, quantity या permissions बदलें और पहले नया output अंदाज़ा लगाएँ।

这个脚本在一个小型订单系统中用到了所有运算符家族。把它敲一遍并运行,然后修改价格、数量或权限,先预测新的输出。

# operators_sandbox.py — every operator family in one script


def main():
    # arithmetic
    price = 999.00
    quantity = 3
    gst_rate = 0.18
    subtotal = price * quantity
    gst = subtotal * gst_rate
    total = subtotal + gst
    print("=== ORDER SUMMARY ===")
    print(f"Subtotal: ₹{subtotal:,.2f}")
    print(f"GST 18%:  ₹{gst:,.2f}")
    print(f"Total:    ₹{total:,.2f}")

    # assignment (compound)
    balance = 5000.00
    balance -= total
    balance += 500.00                     # refund
    print(f"Balance:  ₹{balance:,.2f}")

    # comparison + logical
    is_member = True
    discount = (quantity >= 3 or is_member) and balance > 0 and not total > 10_000
    print(f"Discount: {discount}")

    # membership
    payment_methods = {"card", "upi", "cash"}
    chosen = "upi"
    print(f"Paying via: {chosen}" if chosen in payment_methods else "Unsupported method")

    # identity
    error = None
    if error is None:
        print("Order processed successfully")

    # precedence
    print(f"Precedence: {2 + 3 * 4}, {(2 + 3) * 4}, {2 ** 3 ** 2}")

    # bitwise flags
    READ, WRITE, EXECUTE = 0b100, 0b010, 0b001
    permissions = READ | WRITE
    print(f"Permissions: {permissions:03b}")
    print(f"Can read?    {bool(permissions & READ)}")
    print(f"Can write?   {bool(permissions & WRITE)}")
    print(f"Can execute? {bool(permissions & EXECUTE)}")


if __name__ == "__main__":
    main()
OUTPUT
=== ORDER SUMMARY === Subtotal: ₹2,997.00 GST 18%: ₹539.46 Total: ₹3,536.46 Balance: ₹1,963.54 Discount: True Paying via: upi Order processed successfully Precedence: 14, 20, 512 Permissions: 110 Can read? True Can write? True Can execute? False

SectionSection第 13 节

Exercises — Test Your Understanding 🎯अभ्यास — अपनी समझ जाँचें 🎯练习 —— 检验你的理解 🎯

Predict each answer on paper first, then run the code. Every answer below was produced by Python.

पहले हर जवाब काग़ज़ पर अंदाज़ा लगाएँ, फिर code चलाएँ। नीचे का हर जवाब Python से बना है।

先在纸上预测每个答案,再运行代码。下面的每个答案都由 Python 计算得出。

🎯 Exercise 1 — Arithmetic predictionअभ्यास 1 — Arithmetic अंदाज़ा练习 1 —— 算术预测
Q1
7 + 3 * 2
Q2
(7 + 3) * 2
Q3
17 % 5
Q4
17 // 5
Q5
2 ** 3 ** 2
Q6
-3 ** 2
Q7
-17 % 5
Answersजवाब答案

Q1 = 13, Q2 = 20, Q3 = 2, Q4 = 3, Q5 = 512, Q6 = -9, Q7 = 3

🎯 Exercise 2 — Even or odd?अभ्यास 2 — Even या odd?练习 2 —— 奇数还是偶数?

Read a number and print whether it is even or odd. Bonus: say if it is divisible by 3, by 5, or by both. Check 15 first — why?

एक संख्या पढ़ें और बताएँ even है या odd। Bonus: बताएँ 3 से, 5 से, या दोनों से विभाज्य है। 15 पहले जाँचें — क्यों?

读入一个数,输出它是奇数还是偶数。附加题:判断它能否被 3、5 或两者同时整除。为什么要先检查 15?

Solution (run with input 45)हल (input 45 के साथ)参考答案(输入 45)
n = int(input("Enter a number: "))
if n % 2 == 0:
    print(f"{n} is even")
else:
    print(f"{n} is odd")

if n % 15 == 0:                 # divisible by 3 AND 5 → check this first
    print(f"{n} is divisible by both 3 and 5")
elif n % 3 == 0:
    print(f"{n} is divisible by 3")
elif n % 5 == 0:
    print(f"{n} is divisible by 5")
OUTPUT
Enter a number: 45 45 is odd 45 is divisible by both 3 and 5
🎯 Exercise 3 — Logic predictionअभ्यास 3 — Logic अंदाज़ा练习 3 —— 逻辑预测
Q1
True and False or True
Q2
not True or False
Q3
not (True or False)
Q4
5 > 3 and 2 < 1
Q5
"a" or "b"
Q6
0 and "hello"
Answersजवाब答案

Q1 = True, Q2 = False, Q3 = False, Q4 = False, Q5 = 'a', Q6 = 0

🎯 Exercise 4 — Simple calculatorअभ्यास 4 — सरल calculator练习 4 —— 简易计算器

Read two numbers and an operator (+ - * / // % **). Use in to check the operator, and refuse to divide by zero.

दो संख्याएँ और एक operator (+ - * / // % **) पढ़ें। Operator जाँचने के लिए in लगाएँ, और शून्य से भाग मना करें।

读入两个数和一个运算符(+ - * / // % **)。用 in 检查运算符是否有效,并拒绝除以零。

Solution (two real runs)हल (दो असली runs)参考答案(两次真实运行)
a = float(input("First number:  "))
op = input("Operator (+ - * / // % **): ")
b = float(input("Second number: "))

valid_ops = {"+", "-", "*", "/", "//", "%", "**"}
if op not in valid_ops:
    print("Invalid operator!")
elif op in {"/", "//", "%"} and b == 0:
    print("Cannot divide by zero!")
else:
    if op == "+":
        result = a + b
    elif op == "-":
        result = a - b
    elif op == "*":
        result = a * b
    elif op == "/":
        result = a / b
    elif op == "//":
        result = a // b
    elif op == "%":
        result = a % b
    else:
        result = a ** b
    print(f"{a} {op} {b} = {result}")
OUTPUT
First number: 7 Operator (+ - * / // % **): // Second number: 2 7.0 // 2.0 = 3.0 First number: 7 Operator (+ - * / // % **): % Second number: 0 Cannot divide by zero!
🎯 Exercise 5 — Password strengthअभ्यास 5 — Password की मज़बूती练习 5 —— 密码强度

A password is strong if it has 8+ characters, a digit, an uppercase and a lowercase letter. Combine all four checks into ONE expression with and.

Password मज़बूत है अगर उसमें 8+ characters, एक digit, एक uppercase और एक lowercase अक्षर हो। चारों जाँचों को and से एक expression में जोड़ें।

密码满足以下条件即为强密码:至少 8 个字符,包含数字、大写字母和小写字母。用 and 把四个检查合成一个表达式。

Solutionहल参考答案
def is_strong(password):
    return (len(password) >= 8 and
            any(c.isdigit() for c in password) and
            any(c.isupper() for c in password) and
            any(c.islower() for c in password))


for pw in ["hello", "hello123", "Hello123", "HELLO123"]:
    print(f"{pw:<9} → {'strong' if is_strong(pw) else 'weak'}")
OUTPUT
hello → weak hello123 → weak Hello123 → strong HELLO123 → weak
🎯 Exercise 6 — Leap yearअभ्यास 6 — Leap year练习 6 —— 闰年

A year is a leap year if it is divisible by 4, except years divisible by 100, unless also divisible by 400. Write it as one expression.

साल leap year है अगर 4 से विभाज्य हो, सिवाय उन सालों के जो 100 से विभाज्य हों, जब तक वे 400 से भी विभाज्य न हों। इसे एक expression में लिखें।

能被 4 整除的年份是闰年,但能被 100 整除的除外,除非它也能被 400 整除。用一个表达式写出来。

Solutionहल参考答案
for year in [2000, 2020, 2024, 2025, 2100]:
    is_leap = (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
    print(year, "leap" if is_leap else "not leap")
OUTPUT
2000 leap 2020 leap 2024 leap 2025 not leap 2100 not leap
LIVELIVE互动Leap-Year CheckerLeap-Year जाँचक闰年检查器

Type any year. Each part of the expression is coloured green (True) or red (False), so you can see which rule decided.

कोई भी साल लिखें। Expression का हर हिस्सा हरा (True) या लाल (False) रंगा है, ताकि दिखे कि किस नियम ने फ़ैसला किया।

输入任意年份。表达式的每一部分都标为绿色(True)或红色(False),一眼就能看出是哪条规则起了作用。


SectionSection第 14 节

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

🐍 Python Operators — 8 RulesPython Operators — 8 नियमPython 运算符 —— 8 条法则
1
When in doubt, use brackets. (a + b) * c is clearer than trusting the precedence table from memory.
शक हो तो brackets लगाएँ। (a + b) * c precedence table की याद पर भरोसे से ज़्यादा साफ़ है।
拿不准就加括号。(a + b) * c 比凭记忆依赖优先级表更清楚。
2
Never compare floats with ==. Use math.isclose(a, b).
Floats की तुलना == से न करें। math.isclose(a, b) लगाएँ।
不要用 == 比较浮点数。使用 math.isclose(a, b)。
3
Use is only for None (and true identity checks). Use == for numbers, strings and collections.
is सिर्फ़ None के लिए (और असली identity जाँच के लिए)। Numbers, strings और collections के लिए ==।
is 只用于 None(以及真正的身份检查)。数字、字符串和容器请用 ==。
4
Know your division. / always gives a float; // rounds down, even for negatives; % takes the sign of the divisor.
अपना division जानें। / हमेशा float देता है; // negatives में भी नीचे round करता है; % भाजक का चिह्न लेता है।
弄清除法。/ 总是返回浮点数;// 即使对负数也向下取整;% 的符号与除数相同。
5
Chain comparisons for ranges: 18 <= age < 65 reads like maths.
Ranges के लिए comparisons chain करें: 18 <= age < 65 गणित जैसा पढ़ता है।
区间判断用链式比较:18 <= age < 65 读起来就像数学式。
6
Remember ** is special. 2 ** 3 ** 2 is 512, and -2 ** 2 is −4.
याद रखें ** ख़ास है। 2 ** 3 ** 2 = 512, और -2 ** 2 = −4।
记住 ** 很特殊。2 ** 3 ** 2 是 512,-2 ** 2 是 −4。
7
Use in for membership instead of writing a loop, and use a set when you check the same collection many times.
Membership के लिए in लगाएँ, loop लिखने के बजाय, और एक ही collection बार-बार जाँचनी हो तो set इस्तेमाल करें।
用 in 判断成员,不要自己写循环;需要反复查找同一集合时使用 set。
8
Let short-circuiting work for you. Put the cheap or safe check first: x != 0 and total / x > 1.
Short-circuiting का फ़ायदा उठाएँ। सस्ती या सुरक्षित जाँच पहले रखें: x != 0 and total / x > 1।
善用短路。把开销小或保证安全的检查放在前面:x != 0 and total / x > 1。
LIVELIVE互动Quick Checkछोटी जाँच小测验

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

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

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

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

Operators are the verbs of Python. Arithmetic computes, comparison asks, logic combines (and short-circuits), assignment stores, bitwise flips bits, in searches, and is checks identity. Precedence decides the order — and when it is not obvious, brackets make it obvious. Most operator bugs come from a handful of traps: / vs //, is vs ==, float equality and -2 ** 2. Now you know them all.

Operators Python की क्रियाएँ हैं। Arithmetic गणना करता है, comparison पूछता है, logic जोड़ता है (और short-circuit करता है), assignment रखता है, bitwise bits पलटता है, in खोजता है, और is पहचान जाँचता है। Precedence क्रम तय करता है — और जब वह साफ़ न हो, तो brackets उसे साफ़ कर देते हैं। ज़्यादातर operator bugs कुछ ही जालों से आते हैं: / बनाम //, is बनाम ==, float समानता और -2 ** 2। अब आप ये सब जानते हैं।

运算符是 Python 的动词。算术负责计算,比较负责提问,逻辑负责组合(并会短路),赋值负责存储,位运算翻转二进制位,in 负责查找,is 负责检查身份。优先级决定执行顺序 —— 不明显时就用括号让它变得明显。大多数运算符 bug 都来自几个陷阱:/ 与 //、is 与 ==、浮点相等以及 -2 ** 2。现在你都掌握了。

🐍 Try Python Yourself

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