- Understanding Python Type Casting: A Comprehensive Guide
- What is Type Casting?
- Why is Type Casting Important in Python?
- Types of Type Casting in Python
- Implicit Type Casting
- Explicit Type Casting
- Type Casting in Python: Examples
- Type Casting in Python: Common Issues
- TypeError
- ValueError
- Loss of Precision
- Conclusion
- Type Casting in Python
- Types of Casting in Python
- 1. Implicit Type casting
- 2. Explicit Type casting
- Examples of Type Casting in Python
- Example # 1 – Implicit Type Conversion/Casting
- Example #2 – Explicit Type Conversion
- Example #3 – Explicit Type casting Using Constructor Functions
- Conclusion
- Recommended Articles
Understanding Python Type Casting: A Comprehensive Guide
Python is a high-level programming language that has become popular for its simplicity, readability, and versatility. One of the features of Python is type casting, which is the process of converting one data type into another. This guide aims to provide a comprehensive understanding of type casting in Python.
What is Type Casting?
Type casting, also known as type conversion, is a process in which data of one type is converted into another type. In Python, this can be achieved using functions such as int() , float() , and str() . For example, converting a floating-point number to an integer using int() or converting a string to a float using float() .
Why is Type Casting Important in Python?
Type casting is important in Python because different data types have different properties and functions associated with them. For example, integers can be used for mathematical operations, whereas strings can be used for text manipulation. By converting data from one type to another, we can perform operations that are specific to that data type.
Types of Type Casting in Python
In Python, there are two types of type casting: implicit type casting and explicit type casting.
Implicit Type Casting
Implicit type casting, also known as automatic type conversion, occurs when Python automatically converts one data type into another. This happens when a value of one type is assigned to a variable of another type.
For example, if we assign a floating-point number to an integer variable, Python will implicitly cast the floating-point number to an integer:
In this example, the floating-point number 10.5 is implicitly cast to an integer 10 when it is assigned to the integer variable y .
Explicit Type Casting
Explicit type casting, also known as manual type conversion, occurs when a programmer explicitly casts a value from one type to another using type casting functions.
For example, if we want to convert an integer to a floating-point number, we can use the float() function:
In this example, the integer 10 is explicitly cast to a floating-point number 10.0 using the float() function.
Type Casting in Python: Examples
Here are some examples of type casting in Python:
# Converting an integer to a floating-point number x = 10 y = float(x) print(y) # Converting a floating-point number to an integer x = 10.5 y = int(x) print(y) # Converting a string to an integer x = "10" y = int(x) print(y) # Converting a string to a floating-point number x = "10.5" y = float(x) print(y) # Converting an integer to a string x = 10 y = str(x) print(y) # Converting a floating-point number to a string x = 10.5 y = str(x) print(y)
Type Casting in Python: Common Issues
There are several common issues that arise when type casting in Python. Here are a few of the most common ones:
TypeError
A TypeError occurs when a type casting function is called with an argument that is not of the correct type. For example, if we try to convert a string that cannot be converted to an integer to an integer using the int() function, a TypeError will be raised:
TypeError: invalid literal for int() with base 10: 'hello'
In this example, the string «hello» cannot be converted to an integer, so a TypeError is raised.
ValueError
A ValueError occurs when a type casting function is called with an argument that is not a valid value for that type. For example, if we try to convert a string that cannot be converted to a floating-point number to a floating-point number using the float() function, a ValueError will be raised:
x = "hello" y = float(x) print(y)
ValueError: could not convert string to float: 'hello'
In this example, the string «hello» cannot be converted to a floating-point number, so a ValueError is raised.
Loss of Precision
When converting a floating-point number to an integer, there may be a loss of precision. This is because the decimal part of the floating-point number will be truncated, and only the integer part will be kept. For example:
In this example, the decimal part of the floating-point number 10.5 is lost when it is converted to an integer 10 .
Conclusion
In this guide, we have covered the basics of type casting in Python. We have discussed what type casting is, why it is important, and the different types of type casting. We have also seen several examples of type casting in action and some of the common issues that can arise when type casting. By understanding type casting, you will be able to write more efficient and versatile code in Python.
Type Casting in Python
Type casting is a method used to change the variables/ values declared in a certain data type into a different data type to match the operation required to be performed by the code snippet. In python, this feature can be accomplished by using constructor functions like int(), string(), float(), etc. The type casting process’s execution can be performed by using two different types of type casting, such as implicit type casting and explicit type casting.
Types of Casting in Python
Python has two types of type conversion:
1. Implicit Type casting
Implicit type conversion is performed automatically by the interpreter, without user intervention. Python automatically converts one data type to another data type. This process doesn’t need any user involvement Python promotes the conversion of lower data type, for example, integer to higher data type says float to avoid data loss. This type of conversion or type casting is called UpCasting.
2. Explicit Type casting
In Explicit Type conversion, the user or programmer converts the data type of an object to the required data type. In Python we use predefined functions like int(), float(), str(), bool() etc to perform explicit type conversion.
(Required datatype) (Expression) ↓ (Desired type)
Examples of Type Casting in Python
Below are the examples of type casting in python:
Example # 1 – Implicit Type Conversion/Casting
Program to illustrate Implicit Type conversion/casting.
Python file: Example1.py
# Program to illustrate Implicit type conversion # creating addition() function to add two numbers def addition(a, b): print("Type of first number(a) :", a, type(a)) print("Type of second number(b) :", b, type(b)) c = a + b print("Type of resulting variable(c) :", c, type(c)) # addition() function calls with different inputs addition(21, 23) # both integers print('\n') addition(21, 23.0) # second being float print('\n') addition(21.0, 23) # first being float print('\n') addition(21.0, 23.0) # both float
Output: Example1.py
Explanation:
The function to add two numbers is defined. Type of first input number, second input number and the type of summation is printed.
- The first call of addition(): Both input numbers are of integer type, so the result is also an integer. No type casting is needed in this case.
- The second call of addition(): First input is an integer, and the second input is of floating type. So python interpreter internally converts the integer type to float type to avoid data loss. Therefore, the result is floating type, as shown in the above output.
- The third call of addition(): First input is a floating number, and the second input is of integer type. So python interpreter internally converts the integer type to float type to avoid data loss. Therefore, the result is a floating type.
- The fourth call of addition(): Both numbers are of floating type. So python interpreter will not perform any type of conversion here. Therefore, the result is a floating type.
Example #2 – Explicit Type Conversion
Following is an illustration of the Explicit type conversion.
Python file: Example2.py
# Program to illustrate Explicit type conversion # creating addition() function to add two numbers def addition(a, b): print("Type of first number(a) :", a, type(a)) print("Type of second number(b) :", b, type(b)) c = a + b print("Type of resulting variable(c) :", c, type(c)) print("accepting input from the user -->") print("Enter first number") num1 = input() print("Enter second number") num2 = input() # addition() function call addition(num1, num2) print('\n')
Output: Example2.py
Explanation:
- In the above program, the addition() function is defined, which will compute the summation of two numbers. The user is prompted to enter two numbers through input() statements.
- Finally, addition() is called with numbers 23 and 18. But the result is 2318 as shown in the below output and not 41. Why??
- This is because the return type of input() is a string. Therefore, the numbers entered by the user are treated as string values. So, the output is the concatenation of string rather than a summation of integers which is the expected output. In this case, Python will not perform any type casting itself. This can be corrected with Explicit type conversion.
Above Code Can Be Modified As:
# Program to illustrate Explicit type conversion # creating addition() function to add two numbers def addition(a, b): print("Type of first number(a) :", a, type(a)) print("Type of second number(b) :", b, type(b)) c = a + b print("Type of resulting variable(c) :", c, type(c)) # addition() function calls with different inputs print("accepting input from the user -->") print("Enter first number") # Explicit typecasting num1 = int(input()) print("Enter second number") num2 = int(input()) # addition() function call addition(num1, num2) print('\n')
Here, in this program int(input()) will convert the string to the integer type. Therefore, we’ll get the desired output as shown below:
Example #3 – Explicit Type casting Using Constructor Functions
Explicit Type casting using constructor functions like int(), float(), str() etc.
Python file: Example3.py
# Explicit Type conversion using constructor functions # 1 --> Converting to integer type using int() print("1: converting to integer type") print(int(9.6)) # float to int print(int(True)) # bool to int print(int(False)) # bool to int print("123") # str to int print('\n') # 2 --> converting to float type using float() print("2: converting to floating type") print(float(12)) # int to float print(float(True)) # bool to float print(float(False)) # bool to float print(float("123")) # string to float print('\n') # 3 --> converting to bool type using bool() print("3: converting to boolean type") print(bool(12)) # integer to bool print(bool(0.0)) # float to bool print(bool([1,2,3])) # list to bool print(bool()) # tuple to bool print('\n') # 4 --> converting to string type using str() print("4: converting to string type") print(str(123)) # integer to string print(str(12.12)) # float to string print(str([10, 20, 30])) # list to strings
Output: Example3.py
Note: Constructor functions are not limited to the above four ones. In fact list of constructor functions is quite exhaustive. It includes dict(), tuple(), list(), oct(), hex(), bin() and so on.
Conclusion
Time and again, there is a need to convert a value of one data type to another in any programming language. Python offers both Implicit type and Explicit type conversions.
A python interpreter performs implicit type conversion without programmer intervention. The programmer performs an explicit type conversion.
Recommended Articles
This is a Guide to Type Casting in Python. Here we discuss the basic concept, two different types and various examples of casting in python. You may also look at the following articles to learn more –