Python Casting
Casting means converting a value from one type to another using Python's built-in constructor functions.
Why cast?
Sometimes a value has the wrong type for what you want to do with it. Text typed by a user arrives as a string even when it looks like a number, and you cannot do arithmetic on it until you convert it. Casting solves this by building a new value of the target type from the value you already have.
Converting to numbers
The int() function turns a suitable string or a float into an integer, and float() turns a suitable string or an int into a float. When int() receives a float it truncates toward zero, discarding the fractional part rather than rounding it.
Numeric casting
int("10") # 10
int(9.8) # 9, the .8 is dropped
float("3.5") # 3.5
float(7) # 7.0
print(int("10") + float(7)) # 17.0Converting to text
The str() function turns any value into its string form, which is essential when you want to join a number to a message. Trying to add a number directly to a string raises a TypeError, so cast the number first.
Casting for output
score = 95
message = "Your score is " + str(score)
print(message) # Your score is 95Converting to boolean
- bool() returns False for empty or zero-like values: 0, 0.0, "", [], {}, and None.
- bool() returns True for every other value, including any non-empty string or list.
- Casting can fail, so guard user input with try/except or validate it first.
- Casting always builds a new value; the original variable keeps its own type.
Boolean casting
print(bool(0)) # False
print(bool("")) # False
print(bool("no")) # True, any non-empty string is truthy
print(bool([1, 2])) # TrueExercise: Python Casting
What does int("42") return?