Python Notes
Python ke sabhi operators — arithmetic, comparison, logical, bitwise, assignment, identity, membership, aur walrus — examples aur precedence table ke saath complete guide.
Hindi: Operators wo symbols hain jo operations perform karte hain. Jaise maths mein+,-,×,÷hote hain, waise hi Python mein bahut saare operators hain — arithmetic se lekar bitwise tak!
2. Arithmetic Operators
Hindi: Arithmetic operators mathematical calculations ke liye use hote hain — jamate hain, ghatate hain, gunna karte hain, etc.
a = 17
b = 5
print(f"a = {a}, b = {b}")
print(f"Addition (+): {a} + {b} = {a + b}")
print(f"Subtraction (-): {a} - {b} = {a - b}")
print(f"Multiplication (*): {a} * {b} = {a * b}")
print(f"Division (/): {a} / {b} = {a / b}") # Always float
print(f"Floor Division (//): {a} // {b} = {a // b}") # Integer part
print(f"Modulo (%): {a} % {b} = {a % b}") # Remainder
print(f"Exponentiation (**): {a} ** {b} = {a ** b}") # Powera = 17, b = 5 Addition (+): 17 + 5 = 22 Subtraction (-): 17 - 5 = 12 Multiplication (*): 17 * 5 = 85 Division (/): 17 / 5 = 3.4 Floor Division (//): 17 // 5 = 3 Modulo (%): 17 % 5 = 2 Exponentiation (**): 17 ** 5 = 1419857
Division Explained
# Regular division always returns float
print(10 / 2) # 5.0 (not 5!)
print(7 / 2) # 3.5
# Floor division — always rounds DOWN (toward negative infinity)
print(7 // 2) # 3
print(-7 // 2) # -4 ← rounds DOWN, not toward zero!
print(7 // -2) # -4 ← same rule
# Modulo — remainder
print(10 % 3) # 1
print(-10 % 3) # 2 ← Python modulo always non-negative when divisor is positive
print(10 % -3) # -2
# Relationship: a == (a // b) * b + (a % b)
a, b = 17, 5
print(f"\nVerify: {a} == ({a}//{b})*{b} + {a}%{b}")
print(f" {a} == {a//b}*{b} + {a%b}")
print(f" {a} == {(a//b)*b + a%b}")5.0
3.5
3
-4
-4
1
2
-2
Verify: 17 == (17//5)*5 + 17%5
17 == 3*5 + 2
17 == 17Practical Uses of % (Modulo)
# Check even/odd
for i in range(1, 11):
status = "Even" if i % 2 == 0 else "Odd"
print(f"{i}: {status}", end=" ")
print()
# Check divisibility
print(f"\n100 divisible by 7? {100 % 7 == 0}") # False
print(f"100 divisible by 5? {100 % 5 == 0}") # True
# Clock wrap-around (circular)
hour = 11
hours_later = 5
new_hour = (hour + hours_later) % 24
print(f"\n{hour}:00 + {hours_later} hours = {new_hour}:00") # 16:00
# Last N digits
big_number = 1234567890
last_4 = big_number % 10000
print(f"Last 4 digits of {big_number}: {last_4:04d}")1: Odd 2: Even 3: Odd 4: Even 5: Odd 6: Even 7: Odd 8: Even 9: Odd 10: Even 100 divisible by 7? False 100 divisible by 5? True 11:00 + 5 hours = 16:00 Last 4 digits of 1234567890: 7890
String & List Operators
Hello World HelloHelloHello [1, 2, 3, 4, 5, 6] [1, 2, 3, 1, 2, 3] ----------------------------------------
3. Comparison Operators
Hindi: Comparison operators do values ko compare karte hain aurTrueyaFalsereturn karte hain.
a, b = 10, 20
print(f"a={a}, b={b}")
print(f"a == b : {a == b}") # Equal to
print(f"a != b : {a != b}") # Not equal to
print(f"a > b : {a > b}") # Greater than
print(f"a < b : {a < b}") # Less than
print(f"a >= b : {a >= b}") # Greater than or equal
print(f"a <= b : {a <= b}") # Less than or equala=10, b=20 a == b : False a != b : True a > b : False a < b : True a >= b : False a <= b : True
Chained Comparisons (Python's Superpower!)
# Python allows mathematical-style chaining
x = 15
# Without chaining (other languages)
result = x > 10 and x < 20
print(result)
# With chaining (Python style) — much cleaner!
result = 10 < x < 20
print(result)
# More examples
age = 25
print(f"18 <= {age} <= 65: {18 <= age <= 65}") # Working age
marks = 75
print(f"60 <= {marks} <= 79: {60 <= marks <= 79}") # Grade C range
# Chained works left to right
print(f"1 < 2 < 3: {1 < 2 < 3}") # True
print(f"1 < 3 < 2: {1 < 3 < 2}") # False (3 < 2 is False)True True 18 <= 25 <= 65: True 60 <= 75 <= 79: True 1 < 2 < 3: True 1 < 3 < 2: False
Comparing Different Types
True False True True True True True
4. Logical Operators
Hindi: Logical operators boolean conditions ko combine karne ke liye use hote hain.
# Truth table examples
print("AND (and):")
print(f"True and True = {True and True}")
print(f"True and False = {True and False}")
print(f"False and True = {False and True}")
print(f"False and False = {False and False}")
print("\nOR (or):")
print(f"True or True = {True or True}")
print(f"True or False = {True or False}")
print(f"False or True = {False or True}")
print(f"False or False = {False or False}")
print("\nNOT (not):")
print(f"not True = {not True}")
print(f"not False = {not False}")AND (and): True and True = True True and False = False False and True = False False and False = False OR (or): True or True = True True or False = True False or True = True False or False = False NOT (not): not True = False not False = True
Short-Circuit Evaluation
0 hello [] hello 5 [1, 2] Display name: Guest Safe division: 0
Logical Operators with Non-Boolean Values
# Real-world use: configuration with defaults
config_debug = None
debug_mode = config_debug or False
name = " " # whitespace only
valid_name = name.strip() or "Anonymous"
score = 0
display = score or "No score yet"
print(f"debug_mode: {debug_mode}")
print(f"valid_name: {valid_name}")
print(f"display: {display}")debug_mode: False valid_name: Anonymous display: No score yet
5. Assignment Operators
x = 100
print(f"Initial: x = {x}")
x += 20; print(f"x += 20 → {x}") # x = x + 20
x -= 15; print(f"x -= 15 → {x}") # x = x - 15
x *= 2; print(f"x *= 2 → {x}") # x = x * 2
x /= 7; print(f"x /= 7 → {x:.4f}") # x = x / 7
x = 100 # reset
x //= 7; print(f"x //= 7 → {x}") # x = x // 7
x %= 4; print(f"x %= 4 → {x}") # x = x % 4
x = 2
x **= 10; print(f"x **= 10 → {x}") # x = x ** 10Initial: x = 100 x += 20 → 120 x -= 15 → 105 x *= 2 → 210 x /= 7 → 30.0000 x //= 7 → 14 x %= 4 → 2 x **= 10 → 1024
Bitwise Assignment Operators
x = 0b1010 # 10 in binary
print(f"Initial: x = {x} ({bin(x)})")
x &= 0b1100; print(f"x &= 0b1100 → {x} ({bin(x)})") # AND
x = 0b1010
x |= 0b0101; print(f"x |= 0b0101 → {x} ({bin(x)})") # OR
x = 0b1010
x ^= 0b1111; print(f"x ^= 0b1111 → {x} ({bin(x)})") # XOR
x = 8
x >>= 1; print(f"x >>= 1 → {x} ({bin(x)})") # Right shift
x <<= 2; print(f"x <<= 2 → {x} ({bin(x)})") # Left shiftInitial: x = 10 (0b1010) x &= 0b1100 → 8 (0b1000) x |= 0b0101 → 15 (0b1111) x ^= 0b1111 → 5 (0b101) x >>= 1 → 4 (0b100) x <<= 2 → 16 (0b10000)
6. Identity Operators (is, is not)
Hindi: Identity operators check karte hain ki do variables same memory location (object) point kar rahe hain ya nahi.==value check karta hai,ismemory address check karta hai.
a == c: True a is c: False a is b: True id(a): 140234567890 (some address) id(b): 140234567890 (same as a) id(c): 140234567891 (different) x is y (100 is 100): True x is y (1000 is 1000): False value is None: True value is not None: False
7. Membership Operators (in, not in)
Hindi: Membership operators check karte hain ki koi value kisi sequence (list, string, tuple, dict, set) mein hai ya nahi.
True False True True False True False False 'DEL' in codes: True 'LON' in codes: False
# Practical use: input validation
def validate_grade(grade):
valid_grades = {"A+", "A", "B", "C", "D", "F"}
if grade.upper() in valid_grades:
return f"Valid grade: {grade.upper()}"
return f"Invalid grade: {grade}"
print(validate_grade("A"))
print(validate_grade("B"))
print(validate_grade("E"))
print(validate_grade("Z"))Valid grade: A Valid grade: B Invalid grade: E Invalid grade: Z
8. Bitwise Operators
Hindi: Bitwise operators numbers ke binary representation par operate karte hain. Yeh low-level programming, networking, aur performance-critical code mein use hote hain.
a = 0b1010 # 10
b = 0b1100 # 12
print(f"a = {a:4d} = {a:04b}")
print(f"b = {b:4d} = {b:04b}")
print()
# AND (&) — 1 only if BOTH bits are 1
print(f"a & b = {a & b:4d} = {a & b:04b} (AND)")
# OR (|) — 1 if EITHER bit is 1
print(f"a | b = {a | b:4d} = {a | b:04b} (OR)")
# XOR (^) — 1 if bits are DIFFERENT
print(f"a ^ b = {a ^ b:4d} = {a ^ b:04b} (XOR)")
# NOT (~) — flip all bits
print(f"~a = {~a:4d} = {~a & 0xFFFF:016b}... (NOT)")
# Left shift (<<) — multiply by 2^n
print(f"a << 1 = {a << 1:4d} = {a << 1:04b} (Left shift × 2)")
print(f"a << 2 = {a << 2:4d} = {a << 2:04b} (Left shift × 4)")
# Right shift (>>) — divide by 2^n
print(f"a >> 1 = {a >> 1:4d} = {a >> 1:04b} (Right shift ÷ 2)")a = 10 = 1010 b = 12 = 1100 a & b = 8 = 1000 (AND) a | b = 14 = 1110 (OR) a ^ b = 6 = 0110 (XOR) ~a = -11 = 1111111111110101... (NOT) a << 1 = 20 = 10100 (Left shift × 2) a << 2 = 40 = 101000 (Left shift × 4) a >> 1 = 5 = 101 (Right shift ÷ 2)
Practical Bitwise Uses
# Fast multiply/divide by powers of 2
x = 256
print(f"{x} * 4 = {x * 4}") # normal
print(f"{x} << 2 = {x << 2}") # fast (bit shift)
# Permission flags (used in Unix file permissions)
READ = 0b100 # 4
WRITE = 0b010 # 2
EXECUTE = 0b001 # 1
# Grant read + write
permission = READ | WRITE
print(f"\nPermission: {permission:03b} ({permission})")
# Check if write permission is set
has_write = bool(permission & WRITE)
print(f"Has WRITE: {has_write}")
has_execute = bool(permission & EXECUTE)
print(f"Has EXECUTE: {has_execute}")
# Revoke write permission
permission &= ~WRITE
print(f"After revoking WRITE: {permission:03b} ({permission})")256 * 4 = 1024 256 << 2 = 1024 Permission: 110 (6) Has WRITE: True Has EXECUTE: False After revoking WRITE: 100 (4)
9. Walrus Operator := (Python 3.8+)
Hindi: Walrus operator := ek hi expression mein assign bhi karta hai aur use bhi karta hai — "assign and use in one step."Long list! Length = 10 Long list! Length = 10 Rolling dice until you get 6: Rolled: 3 Rolled: 1 Rolled: 4 Rolled: 6! Total before 6: 8
10. Ternary / Conditional Expression
# Python's ternary operator (conditional expression)
# value_if_true if condition else value_if_false
age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)
marks = 75
grade = (
"A+" if marks >= 90 else
"A" if marks >= 80 else
"B" if marks >= 70 else
"C" if marks >= 60 else
"D" if marks >= 45 else
"F"
)
print(f"Marks: {marks} → Grade: {grade}")Adult Marks: 75 → Grade: B
11. Operator Precedence Table
# Precedence examples
print(2 + 3 * 4) # 14, not 20 (* before +)
print((2 + 3) * 4) # 20 (parentheses first)
print(2 ** 3 ** 2) # 512 (3**2=9, then 2**9=512 — right to left!)
print(10 - 3 - 2) # 5 (left to right: 10-3=7, 7-2=5)
# Complex expression
x = 3
result = x + 2 * x ** 2 - 1
# = 3 + 2 * (3^2) - 1
# = 3 + 2 * 9 - 1
# = 3 + 18 - 1
# = 20
print(f"\nx + 2*x**2 - 1 = {result}") # 20
# Add parentheses for clarity!
result_clear = x + (2 * (x ** 2)) - 1
print(f"With parens: = {result_clear}") # same14 20 512 5 x + 2*x**2 - 1 = 20 With parens: = 20
12. Real-World Example: Grade & Attendance System
╔══════════════════════════════════╗ ║ STUDENT EVALUATION REPORT ║ ╠══════════════════════════════════╣ ║ Name: Priya Sharma ║ ║ Marks: 430/500 (86.0%) ║ ║ Attendance: 92.5% ║ ║ Grade: A ║ ║ Result: PASS ║ ║ Scholarship: None ║ ╚══════════════════════════════════╝
Practice Exercises
Exercise 1 — Operator Practice
Without running the code, predict each output:
print(15 // 4)
print(15 % 4)
print(2 ** 8)
print(10 > 5 > 3)
print(True + True + True)
print("hello" * 3)
print(not (5 > 3 and 2 < 1))Exercise 2 — Bitwise Operations
Without built-in functions, use bitwise operators to:
- Check if a number is even or odd
- Multiply a number by 8 using shifts
- Swap two numbers without a temporary variable (using XOR!)
Exercise 3 — Salary Calculator
Input: basic salary. Calculate using operators:
- HRA = 40% of basic
- DA = 15% of basic
- Tax = 10% of (basic + HRA + DA) if total > 30000 else 0
- Net salary = basic + HRA + DA - tax
Interview Questions
Q1. What is the difference between / and // in Python? > / always returns a float (true division). // returns an integer (floor division) — it rounds DOWN toward negative infinity. 7/2 = 3.5, 7//2 = 3, -7//2 = -4 (rounds toward -∞, not toward 0).
Q2. What is the difference between == and is? > == compares values (calls __eq__), is compares identity (same memory address). [1,2] == [1,2] is True (same values), but [1,2] is [1,2] is False (different objects). Always use is for None, True, False comparisons.
Q3. Explain short-circuit evaluation in Python. > and evaluates left to right and stops (returns value) at the first falsy value. or stops at the first truthy value. This prevents unnecessary evaluation: y and (x/y) won't divide when y=0.
Q4. What does 5 2 3 evaluate to? Explain why. > It evaluates to 390625 (5 8). is right-associative, so 2 3 = 8 is evaluated first, then 5 8 = 390625. This is different from left-to-right evaluation which would give (52)3 = 25**3 = 15625.
Q5. What are membership operators and what is their time complexity? > in and not in check for membership. Time complexity: O(n) for lists/tuples, O(1) for sets/dict-keys (hash lookup). For large membership checks, use sets instead of lists for performance.
⚠️ Common Mistakes
1. = vs == confuse karna 🚫
Galti: if x = 5: likhna (assignment) instead of if x == 5: (comparison). Python mein yeh SyntaxError dega, but logic mein confusion hota hai beginners ko.
2. / aur // ka farak na samajhna 🔢
Galti: Sochna ki 10 / 2 integer 5 dega — actually yeh 5.0 (float) deta hai! Integer result chahiye toh 10 // 2 use karo.
# ❌ Wrong assumption
result = 10 / 2 # 5.0, NOT 5!
# ✅ Correct
result = 10 // 2 # 53. is ko == ki jagah use karna 🧠
Galti: if my_list is [1, 2, 3]: — yeh hamesha False hoga kyunki yeh memory address compare karta hai! Values compare karne ke liye == use karo. is sirf None, True, False ke saath use karo.
4. Operator precedence ignore karna 📐
Galti: 2 + 3 * 4 ko 20 samajhna — actually yeh 14 hai kyunki * pehle execute hota hai! Jab doubt ho, parentheses () use karo.
# ❌ Expecting 20
print(2 + 3 * 4) # 14 (* has higher precedence)
# ✅ Use parentheses
print((2 + 3) * 4) # 205. not, and, or ka order galat samajhna 🔄
Galti: Sochna ki not x or y matlab hai not (x or y) — actually yeh (not x) or y hai! not ki precedence sabse zyada hai logical operators mein.
# ❌ Wrong assumption
not True or True # = (not True) or True = False or True = True
# NOT same as:
not (True or True) # = not True = False6. Negative numbers ke saath // aur % ka confusion 😵
Galti: -7 // 2 ko -3 samajhna — actually yeh -4 hai! Python hamesha negative infinity ki taraf round karta hai (floor division).
# ❌ Wrong: thinking it truncates toward zero
print(-7 // 2) # -4 (not -3!) — rounds toward -∞
print(-7 % 2) # 1 (not -1!)7. Mutable objects ke saath * operator ka trap 🪤
Galti: [[]] * 3 se 3 independent lists milegi — NAHI! Sab same object ki references hain.
✅ Key Takeaways
- 🎯 Python mein 8 types ke operators hain: Arithmetic, Comparison, Logical, Assignment, Identity, Membership, Bitwise, aur Walrus (
:=).
- 🔢
/hamesha float return karta hai (10/2 = 5.0), integer chahiye toh//use karo. Floor division hamesha negative infinity ki taraf round karta hai.
- ⚖️
==value compare karta hai,ismemory address (identity) compare karta hai.Nonecheck ke liye hameshais Noneuse karo,== Nonenahi.
- ⚡ Short-circuit evaluation bahut powerful hai —
andpehle falsy value par rukta hai,orpehle truthy value par. Default values set karne ke liye:name = user_input or "Guest".
- 📐 Operator precedence yaad rakho:
**> unary >* / // %>+ -> comparisons >not>and>or. Jab doubt ho, parentheses use karo!
- 🔗 Comparison chaining Python ki superpower hai —
10 < x < 20likhnax > 10 and x < 20se cleaner aur readable hai.
- 🧮 Bitwise operators permissions, flags, aur fast multiply/divide ke liye useful hain.
<<multiply by 2,>>divide by 2. Sets ke operations bhi bitwise jaisi hain.
- 🦦 Walrus operator
:=(Python 3.8+) ek expression mein assign + use dono karta hai — loops aur conditions mein code concise banata hai.
- 🏎️ Membership check (
in) sets mein O(1) hai aur lists mein O(n). Large data ke saath hamesha set use karo for fast lookups.
- 📝 Augmented assignment (
+=,-=,*=, etc.) code shorter aur readable banate hain. Yeh new object create karte hain immutable types (int, str, tuple) ke liye.
❓ FAQ
Q1. == aur is mein kya farak hai? Kab kaunsa use karna chahiye? > == values compare karta hai (content check), jabki is identity check karta hai (same memory object hai ya nahi). Rule: None, True, False ke liye hamesha is use karo. Baaki sab ke liye == use karo. Example: [1,2] == [1,2] ✅ True, but [1,2] is [1,2] ❌ False (alag objects hain memory mein).
Q2. Python mein operator precedence kaise yaad karein? > Simple rule: P-E-MD-AS-C-L — Parentheses > Exponent (**) > Multiply/Divide/Mod > Add/Subtract > Comparisons > Logical (not > and > or). Jab bhi doubt ho, parentheses () laga do — code readable bhi hoga aur bug-free bhi!
Q3. and aur or operators actual values return karte hain ya sirf True/False? > Python mein and/or actual values return karte hain, sirf True/False nahi! 5 and "hello" returns "hello", 0 or "default" returns "default". Yeh feature default values set karne mein bahut kaam aata hai: name = user_input or "Guest".
Q4. Floor division (//) negative numbers ke saath kaise kaam karta hai? > // hamesha negative infinity ki taraf round karta hai (floor). Isliye -7 // 2 = -4 (not -3!). Yeh C/Java se alag hai jahan truncation toward zero hota hai. Relationship yaad rakho: a == (a // b) * b + (a % b) hamesha true hoti hai.
Q5. Walrus operator := kab use karna chahiye? > Walrus operator tab useful hai jab aapko ek value assign bhi karni ho aur turant use bhi. Best cases: while loops (while (line := input()) != "quit"), list comprehensions with filtering, aur if conditions jahan computed value baad mein chahiye. Overuse mat karo — readability important hai!
Q6. Bitwise operators ka real-world mein kya use hai? Kya beginners ko seekhna zaroori hai? > Bitwise operators permission systems (Unix file permissions), feature flags, networking (IP masking), aur performance optimization (fast multiply/divide by 2) mein use hote hain. Beginners ke liye initially zaroori nahi, but interviews mein puchha jaata hai aur system programming mein must hai.
Q7. not in aur not x in y mein koi farak hai? > Technically dono same hain — x not in y aur not (x in y) same result dete hain. But x not in y zyada Pythonic aur readable hai. PEP 8 bhi isi ko recommend karta hai. Same applies to is not vs not ... is.
Q8. Python mein ++ ya -- operator kyun nahi hai? > Python mein ++/-- (increment/decrement) operators intentionally nahi hain. Iske jagah x += 1 aur x -= 1 use karo. Reason: Python ki philosophy hai explicit > implicit, aur ++ se related bugs (pre vs post increment) avoid hote hain. Plus, Python mein integers immutable hain toh in-place increment ka concept hi nahi lagta.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Operators.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Python Master Course topic.
Search Terms
python-master-course, python master course, python, master, course, basics, operators, python operators
Related Python Master Course Topics