Python Notes
Python mein ek data type se doosre mein convert karna — int(), float(), str(), bool(), list(), tuple(), set(), dict() — implicit aur explicit casting ke saath complete guide.
Hindi: Type casting matlab ek data type ko doosre data type mein convert karna. Jaise Indian Rupees ko Dollars mein convert karte hain, waise hi Python meinintkostryafloatkointmein convert kar sakte hain.
2. Implicit Type Conversion
Python automatically converts types to avoid data loss in expressions.
Hindi: Implicit conversion mein Python khud hi type change kar deta hai bina aapko kuch kiye. Yeh mostly numeric operations mein hota hai.
# int + float → float (Python auto-promotes)
a = 10 # int
b = 3.14 # float
result = a + b
print(f"{a} + {b} = {result}")
print(f"Type: {type(result)}")
# int + bool → int
x = 5
y = True # True = 1
result2 = x + y
print(f"\n{x} + True = {result2}")
print(f"Type: {type(result2)}")
# int + complex → complex
p = 4
q = 2 + 3j
result3 = p + q
print(f"\n{p} + {q} = {result3}")
print(f"Type: {type(result3)}")10 + 3.14 = 13.14 Type: <class 'float'> 5 + True = 6 Type: <class 'int'> 4 + (2+3j) = (6+3j) Type: <class 'complex'>
Implicit Conversion Hierarchy
3. Explicit Type Conversion — int()
Hindi: int() function kisi bhi value ko integer mein convert karta hai.# String to int
age_str = "25"
age = int(age_str)
print(f"'{age_str}' → {age}")
print(f"Type: {type(age)}")
# Float to int (truncates decimal, does NOT round)
pi = 3.99
pi_int = int(pi)
print(f"\n{pi} → {pi_int}") # 3, NOT 4!
price = -7.8
print(f"{price} → {int(price)}") # -7 (toward zero)
# Bool to int
print(f"\nTrue → {int(True)}") # 1
print(f"False → {int(False)}") # 0
# Different number bases
print(f"\nBinary '1010' → {int('1010', 2)}") # base 2 → 10
print(f"Octal '17' → {int('17', 8)}") # base 8 → 15
print(f"Hex 'FF' → {int('FF', 16)}") # base 16 → 255
print(f"Base 36 'z' → {int('z', 36)}") # base 36 → 35'25' → 25 Type: <class 'int'> 3.99 → 3 -7.8 → -7 True → 1 False → 0 Binary '1010' → 10 Octal '17' → 15 Hex 'FF' → 255 Base 36 'z' → 35
What int() CANNOT Convert
ValueError: invalid literal for int() with base 10: 'hello' ValueError: invalid literal for int() with base 10: '3.14' TypeError: int() argument must be a string, a bytes-like object or a real number, not 'list' '3.14' string → int: 3
4. Explicit Type Conversion — float()
# int to float
x = 42
print(f"{x} → {float(x)}")
# String to float
price_str = "299.99"
price = float(price_str)
print(f"'{price_str}' → {price}")
print(f"Type: {type(price)}")
# Scientific notation string
sci = float("1.5e10")
print(f"'1.5e10' → {sci}")
# Bool to float
print(f"True → {float(True)}")
print(f"False → {float(False)}")
# Special float values
inf = float('inf')
neg_inf = float('-inf')
nan = float('nan')
print(f"\nInfinity: {inf}")
print(f"Negative Infinity: {neg_inf}")
print(f"NaN: {nan}")
print(f"Is NaN: {nan != nan}") # NaN != NaN is True!42 → 42.0 '299.99' → 299.99 Type: <class 'float'> '1.5e10' → 15000000000.0 True → 1.0 False → 0.0 Infinity: inf Negative Infinity: -inf NaN: nan Is NaN: True
5. Explicit Type Conversion — str()
Hindi: str() kisi bhi Python object ko string mein convert kar deta hai. Yeh sabse safe conversion hai — koi bhi cheez string ban sakti hai!25 years old
Pi is: 3.14159
int → str: '42'
float → str: '3.14'
bool → str: 'True'
NoneType → str: 'None'
list → str: '[1, 2]'
dict → str: "{'a': 1}"String Formatting Alternatives
name = "Rahul"
age = 25
score = 95.5
# Method 1: str() + concatenation
print("Name: " + str(age))
# Method 2: f-string (recommended — Python 3.6+)
print(f"Name: {name}, Age: {age}, Score: {score:.1f}")
# Method 3: .format()
print("Name: {}, Age: {}, Score: {:.1f}".format(name, age, score))
# Method 4: % formatting (old style)
print("Name: %s, Age: %d, Score: %.1f" % (name, age, score))Name: 25 Name: Rahul, Age: 25, Score: 95.5 Name: Rahul, Age: 25, Score: 95.5 Name: Rahul, Age: 25, Score: 95.5
6. Explicit Type Conversion — bool()
Value bool()
------------------------------
0 False
1 True
-1 True
100 True
0.0 False
0.1 True
-3.14 True
'' False
'hello' True
' ' True
[] False
[0] True
[False] True
{} False
{'a': 1} True
() False
(0,) True
set() False
{0} True
None False7. Collection Type Conversions
list(), tuple(), set()
str → list: ['P', 'y', 't', 'h', 'o', 'n']
str → tuple: ('P', 'y', 't', 'h', 'o', 'n')
str → set: {'P', 'y', 't', 'h', 'o', 'n'}
Original list: [1, 2, 2, 3, 3, 3, 4]
To tuple: (1, 2, 2, 3, 3, 3, 4)
To set: {1, 2, 3, 4}
To list via set: [1, 2, 3, 4]
range(1, 11) → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]dict() Conversion
List of tuples → dict: {'name': 'Rahul', 'age': 25, 'city': 'Delhi'}
Zipped lists → dict: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Keyword args → dict: {'host': 'localhost', 'port': 5432, 'db': 'mydb'}8. Number System Conversions
Decimal: 255 Binary: 0b11111111 Octal: 0o377 Hex: 0xff Binary (no prefix): 11111111 Octal (no prefix): 377 Hex (no prefix): ff Hex uppercase: FF '11111111' (binary) → 255 'ff' (hex) → 255 '377' (octal) → 255
9. Character Conversions — ord() and chr()
# ord() — character to ASCII/Unicode code
print(f"'A' = {ord('A')}") # 65
print(f"'a' = {ord('a')}") # 97
print(f"'0' = {ord('0')}") # 48
print(f"'Z' = {ord('Z')}") # 90
# chr() — code to character
print(f"\nchr(65) = '{chr(65)}'") # 'A'
print(f"chr(97) = '{chr(97)}'") # 'a'
# Practical use: shift cipher (Caesar cipher)
def caesar_encrypt(text, shift):
result = ""
for char in text:
if char.isalpha():
base = ord('A') if char.isupper() else ord('a')
result += chr((ord(char) - base + shift) % 26 + base)
else:
result += char
return result
message = "Hello, World!"
encrypted = caesar_encrypt(message, 3)
decrypted = caesar_encrypt(encrypted, -3)
print(f"\nOriginal: {message}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")'A' = 65 'a' = 97 '0' = 48 'Z' = 90 chr(65) = 'A' chr(97) = 'a' Original: Hello, World! Encrypted: Khoor, Zruog! Decrypted: Hello, World!
10. Type Casting Flowchart
| ├── Integer | int(value) |
| │ ├── From string | int("42") ✅ |
| │ ├── From float: int(3.9) | 3 ✅ (truncates) |
| │ ├── From bool: int(True) | 1 ✅ |
| │ └── From float str | int(float("3.9")) ✅ |
| ├── Float | float(value) |
| │ ├── From int: float(42) | 42.0 ✅ |
| │ ├── From string | float("3.14") ✅ |
| │ └── From bool: float(True) | 1.0 ✅ |
| ├── String | str(value) |
| │ └── Anything | str(anything) ✅ (always works) |
| ├── Boolean | bool(value) |
| │ └── 0, "", [], {}, None | False |
| │ Everything else | True |
| ├── list(iterable) | list |
| ├── tuple(iterable) | tuple |
| ├── set(iterable) | set (removes duplicates) |
| └── dict(key_value_pairs) | dict |
11. Safe Type Conversion with Error Handling
safe_int('42' ) = 42
safe_int('3.14' ) = -1
safe_int('hello' ) = -1
safe_int(None ) = -1
safe_int([] ) = -1
safe_int(' 25 ' ) = -1
safe_int('0xFF' ) = -1
safe_float('42' ) = 42.0
safe_float('3.14' ) = 3.14
safe_float('hello' ) = -1.0
safe_float(None ) = -1.0
safe_float([] ) = -1.0
safe_float(' 25 ' ) = -1.0
safe_float('0xFF' ) = -1.012. Real-World Example: Form Data Processing
PROCESSED EMPLOYEE DATA ======================================== name : 'Rahul Sharma' (str) age : 28 (int) salary : 75000.5 (float) experience_years : 5 (int) is_manager : True (bool) skills : ['Python', 'Django', 'React'] (list) rating : 4.7 (float)
Practice Exercises
Exercise 1 — Basic Conversions
Convert and print the type after conversion:
a = "100" # → int
b = 3.7 # → int (notice what happens to decimal)
c = 42 # → float, then → str
d = "False" # → bool (careful — what does bool("False") return?)
e = range(1, 6) # → listExercise 2 — User Input Processing
# Simulate getting user input (input() always returns string!)
user_age = input("Enter your age: ") # "22"
user_height = input("Enter height in cm: ") # "175"
# Convert and calculate BMI category
# height in m = height_cm / 100
# BMI = weight / height² — assume weight = 70kgExercise 3 — Number System Challenge
Convert the number 2024 to:
- Binary, Octal, Hexadecimal
- Convert each back to decimal to verify
- Find the character for ASCII code 2024 % 128
Interview Questions
Q1. What is the difference between implicit and explicit type conversion? > Implicit: Python automatically converts types (e.g., int + float → float) to prevent data loss. Explicit: Programmer manually converts using functions like int(), float(), str(). Python never implicitly converts between numbers and strings.
Q2. What does int(3.9) return — 3 or 4? > It returns 3. int() truncates (cuts) the decimal part, it does NOT round. For rounding, use round(3.9) → 4. For floor, use math.floor(3.9) → 3. For ceiling, use math.ceil(3.9) → 4.
Q3. What happens when you do bool("False")? > It returns True! Any non-empty string is truthy, including "False", "0", "None". Only the empty string "" is falsy. To convert the string "false" to boolean False, compare: "false".lower() == "true".
Q4. How would you safely convert user input (always a string) to integer? > Use try-except: try: value = int(input("Enter number: ")); except ValueError: print("Invalid!"). Or use a validation loop. Never call int() on raw user input without error handling.
Q5. What is the difference between str(), repr(), and format()? > str() gives a human-readable string, repr() gives an unambiguous programmer's representation (e.g., includes quotes for strings). format() gives a formatted string with format specifiers. str(3.14) → '3.14', repr("hello") → "'hello'", format(3.14159, '.2f') → '3.14'.
⚠️ Common Mistakes
❌ Mistake 1: int("3.14") directly convert karna
Problem: Float wali string ko directlyint()mein pass karnaValueErrordeta hai. Fix: Pehlefloat()mein convert karo, phirint()use karo →int(float("3.14"))✅
❌ Mistake 2: bool("False") ko False samajhna
Problem:bool("False")returnsTruekyunki non-empty string hamesha truthy hoti hai! 😱 Fix: String comparison use karo →value.lower() == "true"✅
❌ Mistake 3: int() ko rounding samajhna
Problem:int(3.9)returns3, NOT4. Yeh truncate karta hai, round nahi! Fix: Rounding ke liyeround(3.9)use karo →4✅ yamath.ceil()/math.floor()use karo.
❌ Mistake 4: User input ko bina error handling ke convert karna
Problem:age = int(input("Age: "))— agar user "twenty" type kare toh program crash ho jayega! 💥 Fix: Hameshatry-exceptuse karo: ``python try: age = int(input("Age: ")) except ValueError: print("Please enter a valid number!")``
❌ Mistake 5: str() aur concatenation mein confusion
Problem:"Age: " + 25→TypeError! Python automatically int ko string mein convert nahi karta concatenation mein. Fix:"Age: " + str(25)ya better — f-string use karo:f"Age: {25}"✅
❌ Mistake 6: set() mein order expect karna
Problem:set([3, 1, 2])ka output{1, 2, 3}ya kuch bhi ho sakta hai — sets unordered hote hain! Fix: Agar order chahiye tohsorted(set(my_list))use karo ✅
❌ Mistake 7: float precision loss ignore karna
Problem:float("0.1") + float("0.2")=0.30000000000000004😵 — yeh binary floating point ki limitation hai. Fix: Precise calculations ke liyedecimalmodule use karo: ``python from decimal import Decimal Decimal("0.1") + Decimal("0.2") # → Decimal('0.3') ✅``
✅ Key Takeaways
- 🔄 Type casting = ek data type ko doosre mein convert karna. Python mein do tarike hain: Implicit (automatic) aur Explicit (manual using functions).
- 📈 Implicit conversion hamesha "smaller to larger" type mein hoti hai —
bool → int → float → complex— taaki data loss na ho.
- 🔢
int()truncate karta hai (decimal cut), round NAHI karta.int(9.99)=9, not10.
- 📝
str()sabse safe hai — kisi bhi Python object ko string mein convert kar sakta hai bina error ke.
- ⚡
bool()mein falsy values yaad rakho:0,0.0,"",[],{},(),set(),None→ sabFalsedete hain. Baaki sabTrue!
- 🎯
int()with base — binary, octal, hex strings ko decimal mein convert karne ke liyeint("FF", 16),int("1010", 2)use karo.
- 🛡️ Error handling is essential — user input ya external data convert karte waqt hamesha
try-exceptuse karo. Kabhi bhi raw conversion pe trust mat karo.
- 🔗
ord()andchr()— character ↔ ASCII/Unicode code conversion ke liye.ord('A')= 65,chr(65)= 'A'.
- 📦 Collection conversions —
list(),tuple(),set()kisi bhi iterable pe kaam karte hain.set()duplicates remove karta hai!
- 💡 Pro tip: f-strings (
f"value: {x}") use karo instead ofstr()+ concatenation — cleaner, faster, aur readable hai!
❓ FAQ
Q1. type() aur isinstance() mein kya difference hai? > type(x) exact type batata hai, jabki isinstance(x, int) inheritance bhi check karta hai. Example: type(True) is <class 'bool'> but isinstance(True, int) is True kyunki bool is a subclass of int. Production code mein isinstance() prefer karo! ✅
Q2. Kya hum list ko directly string mein convert kar sakte hain aur wapas list mein la sakte hain? > str([1, 2, 3]) → "[1, 2, 3]" — yeh string ban jayegi. Wapas list mein laane ke liye ast.literal_eval("[1, 2, 3]") use karo, NOT eval() (security risk! 🚨). JSON data ke liye json.loads() aur json.dumps() best hai.
Q3. int(" 42 ") kaam karega ya error dega? > ✅ Kaam karega! int() leading/trailing whitespace automatically handle kar leta hai. Lekin int("4 2") ya int("42abc") mein error aayega kyunki beech mein ya end mein non-numeric characters hain.
Q4. Implicit conversion mein Python str + int ko automatically convert kyun nahi karta? > Kyunki yeh ambiguous hai — "5" + 3 ka matlab "53" (concatenation) ho sakta hai ya 8 (addition). Python "Explicit is better than implicit" philosophy follow karta hai (Zen of Python), isliye aapko khud decide karna hota hai: int("5") + 3 ya "5" + str(3).
Q5. float('inf') aur float('nan') ka real-world use kya hai? > float('inf') — comparison mein use hota hai jab aapko maximum value chahiye (e.g., finding minimum: min_val = float('inf')). float('nan') — missing/invalid data represent karta hai, especially Pandas/NumPy mein. 📊 Special property: nan != nan is True!
Q6. int() vs math.floor() vs math.trunc() — negative numbers pe kya difference hai? > Positive numbers pe same result, but negative pe different! int(-3.7) = -3 (toward zero), math.floor(-3.7) = -4 (toward negative infinity), math.trunc(-3.7) = -3 (same as int). Positive mein: int(3.7) = math.floor(3.7) = math.trunc(3.7) = 3. 🤔
Q7. Kya None ko kisi type mein convert kar sakte hain? > str(None) → "None" ✅, bool(None) → False ✅, but int(None) → TypeError ❌, float(None) → TypeError ❌. None ko numeric types mein directly convert nahi kar sakte — pehle check karo: value if value is not None else 0.
Q8. Multiple types ek saath check karne ka best way kya hai? > isinstance() mein tuple pass karo: isinstance(x, (int, float)) — yeh check karega ki x int hai ya float. Yeh type(x) == int or type(x) == float se zyada Pythonic aur inheritance-friendly hai! 🐍
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Python Type Casting.
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, type, casting
Related Python Master Course Topics