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.

FunctionConverts toExample
int(x)An integerint("25") gives 25
float(x)A floating point numberfloat("3.5") gives 3.5
str(x)A stringstr(99) gives "99"
bool(x)A booleanbool(0) gives False

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.0
Note: int() only accepts strings that look like whole numbers. int("3.5") raises a ValueError, so convert to float first and then to int if you need to drop the decimals: int(float("3.5")).

Converting 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 95

Converting 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]))   # True

Exercise: Python Casting

What does int("42") return?