Python Type Casting
Type casting in Python refers to converting a value from one data type to another. Although Python automatically assigns data types, there are situations—such as handling user input or external data—where you may want to explicitly define or change a variable’s type.
Python performs casting using built-in constructor functions, since data types in Python are implemented as classes.
Common Casting Functions in Python
int() – Converts a value into an integer
- Removes the decimal part from floats
- Converts numeric strings into integers
float() – Converts a value into a floating-point number
- Works with integers, floats, and numeric strings
str() – Converts a value into a string
- Works with numbers, booleans, and other data types
Casting to Integers
When converting values to integers, Python truncates any decimal portion.
Example:
Output:
>
Casting to Floats
Float casting converts numbers into decimal form, even if the value is a whole number.
Example:
Output:
Casting to Strings
The str() function converts any value into text format, making it useful for displaying output.
Example:
Output:
Important Notes on Casting
- Only valid numeric strings can be converted to numbers
- Converting a float to an integer removes the decimal part (no rounding)
- Casting is commonly used when processing user input from forms or command-line input