Python Type Casting
Type Casting
Type casting (also called type conversion) means converting a value from one data type to another — for example, turning the string "42" into the integer 42, or the number 100 into the string "100".
Python assigns data types automatically, but there are many situations where you need to change a value's type yourself:
- User input:
input()always returns a string, even when the user types a number. - External data: values read from files, web forms, CSV files, and APIs often arrive as text.
- Output formatting: numbers sometimes need to be converted to text before being combined with other strings.
How Casting Works in Python
In Python, every data type is implemented as a class. Each class has a constructor function with the same name — int(), float(), str(), and so on. Calling the constructor with a value creates a new value of that type.
number = int("42")
The original value is not modified; a new value of the target type is created and returned.
Implicit vs Explicit Conversion
There are two kinds of type conversion in Python.
Implicit Conversion
Python sometimes converts types automatically when it is safe to do so — for example, when you mix an integer and a float in a calculation:
result = 5 + 2.5
print(result)
print(type(result))
Expected output:
7.5
<class 'float'>
Python converted 5 to 5.0 behind the scenes so that no information was lost.
Explicit Conversion (Type Casting)
When Python cannot safely guess what you want, you must convert the value yourself using a casting function. This is type casting:
age = int("25")
Python never automatically converts between strings and numbers. "5" + 5 raises a TypeError, because it is unclear whether you mean "55" or 10.
Common Casting Functions
| Function | Converts To | Accepts |
|---|---|---|
int() | Integer | Integers, floats (removes the decimal part), strings containing a whole number |
float() | Floating-point number | Integers, floats, strings containing an integer or decimal number |
str() | String | Almost any value: numbers, booleans, lists, and more |
bool() | Boolean | Any value (see below) |
Casting to Integers With int()
int() converts a value into an integer.
- It removes the decimal part from floats (it truncates; it does not round).
- It converts strings that contain a whole number into integers.
Example
a = int(9)
b = int(6.7)
c = int("42")
print(a)
print(b)
print(c)
Expected output:
9
6
42
Explanation:
int(9)— the value is already an integer, so it stays9.int(6.7)— the decimal part.7is removed, giving6.int("42")— the string"42"is converted to the integer42.
Truncation Moves Toward Zero
Because int() simply removes the decimal part, negative numbers move toward zero:
print(int(6.7))
print(int(-6.7))
Expected output:
6
-6
If you want the nearest whole number instead, use round():
print(round(6.7))
Expected output:
7
Strings Must Contain a Whole Number
int() cannot convert a string that contains a decimal point or non-numeric characters:
int("6.7")
Output:
ValueError: invalid literal for int() with base 10: '6.7'
To convert "6.7" to an integer, convert it to a float first:
value = int(float("6.7"))
print(value)
Expected output:
6
Note:
int()ignores spaces at the beginning and end of a string, soint(" 42 ")returns42.
Casting to Floats With float()
float() converts a value into a floating-point number. The result always has a decimal part, even if the value is a whole number.
Example
x = float(5)
y = float("12")
z = float("7.89")
print(x)
print(y)
print(z)
Expected output:
5.0
12.0
7.89
Explanation:
float(5)converts the integer5into5.0.float("12")converts a whole-number string into12.0.float("7.89")converts a decimal string into7.89.
float() works with integers, floats, and numeric strings — including strings in scientific notation, such as float("1e3"), which returns 1000.0.
Casting to Strings With str()
str() converts a value into its text representation. This is useful for displaying values and for joining them with other strings.
Example
p = str("Python")
q = str(100)
r = str(4.56)
print(p)
print(q)
print(r)
Expected output:
Python
100
4.56
Although the printed output looks the same as the original numbers, q and r are now strings. You can confirm this with type():
print(type(q))
Expected output:
<class 'str'>
Practical Use: Joining Numbers With Text
items = 3
message = "You have " + str(items) + " items in your cart"
print(message)
Expected output:
You have 3 items in your cart
Without str(items), Python would raise a TypeError, because + cannot join a string and an integer.
Casting to Booleans With bool()
bool() converts any value to True or False. The rule is simple: empty or zero values are False; everything else is True.
print(bool(0))
print(bool(15))
print(bool(""))
print(bool("Hello"))
print(bool("False"))
Expected output:
False
True
False
True
True
Notice the last line: bool("False") is True, because "False" is a non-empty string. bool() does not read the meaning of the text.
Practical Example: Processing User Input
This is the most common real-world use of casting. input() returns a string, so you must convert it before doing arithmetic.
quantity = input("Enter quantity: ") # Suppose the user types 4
price = input("Enter price: ") # Suppose the user types 250.50
total = int(quantity) * float(price)
print("Total cost:", total)
Example run:
Enter quantity: 4
Enter price: 250.50
Total cost: 1002.0
What happens:
input()returns the strings"4"and"250.50".int(quantity)converts"4"to the integer4.float(price)converts"250.50"to the float250.5.- The numbers are multiplied, giving
1002.0.
Handling Invalid Input Safely
If the user types something that is not a number, the conversion raises a ValueError. You can handle this with try and except, which you will study in the Exception Handling lesson:
text = "abc"
try:
number = int(text)
print("You entered", number)
except ValueError:
print("Please enter a valid whole number")
Expected output:
Please enter a valid whole number
Important Notes on Casting
- Only valid numeric strings can be converted to numbers.
int("abc")andfloat("12a")raise aValueError. - Converting a float to an integer removes the decimal part; it does not round.
- Casting creates a new value; the original variable is unchanged unless you reassign it.
- Casting is commonly used when processing user input from forms, command-line programs, and files.
Common Mistakes
| Mistake | Example | Result |
|---|---|---|
| Doing math on input without converting | input() + 1 | TypeError |
Converting a decimal string with int() | int("3.5") | ValueError |
Expecting int() to round | int(9.99) | 9 |
Expecting bool("False") to be False | bool("False") | True |
| Forgetting to store the converted value | int(age) on its own line | age is still a string |
Related Concepts
- Python Data Types — the types you can convert between
- Python Numeric Data Types —
int,float, andcomplex - Python User Input — the most common source of values that need casting
- Python Exception Handling — handling failed conversions gracefully