This lesson will teach you about Type Conversion in Python and how to use it. Before learning about Type Conversion in Python, you need to know what Python Data Types are, which were covered in the previous lesson.
Type conversion is changing a value from one data type (integer, string, float, etc.) to another. Python has two ways to change types.
When implicit type conversion is on, Python automatically changes from one data type to another. The user has nothing to do with this process.
Let’s look at how Python prevents data loss by converting the lower data type (integer) to the higher data type (float).
Example
intVar = 99 floatVar = 99.99 Sum = intVar + floatVar print("intVar datatype:",type(intVar)) print("floatVar datatype:",type(floatVar)) print("Sum:",Sum) print("Sum DataType:",type(Sum))
Output
intVar datatype:floatVar datatype: Sum: 198.99 Sum DataType:
In the show above,
intVar
, and floatVar
, and store their values in Sum
.intVar
is a type integer and floatVar
is a type float.Sum
has a float data type because Python always changes smaller data types to larger ones to avoid losing data.Now, let’s try adding two variables, a string, and an integer, to see how Python handles adding a string (higher data type) and an integer (lower data type).
Example
intVar = 99 stringVar = "99" print("Data type intVar:",type(intVar)) print("Data type stringVar:",type(stringVar)) Sum = intVar + stringVar print("Sum:",Sum) print("Sum DataType:",type(Sum))
Output
Data type intVar:Data type stringVar: Traceback (most recent call last): File " ", line 6, in TypeError: unsupported operand type(s) for +: 'int' and 'str'
In the show above,
We add intVar
and stringVar
, which are both variables. The output shows that we got TypeError, and Python can’t use Implicit Conversion in these situations. But Python has a way of dealing with these problems called “Explicit Conversion.”
In Explicit Type Conversion, the data type of an object is changed to the type of data needed. For explicit type conversion, we use built-in functions like int(), float(), str(), and so on. This kind of conversion is also called “typecasting” because the user changes the data type of the objects.
Basic Syntax
(expression)
Typecasting can be done by giving the expression the function for the data type it needs.
Example
intVar = 99 stringVar = "99" print("Data type intVar:",type(intVar)) print("Data type stringVar:",type(stringVar)) Sum = intVar + int(stringVar) print("Sum:",Sum) print("Sum DataType:",type(Sum))
Output
Data type intVar:Data type stringVar: Sum: 198 Sum DataType:
We run the same example used in implicit conversion but after typecasting.
stringVar
and intVar
.This concludes the Python Type Conversion lesson. In the next lesson, you will learn Keywords and Identifiers in Python