Type Casting & Truthiness
Type Casting is the process of converting an object from one data type to another. Because Python is Strongly Typed, it will not perform risky conversions automatically (like adding a string "5" to a number 5). You must be explicit about your intent.
1. Implicit vs. Explicit Conversion
Section titled “1. Implicit vs. Explicit Conversion”Implicit (Automatic)
Section titled “Implicit (Automatic)”Python only performs implicit conversion when it is “safe”—meaning no data will be lost. This usually happens when mixing integers and floats.
x = 10 # inty = 2.5 # floatz = x + y # 12.5 (Python promotes x to float automatically)Explicit (Manual)
Section titled “Explicit (Manual)”You use the constructor functions of the class you want to convert to.
int(x): Converts to integer (truncates floats).float(x): Converts to floating point.str(x): Converts to string.bool(x): Converts to boolean.
2. Truthy and Falsy Values
Section titled “2. Truthy and Falsy Values”This is one of the most important concepts in Python logic. Every object in Python has an inherent boolean value. You don’t need a comparison to use an object in an if statement.
The Falsy List
Section titled “The Falsy List”Only these values evaluate to False:
- Constants:
NoneandFalse. - Zeroes:
0,0.0,0j. - Empty Collections:
""(empty string),[](empty list),{}(empty dict),set().
Everything else is Truthy.
def check(val): if val: print(f"{repr(val)} is Truthy") else: print(f"{repr(val)} is Falsy")
check(0) # Falsycheck(0.1) # Truthycheck([]) # Falsycheck(" ") # Truthy (It contains a space!)3. Under the Hood: The __bool__ Method
Section titled “3. Under the Hood: The __bool__ Method”How does Python know if an object is True or False?
When you call bool(obj) or use an object in an if statement, Python follows this priority:
- It looks for a method named
__bool__()on the object’s class and uses its return value. - If
__bool__isn’t defined, it looks for__len__(). If the length is0, it’s False; otherwise, it’s True. - If neither exists, the object is always True.
4. Common Casting Scenarios
Section titled “4. Common Casting Scenarios”1. Handling User Input
Section titled “1. Handling User Input”The input() function always returns a str. To do math, you must cast it.
age = int(input("Enter age: "))2. Truncation vs. Rounding
Section titled “2. Truncation vs. Rounding”Casting a float to an int does not round. it simply chops off the decimal (truncation).
print(int(9.99)) # Output: 9To round properly, use the built-in round() function instead.
3. String Concatenation
Section titled “3. String Concatenation”You cannot add an int to a str. You must cast the number to a string first.
score = 100# print("Score: " + score) # TypeErrorprint("Score: " + str(score)) # Correct5. Summary Table
Section titled “5. Summary Table”| From | To | Method | Result |
|---|---|---|---|
float | int | int(3.8) | 3 (Truncated) |
int | float | float(5) | 5.0 |
str | int | int("10") | 10 |
any | str | str(True) | "True" |
list | bool | bool([]) | False |