Home Tutorials Python Tutorial Type Casting
Type Casting

Type Casting


Definition: Type casting is the process of converting the value of one data type (such as a string, integer, or float) into another data type.

Why: Casting is essential for basic data handling, especially when you receive data in one format (like text from a user) but need to use it in another (like a number for calculations).

Syntax

  • int(value) - Converts to an integer.
  • float(value) - Converts to a floating-point number.
  • str(value) - Converts to a string.

Example

age = "25"
new_age = int(age)

print(new_age)
print(type(new_age))

Explanation

  • The variable age is initially a string because it is enclosed in quotes.
  • The int(age) function converts that string into the integer 25.
  • The type() function confirms that new_age is now an integer (<class 'int'>).

Key Notes

  • You can only cast a string to an integer if the string contains a valid number (e.g., int("10") works, but int("apple") will cause an error).
  • Converting a float to an integer will "truncate" the number, meaning it removes the decimal part without rounding (e.g., int(3.9) becomes 3).
Example

🏋️ Test Yourself With Exercises

Take our quiz on Type Casting to test your knowledge.

Exercise »