HOME HTML EDITOR C JAVA PHP python

Python Type Casting

Type casting (or type conversion) in Python means converting a value from one data type into another using built-in constructor functions such as int(), float(), and str(). This is common when working with user input, files, or APIs where values arrive as strings.

Casting with int()

int() constructs an integer from an integer literal, a float literal (by truncating toward zero, not rounding), or a string containing a whole number:

x = int(5)        # 5
y = int(9.85)     # 9 (fractional part removed)
z = int("42")     # 42

print(x, y, z)

Casting with float()

float() converts an integer, float, or numeric string into a floating-point number:

a = float(12)     # 12.0
b = float(3.5)    # 3.5
c = float("19.5") # 19.5

print(a, b, c)

Casting with str()

str() converts numbers and other values into strings so they can be safely joined with text:

age = 20
score = 88.5

message = "Age: " + str(age) + ", Score: " + str(score)
print(message)

Important Casting Notes

  • Invalid String Conversions: Calling int("abc") or int("3.14") raises a ValueError; convert decimal strings with float() first if needed.
  • Truncation vs. Rounding: int(-3.9) gives -3, not -4—it drops the decimal part.
Tip: Values returned by Python's input() function are always str—cast them with int() or float() before doing math.