Python Operators & Type Conversion
Operators values par calculations, comparisons aur logical checks perform karte hain. Is chapter me arithmetic, assignment, comparison, logical, membership, identity operators, precedence aur explicit type conversion ko practical examples ke saath samjhenge.
What is an operator?
An operator is a symbol or keyword that tells Python to perform an operation on one or more values.
price = 500
quantity = 3
total = price * quantity
print(total)Yahan * multiplication operator hai. price aur quantity operands hain, aur result total me store ho raha hai.
Arithmetic operators
a = 17
b = 5
print(a + b) # addition: 22
print(a - b) # subtraction: 12
print(a * b) # multiplication: 85
print(a / b) # true division: 3.4
print(a // b) # floor division: 3
print(a % b) # remainder: 2
print(a ** 2) # exponent: 289/ generally floating-point result deta hai, while // mathematical floor ki direction me round down karta hai.
-17 // 5 ka result -4 hota hai, because floor division zero ki taraf truncate nahi karti.Division, remainder and practical use
Floor division aur modulo together grouping, pagination aur time conversion jaise tasks me useful hote hain.
total_minutes = 135
hours = total_minutes // 60
minutes = total_minutes % 60
print(hours, "hours", minutes, "minutes")Assignment operators
Compound assignment current value par operation karke name ko new result se rebind karta hai.
score = 10
score += 5
score *= 2
score -= 4
print(score)Common forms include +=, -=, *=, /=, //=, %= and **=.
Comparison operators
Comparisons normally True or False return karte hain.
age = 21
print(age == 21)
print(age != 18)
print(age > 18)
print(age < 30)
print(age >= 21)
print(age <= 21)= assignment hai; == equality comparison hai.Chained comparisons
Python readable chained comparisons support karta hai.
age = 25
print(18 <= age <= 60)Ye conceptually age >= 18 and age <= 60 ke similar intent ko compact form me express karta hai.
Logical operators: and, or, not
is_logged_in = True
has_access = False
print(is_logged_in and has_access)
print(is_logged_in or has_access)
print(not is_logged_in)and ko both sides truthy chahiye; or ko at least one truthy value; not truth value ko invert karta hai.
Short-circuit evaluation
and aur or left-to-right evaluate hote hain and result decide hote hi remaining expression skip kar sakte hain.
name = ""
display_name = name or "Guest"
print(display_name)and/or always literal booleans return nahi karte; they return one of their operands. Beginner conditions me is behavior ko carefully use karo.Membership operators: in and not in
Membership operators check karte hain ki value container me present hai ya nahi.
course = "Python"
print("Py" in course)
print("Java" not in course)Lists, tuples, sets aur dictionaries ke saath membership ko later chapters me detail me use karenge.
Identity operators: is and is not
is equality nahi, object identity check karta hai.
value = None
print(value is None)
print(value is not None)== use karo. None ko check karne ke liye is None preferred hai.Operator precedence
Operators same priority se execute nahi hote. Multiplication usually addition se pehle evaluate hoti hai.
result = 2 + 3 * 4
print(result) # 14
clear_result = (2 + 3) * 4
print(clear_result) # 20Complex expression me parentheses intent ko clear banate hain, even when precedence already correct ho.
What is type conversion?
Type conversion means value ko one type se another type me convert karna, when conversion meaningful and supported ho.
age_text = "21"
age = int(age_text)
price = float("199.50")
label = str(500)
print(age, type(age))
print(price, type(price))
print(label, type(label))int() and float()
int() integer-compatible input convert karta hai. float() decimal-compatible input convert karta hai.
print(int("42"))
print(float("42"))
print(int(3.9))
print(int(-3.9))int(3.9) fractional part remove karke 3 deta hai; int(-3.9) -3 deta hai. Ye floor operation nahi, truncation toward zero hai.
int("3.9") directly valid nahi hai. String integer format me nahi hai; float("3.9") first relevant ho sakta hai if that conversion matches your intent.str() conversion
str() value ka text representation banata hai.
score = 95
message = "Score: " + str(score)
print(message)Python number ko string ke saath automatically concatenate nahi karta.
bool() and truthy/falsy values
bool() value ki truth value convert karta hai.
print(bool(0))
print(bool(1))
print(bool(""))
print(bool("Python"))
print(bool(None))Common falsy values include numeric zero, empty strings/containers and None. Most other normal values truthy hote hain.
Implicit numeric conversion
Some numeric operations me Python compatible types ko automatically promote kar sakta hai.
result = 10 + 2.5
print(result)
print(type(result))Here int and float operation produces a float. But unrelated types ke beech arbitrary implicit conversion expect mat karo.
Conversion errors
# ValueError:
# age = int("twenty")
# TypeError:
# total = "10" + 5User input convert karte waqt invalid values possible hain. Exception handling Chapter 14 me detail me cover hoga.
Bitwise operators — brief preview
Python integers ke saath &, |, ^, ~, << and >> bitwise operators support karta hai. Beginner general application code me ye arithmetic/logical operators se less common hain, so inhe abhi recognize karna enough hai.
Common beginner mistakes
=aur==confuse karna./aur//ka difference ignore karna.- Negative floor division ko zero-toward truncation samajhna.
isko value equality ke liye use karna.int("3.5")ko valid assume karna.- Number aur string ko directly
+se combine karna. - Operator precedence blindly assume karna.
and/orko always boolean-returning samajhna.- Invalid user input conversion errors ignore karna.
Beginner best practices
- Complex expressions me parentheses se intent clear karo.
- Value equality ke liye
==,Nonechecks ke liyeis Noneuse karo. - Conversion intentional rakho; data format pehle samjho.
- User input ko blindly
int()/float()mat karo without considering invalid input. - Currency/exact decimal problems me floating-point limitations yaad rakho.
- Examples ka output run karne se pehle predict karo.
Chapter checklist
- Arithmetic operators ka difference clear hai?
/,//and%use kar sakte ho?- Comparison and logical operators samajh aaye?
in/not inka purpose clear hai?isaur==ka difference clear hai?- Operator precedence me parentheses kab useful hain?
int(),float(),str(),bool()use kar sakte ho?- Invalid conversion se error aa sakta hai ye clear hai?
Practice Task — Simple Bill Calculator
Playground me small bill calculator banao.
item_price = 249.5andquantity = 3variables banao.- Subtotal calculate karo.
- 10% discount ko decimal value se calculate karo.
- Discounted amount calculate karo.
- 18% tax calculate karo.
- Final total print karo.
- Final total ko
str()se label ke saath combine karke print karo. - Check karo final total 500 se greater hai ya nahi.
- Ek boolean
is_large_orderme comparison result store karo. type()se subtotal, final total and boolean ka type print karo."249"string ko integer me convert karke separate test karo.- Intentional
int("249.5")error observe karo, phir correct conversion path try karo.