Type Casting and Conversion
Type Casting and Conversion
Section titled “Type Casting and Conversion”Introduction
Section titled “Introduction”Type conversion is the process of converting a value from one data type to another. Python supports both implicit (automatic) and explicit (manual) conversion.
Implicit Conversion
Section titled “Implicit Conversion”Python automatically converts types when it makes sense:
x = 5 # inty = 2.0 # floatresult = x + y # Python converts x to floatprint(result) # 7.0 (float)
# bool + intprint(True + 5) # 6 (True is treated as 1)Explicit Conversion
Section titled “Explicit Conversion”To Integer int()
Section titled “To Integer int()”int("42") # 42int(3.9) # 3 (truncates!)int(True) # 1int("0xFF", 16) # 255 (hex to int)To Float float()
Section titled “To Float float()”float("3.14") # 3.14float(42) # 42.0float("inf") # infTo String str()
Section titled “To String str()”str(42) # '42'str(3.14) # '3.14'str([1,2,3]) # '[1, 2, 3]'To Boolean bool()
Section titled “To Boolean bool()”bool(0) # Falsebool(1) # Truebool("") # False (empty string)bool("hello") # Truebool([]) # False (empty list)bool(None) # FalseTo List/Tuple/Set
Section titled “To List/Tuple/Set”list("hello") # ['h', 'e', 'l', 'l', 'o']tuple([1,2,3]) # (1, 2, 3)set([1,1,2,3,3]) # {1, 2, 3} — removes duplicatesCommon Errors
Section titled “Common Errors”int("hello") # ValueError: invalid literalint("3.14") # ValueError: can't convert float string directly# Fix:int(float("3.14")) # First convert to float, then int → 3Why It Matters
Section titled “Why It Matters”Type casting is essential when handling user input (input() returns str), processing data from files/APIs, and ensuring correct arithmetic.
Interview Questions
Section titled “Interview Questions”Q1: What is the difference between implicit and explicit type conversion?
A: Implicit conversion is automatic (e.g., int + float → float). Explicit requires a casting function like int(), float(), str().
Q2: What values are considered falsy in Python?
A: False, None, 0, 0.0, "", [], (), {}, set() — all evaluate to False in boolean context.
Practice Exercises
Section titled “Practice Exercises”- Convert a float string “3.14” to an integer.
- Check all falsy values using
bool(). - Parse user input and perform arithmetic with type conversion.