LearningPython TutorialOperators & Type Conversion
CHAPTER 4 · PYTHON BASICS

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.

English + Hinglish52 min readOnline practice included

What is an operator?

An operator is a symbol or keyword that tells Python to perform an operation on one or more values.

basic-operators.pyPython
price = 500
quantity = 3

total = price * quantity
print(total)
Hinglish Explanation

Yahan * multiplication operator hai. price aur quantity operands hain, aur result total me store ho raha hai.

Try it Yourself →

Arithmetic operators

arithmetic.pyPython
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.

Negative numbers: -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.

minutes.pyPython
total_minutes = 135
hours = total_minutes // 60
minutes = total_minutes % 60

print(hours, "hours", minutes, "minutes")

Run division example →

Assignment operators

Compound assignment current value par operation karke name ko new result se rebind karta hai.

assignment.pyPython
score = 10
score += 5
score *= 2
score -= 4

print(score)

Common forms include +=, -=, *=, /=, //=, %= and **=.

Comparison operators

Comparisons normally True or False return karte hain.

comparison.pyPython
age = 21

print(age == 21)
print(age != 18)
print(age > 18)
print(age < 30)
print(age >= 21)
print(age <= 21)
Important: = assignment hai; == equality comparison hai.

Chained comparisons

Python readable chained comparisons support karta hai.

range-check.pyPython
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

logical.pyPython
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.

short-circuit.pyPython
name = ""

display_name = name or "Guest"
print(display_name)
Nuance: Python ke 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.

membership.pyPython
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.

identity.pyPython
value = None

print(value is None)
print(value is not None)
Best practice: Values compare karne ke liye normally == 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.

precedence.pyPython
result = 2 + 3 * 4
print(result)      # 14

clear_result = (2 + 3) * 4
print(clear_result)  # 20

Complex 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.

conversion.pyPython
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))

Try conversions →

int() and float()

int() integer-compatible input convert karta hai. float() decimal-compatible input convert karta hai.

number-conversion.pyPython
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.

Common trap: 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.

string-conversion.pyPython
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.

bool-conversion.pyPython
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.

numeric-promotion.pyPython
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

invalid-conversion.pyPython
# ValueError:
# age = int("twenty")

# TypeError:
# total = "10" + 5

User 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.
  • is ko 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/or ko 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 ==, None checks ke liye is None use 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 in ka purpose clear hai?
  • is aur == 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.

  1. item_price = 249.5 and quantity = 3 variables banao.
  2. Subtotal calculate karo.
  3. 10% discount ko decimal value se calculate karo.
  4. Discounted amount calculate karo.
  5. 18% tax calculate karo.
  6. Final total print karo.
  7. Final total ko str() se label ke saath combine karke print karo.
  8. Check karo final total 500 se greater hai ya nahi.
  9. Ek boolean is_large_order me comparison result store karo.
  10. type() se subtotal, final total and boolean ka type print karo.
  11. "249" string ko integer me convert karke separate test karo.
  12. Intentional int("249.5") error observe karo, phir correct conversion path try karo.