Python Type Conversion

Type conversion in Python

When we perform any operation on variables of different datatypes, the data of one variable will be converted to a higher datatype among the two variables and the operation is completed. This conversion is done by interpreter automatically and it is known as implicit type conversion. But Python does not support implicit type conversion and it will throw an error.

CODE/PROGRAM/EXAMPLE
//Program Example :
num1=10
	num2=“20”
	result=num1+num2
	print(result)

Output:
Traceback (most recent call last):
  File “D:	est.py”, line 3, in <module>
    result=num1+num2
TypeError: unsupported operand type(s) for +: 'int' and 'str'

If we have to avoid this, then we have to explicitly convert the datatype of one variable into the required datatype to complete the operation. This is known as explicit type conversion.

CODE/PROGRAM/EXAMPLE
//Program Example :
num1=10
	num2=“20”
	result=num1+int(num2)
	print(result)
	
Output:
	30
Notepad

Note :Programming languages define their own rules for implicit and explicit conversions. These rules will change from language to language.

Similarly, one has to be careful in explicit conversions as well. For example,

  • Converting a floating point value to integer would result in loss of decimal point values.
  • A larger data type if converted to smaller data type will result in loss of data as the number will be truncated.
#type_conversion_in_python #convert_string_to_integer_python #convert_list_to_array_python #convert_integer_to_string_in_python #data_type_conversion_in_python

(New page will open, for Comment)

Not yet commented...