Type Conversion in Python: How to Convert Values Correctly? ????
Python is a dynamically typed language, meaning you don’t need to explicitly declare variable types—Python automatically assigns them. However, there are times when you need to convert a value from one data type to another, such as converting a number to text or a string to a number.
In this article, we’ll explore how to convert between basic data types (int, float, str, bool), common pitfalls, and how to avoid errors.
Implicit vs. Explicit Conversion
? Implicit Conversion (Automatic)
Python sometimes automatically converts data types when needed, such as in mathematical operations between int and float.
x = 5 # int
y = 2.5 # float
result = x + y # Python automatically converts `x` to float
print(result)
print(type(result)) # Output: <class 'float'>
??? Output:
7.5
<class 'float'>
?? Python automatically converts int to float when necessary.
? Explicit Conversion (Manual Casting)
Sometimes, you need to manually convert a value—such as when processing user input or working with databases.
Python provides built-in functions for type conversion:
2?? Converting to an Integer (int())
You can convert float or str to int if they contain numeric values:
x = 3.9
y = "10"
print(int(x)) # Output: 3 (rounded down)
print(int(y)) # Output: 10 (string converted to an integer)
Warning! Converting non-numeric text to an integer will cause an error:
print(int("Hello")) # ? Error: ValueError
3?? Converting to a Float (float())
Used when you need to work with decimal numbers:
a = "3.14"
b = 5
print(float(a)) # Output: 3.14 (string converted to float)
print(float(b)) # Output: 5.0 (int converted to float)
?? An error occurs if you try to convert non-numeric text:
print(float("Python")) # ? Error: ValueError
4?? Converting to a String (str())
Used when converting numbers or boolean values to text:
x = 42
y = 3.14
z = True
print(str(x)) # Output: "42"
print(str(y)) # Output: "3.14"
print(str(z)) # Output: "True"
This is useful when concatenating text and numbers:
领英推è
age = 25
print("My age is " + str(age)) # Output: My age is 25
?? Without str() conversion, you get an error:
print("My age is " + age) # ? Error: TypeError
5?? Converting to Boolean (bool())
Boolean values (True/False) are essential in conditions. Python automatically considers some values as False:
?? False, 0, "" (empty string), None, [], {} (empty data structures)
?? All other values are True.
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("Hello")) # True
print(bool([])) # False
print(bool([1,2])) # True
?? Useful in conditions:
name = ""
if name:
print("Hello, " + name)
else:
print("No name provided.") # Output: No name provided.
6?? Common Errors in Type Conversion
?? Trying to Convert a Non-Numeric String to an Integer
print(int("Hello")) # ? Error: ValueError
? Solution: Ensure the string contains only digits.
?? Concatenating a Number with a String Without Conversion
age = 30
print("My age is " + age) # ? Error: TypeError
? Solution:
print("My age is " + str(age))
?? Converting float to int – Rounds Down
print(int(3.99)) # Output: 3
? Solution: Use round() for proper rounding:
print(round(3.99)) # Output: 4
7?? Summary
? Python performs automatic conversion (int -> float in operations)
? Manual conversions use int(), float(), str(), bool()
? Be careful when converting non-numeric text to numbers (ValueError)
? float -> int removes the decimal part (rounds down)
? Boolean values: 0, "", None, [] are False, everything else is True