🔄
Basics

Type Conversion

int(), float(), str()
💡 Type conversion ek currency exchange jaisa hai — same "value" ko alag "form" mein convert karna (jaise "5" string ko 5 integer mein), taaki us form ke saath valid operations kar sako.

Python explicit conversion functions deta hai: int(), float(), str(), bool() — koi bhi compatible value ko convert kar sakte ho. Ye C++ ke static_cast<> jaisa concept hai, lekin function-call syntax mein.

age_str = "25"
age_num = int(age_str)     # string se int
print(age_num + 5)           # 30

price = 19.99
price_str = str(price)      # float se string
print("Price: " + price_str)

x = int("10.5")   # ERROR! int() decimal string ko directly convert nahi karega
y = int(float("10.5"))  # correct way: pehle float, phir int — 10
🔄
Type conversion ek currency exchange jaisa hai — same "value" ko alag "form" mein convert karna (jaise "5" string ko 5 integer mein), taaki us form ke saath valid operations kar sako.
1 / 2
⚡ Quick Recap
  • int(), float(), str(), bool() — explicit conversion functions
  • Incompatible conversions ValueError throw karte hain
  • Decimal string ko int mein convert karne ke liye pehle float() se guzaro
Is page mein (1 subtopics)

type(x) == int se compare karne ke bajaye, isinstance(x, int) use karna better hai — ye inheritance ko bhi correctly handle karta hai (jaise bool actually int ka subclass hai Python mein, isinstance() isse sahi handle karta hai).

x = 5
print(isinstance(x, int))    # True
print(isinstance(True, int)) # True! bool, int ka subclass hai Python mein

def process(value):
    if isinstance(value, (int, float)):   # multiple types check
        return value * 2
    return None
💡Tip: isinstance() ka second argument ek tuple of types bhi le sakta hai — isinstance(x, (int, float)) "x int ya float hai" check karta hai, ek hi call mein.