Type casting in Python

3703

In this article, we will learn about

  • What do you mean by Type Casting
  • Why do we need Type Casting
  • How to perform Type Casting in Python
  • Type Conversion available in Python (with example codes)

 

What do you mean by Type Casting

Typecast is used in a program to cast the data type/value from one data type to another. For example, there is a float data and you want to convert it into an integer data value.

Why do we need Type Casting

  • Sometimes we purposely need to round off float data to get the required integer value. Then type casting float to int will be required.
  • Also, when we are not sure about the input data, we forcefully use the typecast in that case.  

In Python 3 the default data type of input value is a string (str). For example please go through the mentioned code and output given below:

Note: We are purposely using the input() function in the given code. We will explain the input() function in greater detail in the upcoming section. Please bear with us.

In the given code we should see, what would be the consequence, if we are not using the required typecast.

Code: When Typecast is not used

# File name: type_cast_not_used.py
a = input()
b = a + 3
print(b)

 

Output: 

3
Traceback (most recent call last):
  File "type_cast_not_used.py", line 2, in <module>
   b = a + 3
TypeError: can only concatenate str (not "int") to str

 

Explanation: 

When you execute the above python script and entered 3 as input. Now we assume that a+3 will be calculated as 3 + 3 and print will return 6. But, it is not the case as input value will be treated as string type and string can only concatenate string type. Thus, TypeError will be returned.

Code: When Typecast is used

a = int(input())
b = a + 3
print(b)

 

Output: 

3
6

 

Explanation: 

When you execute the above python script and enter 3 as input. Sring type will be converted to int data type because we have used the int typecast in front of input() function. Thus, a variable will contain integer value and, b will perform the calculation correctly. The final output will be 6.

Type Conversion available in Python (with example codes)

Available Type Conversions

TypecastFunction
int(a, base)Converts any data type to integer. ‘Base’ specifies the base in which string is if the data type is a string.
float()Convert any data type to a floating-point number type.
ord()Convert a character data type to an integer type.
hex()Convert an integer data type to a hexadecimal string type.
oct()Convert an integer data type to an octal string type.
tuple()Convert to a tuple data type.
set()Returns the type after converting to set.
list()Convert any data type to a list data type.
dict()Convert a tuple of order (key, value) into a dictionary.
str()Is used to convert an integer into a string
complex(real, imag)Converts real numbers to complex(real, imag) number.