Python is a programming language with simple syntax and powerful features, widely used by everyone from beginners to advanced users. Among its features, “casting (type conversion)” is one of the essential techniques for handling data correctly. In this article, we’ll explain Python’s casting (type conversion) in detail, using code examples to make it easy for beginners to understand. By reading this article, you’ll learn the following:
Basic concepts of casting (type conversion) in Python
Differences between explicit and implicit type conversion
Specific methods and considerations for type conversion
Common errors and how to avoid them
Understanding casting makes data handling more flexible and helps prevent bugs. In particular, when working with different data types, performing the appropriate type conversion is crucial.
2. What Is Casting (Type Conversion)? 【Python Basics】
2.1 Definition of Casting (Type Conversion)
Casting (type conversion) refers to converting a data type to another data type. For example, you can convert an integer to a string or a string to a numeric value. Casting is needed in cases such as:
When you want to convert user input (usually a string) to a number for calculations
When you want to convert a list of numbers to a string to format it
To handle different data types properly in Python’s internal processing
In Python, you can easily perform type conversion using built‑in functions.
2.2 Explicit Type Conversion (Explicit Type Conversion)
Explicit type conversion means that the developer intentionally converts one data type to another. In Python, you perform explicit type conversion with functions such as the following.
Conversion Function
Description
Example
int()
Convert strings or floating‑point numbers to integers
int("10") → 10
float()
Convert strings or integers to floating‑point numbers
float("3.14") → 3.14
str()
Convert numbers, lists, etc. to strings
str(100) → "100"
list()
Convert tuples or strings to lists
list("abc") → ['a', 'b', 'c']
tuple()
Convert lists to tuples
tuple([1, 2, 3]) → (1, 2, 3)
dict()
Convert key‑value pairs to dictionaries
dict([(1, 'a'), (2, 'b')]) → {1: 'a', 2: 'b'}
Example: Explicit Type Conversion
# Convert integer to string
num = 10
str_num = str(num)
print(str_num) # "10"
print(type(str_num)) # <class 'str'>
# Convert string to floating‑point number
float_num = float("3.14")
print(float_num) # 3.14
print(type(float_num)) # <class 'float'>
2.3 Implicit Type Conversion (Implicit Type Conversion)
Implicit type conversion means that Python automatically converts data types. Even without explicit instructions from the developer, Python adjusts types internally as needed.
Example: Implicit Type Conversion
num_int = 10 # integer type
num_float = 2.5 # floating‑point number
# integer + float → converted to float
result = num_int + num_float
print(result) # 12.5
print(type(result)) # <class 'float'>
In this way, Python automatically adjusts data types so that operations produce correct results.
2.4 Benefits and Cautions of Using Casting
✅ Benefits of Casting
You can properly handle user input and other data
Calculations and operations across different data types become possible
Explicit casting makes program behavior easier to predict
⚠️ Cautions When Casting
Improper type conversion can cause errors Example: int("abc") cannot be converted and raises a ValueError
Relying too much on implicit conversion can lead to bugs Example: Concatenating an integer and a string directly raises a TypeError
Type conversion has a performance cost Converting large amounts of data can affect performance
In Python, you can convert various data types using built-in functions such as int(), float(), str(), etc.
Conversion Function
Description
Example
int(x)
Convert to integer
int("100") → 100
float(x)
Convert to floating-point number
float("3.14") → 3.14
str(x)
Convert to string
str(42) → "42"
list(x)
Convert to list
list((1, 2, 3)) → [1, 2, 3]
tuple(x)
Convert to tuple
tuple([1, 2, 3]) → (1, 2, 3)
set(x)
Convert to set
set([1, 2, 2, 3]) → {1, 2, 3}
dict(x)
Convert to dictionary
dict([(1, 'a'), (2, 'b')]) → {1: 'a', 2: 'b'}
4. How to Perform Explicit Type Conversion (Casting) with Code Examples
In Python, you can perform an Explicit Type Conversion to deliberately change a data type.
This is a method where developers manually convert data types using built-in functions like int() or str().
4.1 Converting to Integer (int)
# Convert string to integer
num1 = int("10")
print(num1, type(num1)) # 10 <class 'int'>
# Convert floating-point number to integer (truncating the decimal part)
num2 = int(3.99)
print(num2) # 3
# Convert boolean to integer
num3 = int(True)
num4 = int(False)
print(num3, num4) # 1 0
4.2 Converting to Floating-Point Number (float)
# Convert string to floating-point number
num1 = float("10.5")
print(num1, type(num1)) # 10.5 <class 'float'>
# Convert integer to floating-point number
num2 = float(10)
print(num2) # 10.0
# Convert list to set (remove duplicates)
list_data = [1, 2, 2, 3, 3, 3]
set_data = set(list_data)
print(set_data, type(set_data)) # {1, 2, 3} <class 'set'>
4.7 Converting to Dictionary (dict)
# Convert list of lists to dictionary
list_of_pairs = [[1, 'apple'], [2, 'banana']]
dict_data = dict(list_of_pairs)
print(dict_data) # {1: 'apple', 2: 'banana'}
4.8 Summary
Explicit type conversion in Python is important for making programs more flexible.
By using int(), float(), str(), etc., appropriately, converting between different data types becomes easy.
Conversion Function
Description
int(x)
Convert to integer
float(x)
Convert to floating-point number
str(x)
Convert to string
list(x)
Convert to list
tuple(x)
Convert to tuple
set(x)
Convert to set
dict(x)
Convert to dictionary
5. Implicit Type Conversion (Python’s Automatic Conversion)
5.1 What is the type conversion that Python performs automatically?
Implicit type conversion is a mechanism where Python automatically converts to the appropriate data type without the developer explicitly specifying it. Python’s implicit type conversion mainly occurs during operations on numeric types (int, float, complex).
Example: Operations between integers (int) and floating-point numbers (float)
num_int = 10 # integer
num_float = 2.5 # floating-point number
result = num_int + num_float # Python implicitly converts int to float
print(result, type(result)) # 12.5 <class 'float'>
5.2 In what situations does implicit conversion occur?
Case 1: Integer (int) → Floating-point (float)
a = 5
b = 2.0
result = a / b # Python converts int to float
print(result, type(result)) # 2.5 <class 'float'>
Case 2: Integer (int) → Complex (complex)
a = 10 # int
b = 2 + 3j # complex (imaginary)
result = a + b
print(result, type(result)) # (12+3j) <class 'complex'>
Case 3: Boolean (bool) → Numeric (int, float)
print(True + 2) # 3 (True is treated as 1)
print(False + 3.5) # 3.5 (False is treated as 0)
5.3 Precautions and Workarounds for Implicit Type Conversion
⚠️ Caution 1: Mixing strings (str) with numbers (int, float)
num = 10
text = "yen"
# This will cause an error
# print(num + text) # TypeError
# Correct approach
print(str(num) + text) # "10 yen"
⚠️ Caution 2: Implicit conversion does not occur for lists or dictionaries
num_list = [1, 2, 3]
# This will cause an error
# print(num_list + 10) # TypeError
# Correct approach
num_list.append(10)
print(num_list) # [1, 2, 3, 10]
5.4 Benefits and Drawbacks of Implicit Type Conversion
✅ Benefits
Developers can perform calculations smoothly without having to think about type conversion.
int → float or int → complex, etc., allow conversions that do not compromise data precision.
When bool is converted to int, intuitive calculations like True + 1 == 2 become possible.
⚠️ Drawbacks
Unintended type conversions can cause bugs (e.g., when an int becomes a float, rounding errors may occur).
Data types such as lists and dictionaries are not implicitly converted, so appropriate handling is required.
5.5 Summary
In Python, implicit type conversion occurs primarily with numeric types, allowing calculations to be performed with the appropriate type without the developer explicitly casting.
Source Type
Target Type
Example
int → float
float
10 + 2.5 → 12.5
int → complex
complex
10 + (2+3j) → (12+3j)
bool → int
int
True + 1 → 2
6. Common Errors and Countermeasures in Python Casting
6.1 Main Errors that Occur During Casting
The following errors commonly occur when casting (type conversion) in Python.
Error Type
Cause
Example
ValueError
When attempting to cast data that cannot be converted
int("abc")
TypeError
When trying to operate on incompatible types
10 + "5"
KeyError
When specifying a key that does not exist in a dict
my_dict["missing_key"]
AttributeError
When using a method or attribute that does not exist for the type
10.append(5)
6.2 ValueError: Converting Invalid Values
# The string "abc" cannot be converted to an integer
num = int("abc") # ValueError
Solution
user_input = "abc"
if user_input.isdigit():
num = int(user_input)
print(num)
else:
print("Cannot convert to a number")
6.3 TypeError: Improper Operations Between Types
num = 10
text = "yen"
print(num + text) # TypeError
Solution
print(str(num) + text) # "10 yen"
6.4 KeyError: Retrieving a Nonexistent Key from a Dictionary
if 0 <= index < len(my_list):
print(my_list[index])
else:
print("The specified index is out of range")
6.8 TypeError: Incorrect Argument Types for a Function
def add_numbers(a: int, b: int):
return a + b
print(add_numbers(10, "20")) # TypeError
Solution
def add_numbers(a, b):
if isinstance(a, (int, float)) and isinstance(b, (int, float)):
return a + b
else:
return "Please enter a numeric value"
print(add_numbers(10, "20")) # "Please enter a numeric value"
6.9 Summary
In Python casting (type conversion), the following errors are common, so it is important to take appropriate measures.
Error
Cause
Mitigation
ValueError
Converting invalid values
Check with isdigit()
TypeError
Improper operations between types
Explicitly convert with str()
KeyError
Referencing a nonexistent dictionary key
Use dict.get()
AttributeError
Calling a nonexistent method
Check with hasattr()
ZeroDivisionError
Division by zero
Avoid with denominator != 0
IndexError
List index out of range
Check with if index < len(list)
7. Practical: Using Casts in Python | With Code Examples
7.1 Converting User Input to Numbers for Calculation
age = input("Please enter your age: ") # User input is of type str
if age.isdigit(): # Check if it's numeric
age = int(age) # Convert to integer
print(f"In 10 years, you will be {age + 10} years old.")
else:
print("Please enter a numeric value.")
7.2 Converting List Numbers to Strings and Joining
numbers = [10, 20, 30, 40]
str_numbers = [str(num) for num in numbers] # Convert each element to a string
result = ", ".join(str_numbers)
print(result) # "10, 20, 30, 40"
7.3 Casting When Processing CSV Data
csv_data = [
["Alice", "25", "170.5"],
["Bob", "30", "180.2"],
]
for row in csv_data:
name = row[0]
age = int(row[1]) # Convert age to integer
height = float(row[2]) # Convert height to float
print(f"{name} is {age} years old, and their height is {height} cm.")
data = {"1": "apple", "2": "banana", "3": "cherry"}
new_data = {int(k): v for k, v in data.items()}
print(new_data) # {1: 'apple', 2: 'banana', 3: 'cherry'}
Using casts in Python appropriately makes data processing smoother. In particular, casts are important in the following cases.
Use Case
Casting Method
User Input Processing
int() and float()
Converting List Data to Strings
[str(x) for x in list]
Type Conversion for CSV and JSON Data
int(), float()
Converting Dictionary Keys to Numbers
{int(k): v for k, v in dict.items()}
Rounding Calculation Results to Integers
round() and int()
Using Boolean Values as Numbers
int(True) → 1, int(False) → 0
8. Frequently Asked Questions and Solutions About Python Casting [FAQ]
8.1 Are casting and type conversion the same?
Yes, basically casting (cast) and type conversion (type conversion) have the same meaning. However, the term “cast” often refers specifically to “explicit type conversion”.
8.2 Is casting possible between all data types?
No, casting is not possible between all data types. Let’s look at examples of cases where type conversion is possible and where it is not.
User input is obtained via input(), so it always comes in as a string (str). To prevent errors, use exception handling (try-except) when casting.
while True:
user_input = input("Please enter an integer: ")
try:
num = int(user_input)
break
except ValueError:
print("Invalid input. Please enter an integer.")
print(f"Entered number: {num}")
8.7 Summary
We have explained the frequently asked questions and solutions about Python casting.
Question
Solution
What is the difference between casting and type conversion?
Basically the same meaning, but “cast” often refers to explicit conversion
Is casting possible between all data types?
Not always (e.g., int("abc") raises an error)
Should implicit type conversion be avoided?
Useful when used properly, but unintended conversions can cause bugs
What is the difference between isinstance() and casting?
isinstance() checks type, casting converts type
What is a safe way to convert types?
Using try-except prevents errors
9. Summary | Code examples you can try now
9.1 The importance of casting in Python
Casting (type conversion) is a fundamental technique in Python programming for handling data properly.
It is mainly used in the following situations. ✅ Maintain data type consistency ✅ Enable calculations between different data types ✅ Prevent errors
9.2 Basics of casting (type conversion) in Python
In Python, you can explicitly convert data types using built-in functions.
9.4 Common errors during casting and how to address them
Error
Cause
Solution
ValueError
Invalid value conversion
Use isdigit() to check for numeric values
TypeError
Inappropriate operation between types
Explicitly convert using str()
KeyError
Reference to a non-existent dictionary key
Use dict.get()
AttributeError
Calling a non-existent method
Check with hasattr()
Example of safe casting
user_input = "100a"
try:
num = int(user_input) # Convert to number
print(f"Conversion successful: {num}")
except ValueError:
print("Invalid input. Please enter a numeric value.")
9.5 Practical code: Leveraging casting in Python
while True:
user_input = input("Please enter your age (integers only): ")
if user_input.isdigit(): # Check if input is numeric
age = int(user_input)
print(f"In 10 years, the age will be {age + 10} years.")
break
else:
print("Invalid input. Please enter an integer.")
9.6 Best practices for casting
✅ Check data types in advance ✅ Implement error handling ✅ Use appropriate conversion functions ✅ Avoid over-reliance on implicit conversion
9.7 Summary and future learning points
In this article, we covered the following topics. ✔ Basics of casting in Python ✔ Explicit type conversion (int(), float(), str(), etc.) ✔ Implicit type conversion (Python’s automatic conversion) ✔ Common casting errors and their solutions ✔ Practical examples of using casting To make Python programming more efficient, be sure to write and try the code yourself! 🚀