While Python can automatically convert data types when it is safe to do so, there are many situations where you need full control over how values are transformed. Explicit type casting is the solution in such cases, allowing you to manually convert data from one type to another as needed.
This approach is part of the broader concept of type casting in Python, where data types are intentionally converted to meet specific requirements.
Note: To understand the fundamentals of type casting in Python — including how and why data types are converted — explore our complete guide on Python Type Casting.
What is Explicit Type Casting in Python?
Explicit type casting in Python refers to manually converting a value from one data type to another using built-in casting functions.
These built-in functions allow you to convert between numeric types, strings, booleans, and complex numbers as needed.
The most commonly used casting functions are listed below:
Built-in Casting Functions in Python:
int()– Converts value to integer typefloat()– Converts value to floating-point numberstr()– Converts value to string formatbool()– Converts value to boolean (True/False)complex()– Converts value to complex number type
Example:
x = "123"
y = int(x)
print(y) # Output: 123
print(type(y)) # Output: <class 'int'>
Explanation:
In this example, the string “123” is explicitly converted into an integer using the int() function. By manually casting the value, you ensure that Python treats it as a number rather than text. This level of control helps prevent errors and guarantees that calculations or comparisons behave as expected.
Pro Tip:
Use explicit type casting whenever working with user input or external data sources. For example, values entered through forms are typically received as strings and must be converted into numeric types before performing calculations or analysis.
Why Use Explicit Casting in Python?
Explicit type casting in Python is used when data needs to be processed or displayed in a specific format. It ensures accuracy and prevents unexpected behavior, especially when working with user input or calculations.
Here are common reasons developers use explicit casting:
i) Preparing Data for Arithmetic Operations
When values are stored as strings (e.g., “25” or “3.5”), Python treats them as text. Arithmetic operations cannot be performed directly.
By converting them using int() or float(), calculations work correctly.
Example:
x = "10"
y = "5"
total = int(x) + int(y)
print(total)
# Output: 15
Explanation:
Since x and y are strings, adding them directly would result in “105”. Converting them with int() allows numeric addition instead.
ii) Converting User Input into Numeric Types
When using the input() function, Python always reads the entered value as a string — even if the user types a number.
Explicit type casting ensures the value is converted into the correct numeric type before performing calculations.
Example
age = input("Enter your age: ") # Always returns string
age = int(age) # Explicitly cast to integer
print("You are", age, "years old.")
Explanation:
Since input() returns a string, converting it with int() allows arithmetic operations or comparisons to work correctly.
iii) Formatting Output for Display or Logging
The str() function converts numbers, booleans, or other values into string format.
This is useful when creating user-friendly messages, reports, or logs.
Example
score = 95
print("Your final score is " + str(score))
Explanation:
The str() function converts the integer into text, allowing it to be safely combined with other strings.
iv) Controlling Boolean Evaluations in Conditions or Loops
The bool() function helps control how values are evaluated in conditions, especially when variables may be empty or zero.
Example
tasks = []
if bool(tasks):
print("Tasks available")
else:
print("No tasks to complete")
Explanation:
Empty lists, empty strings, and numeric zeros evaluate to False. Using bool() makes condition checks clear and predictable.
Quick Recap
Explicit casting ensures:
- Accuracy in calculations
- Clarity in input/output handling
- Predictability in condition checks
- Error-free data manipulation
It’s one of the most powerful tools for maintaining clean, professional, and reliable Python code.
Common Explicit Casting Functions in Python
Python provides several built-in functions for manually converting values between different data types.
These functions are widely used in data processing, user input handling, and mathematical operations where type compatibility is important.
Explicit type casting gives developers control over how values are interpreted, improving accuracy and code clarity.
Type Casting Functions Table
The table below provides a quick reference to Python’s built-in type casting functions and their common usage.
| Function | Converts To | Usage Example |
|---|---|---|
| int() | Integer | int(“10”) → 10 |
| float() | Float | float(“3.14”) → 3.14 |
| str() | String | str(100) → “100” |
| bool() | Boolean | bool(0) → False |
| complex() | Complex | complex(3) → (3+0j) |
Below is a brief introduction to each casting function, along with a simple example and a link to its complete guide.
1. int() — Convert to Integer
Theint() function in Python converts numeric values, booleans, or digit-based strings into integers. It is one of the most commonly used type-casting functions.
Basic Example: int(value)
x = int("25")
print(x) # Output: 25
Explanation:
Here, the string “25” is converted into the integer 25 usingint(). After conversion, x stores a numeric value that can be used in calculations.
Explore detailed concepts and examples of Python’s int() function for converting strings, floats, and booleans into integers:
Python int() Function – Complete Guide
Move To Top ⬆ 2. float() — Convert to Floating-Point Number
The float() function converts integers, numeric strings, or boolean values into floating-point (decimal) numbers.
Basic Example: float(value)
price = float("19.99")
print(price) # Output: 19.99
Explanation:
In this example, "19.99" is a string. The float() function converts it into a decimal number. After conversion, Python treats it as a numeric value, allowing you to perform mathematical operations such as addition, subtraction, or division.
More Examples
print(float(5)) # Output: 5.0
print(float("2.5")) # Output: 2.5
print(float(True)) # Output: 1.0
print(float(False)) # Output: 0.0
print(float("1e3")) # Output: 1000.0
# print(float("xyz")) # Raises ValueError
Explanation:
The float() function converts values as follows:
- Whole numbers, e.g.,
5, into decimal form (5.0). - Numeric strings, e.g.,
"2.5", into floating-point values (2.5) that can be used in calculations. - Boolean values:
Truebecomes1.0andFalsebecomes0.0. - Non-numeric strings, e.g.,
"xyz", if passed tofloat(), will raise aValueError:float("xyz"). - The float() function converts the scientific notation string “1e3” into the decimal value 1000.0, because 1e3 represents 1 × 10³.
To learn about syntax details, scientific notation, and special cases, visit:
Python float() Function – Complete Guide
3. str() — Convert to String
The str() function converts numbers, booleans, or other data types into string format.
Basic Example: str(value)
message = str(100)
print(message) # Output: "100"
Explanation:
The str() function converts the number 100 into text. After conversion, the variable message stores “100” as a string.
Learn detailed concepts and practical examples of converting numbers, booleans, and collections into strings with Python’s str() function:
Python str() Function – Complete Guide
4. bool() — Convert to Boolean
The bool() function converts a value into either True or False based on its truth value.
Basic Example: bool(value)
print(bool(0)) # False
print(bool("Python")) # True
Explanation:
Line 1: bool(0) returns False because 0 is considered a falsy value in Python. Any numeric value equal to zero evaluates to False.
Line 2: bool("Python") returns True because the string is not empty. Any non-empty string is treated as truthy and evaluates to True.
See detailed examples of how Python evaluates different values as True or False across various data types:
Python bool() Function – Complete Guide
5. complex() — Convert to Complex Number
The complex() function converts numeric values into a complex number using real and imaginary parts.
Basic Syntax: complex(real, imaginary)
number = complex(3, 4)
print(number) # Output: (3+4j)
Explanation:
Line 1:In this example, complex(3, 4) creates a complex number where3 is the real part and 4 is the imaginary part.
Python automatically represents the imaginary part using j.
Line 2:The variable number now stores the value (3+4j).
When print(number) is executed, Python displays the complex number in standard form.
Learn about different input formats and numeric behavior of Python’s complex() function:
Python complex() Function – Complete Guide
Conclusion
Explicit type casting is a fundamental concept in Python that ensures data is handled accurately and predictably. By understanding when and how to convert between data types, you can write cleaner, safer, and more reliable programs.
Use this guide as a starting point and explore the detailed function-specific tutorials to strengthen your understanding of each casting function.