Type conversion and coercion in python

Before learning Type Conversion in Python, you should have knowledge about Python Data Types.

Type Conversion

The process of converting the value of one data type [integer, string, float, etc.] to another data type is called type conversion. Python has two types of type conversion.

  1. Implicit Type Conversion
  2. Explicit Type Conversion

Implicit Type Conversion

In Implicit type conversion, Python automatically converts one data type to another data type. This process doesn't need any user involvement.

Let's see an example where Python promotes the conversion of the lower data type [integer] to the higher data type [float] to avoid data loss.

Example 1: Converting integer to float

num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print["datatype of num_int:",type[num_int]]
print["datatype of num_flo:",type[num_flo]]

print["Value of num_new:",num_new]
print["datatype of num_new:",type[num_new]]

When we run the above program, the output will be:

datatype of num_int: 
datatype of num_flo: 

Value of num_new: 124.23
datatype of num_new: 

In the above program,

  • We add two variables num_int and num_flo, storing the value in num_new.
  • We will look at the data type of all three objects respectively.
  • In the output, we can see the data type of num_int is an integer while the data type of num_flo is a float.
  • Also, we can see the num_new has a float data type because Python always converts smaller data types to larger data types to avoid the loss of data.

Now, let's try adding a string and an integer, and see how Python deals with it.

Example 2: Addition of string[higher] data type and integer[lower] datatype

num_int = 123
num_str = "456"

print["Data type of num_int:",type[num_int]]
print["Data type of num_str:",type[num_str]]

print[num_int+num_str]

When we run the above program, the output will be:

Data type of num_int:  
Data type of num_str:  

Traceback [most recent call last]: 
  File "python", line 7, in  
TypeError: unsupported operand type[s] for +: 'int' and 'str'

In the above program,

  • We add two variables num_int and num_str.
  • As we can see from the output, we got TypeError. Python is not able to use Implicit Conversion in such conditions.
  • However, Python has a solution for these types of situations which is known as Explicit Conversion.

Explicit Type Conversion

In Explicit Type Conversion, users convert the data type of an object to required data type. We use the predefined functions like int[], float[], str[], etc to perform explicit type conversion.

This type of conversion is also called typecasting because the user casts [changes] the data type of the objects.

Syntax :

[expression]

Typecasting can be done by assigning the required data type function to the expression.

Example 3: Addition of string and integer using explicit conversion

num_int = 123
num_str = "456"

print["Data type of num_int:",type[num_int]]
print["Data type of num_str before Type Casting:",type[num_str]]

num_str = int[num_str]
print["Data type of num_str after Type Casting:",type[num_str]]

num_sum = num_int + num_str

print["Sum of num_int and num_str:",num_sum]
print["Data type of the sum:",type[num_sum]]

When we run the above program, the output will be:

Data type of num_int: 
Data type of num_str before Type Casting: 

Data type of num_str after Type Casting: 

Sum of num_int and num_str: 579
Data type of the sum: 

In the above program,

  • We add num_str and num_int variable.
  • We converted num_str from string[higher] to integer[lower] type using int[] function to perform the addition.
  • After converting num_str to an integer value, Python is able to add these two variables.
  • We got the num_sum value and data type to be an integer.

Key Points to Remember

  1. Type Conversion is the conversion of object from one data type to another data type.
  2. Implicit Type Conversion is automatically performed by the Python interpreter.
  3. Python avoids the loss of data in Implicit Type Conversion.
  4. Explicit Type Conversion is also called Type Casting, the data types of objects are converted using predefined functions by the user.
  5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.

  • Articles
  • Screencasts
  • Exercises
  • Courses
  • Pastebin
  • Gift
  • Sign Up
  • Sign In

2 minute read Python 3.7—3.10

Watch as video

02:31

Sign in to your Python Morsels account to save your screencast settings.

Don't have an account yet? Sign up here.

Many programming languages have something called type coercion; it's where the language will implicitly convert one object to another type of object in certain circumstances.

Python does not have type coercion.

Numeric Types and Coercion

If we add together an integer [2] and a floating-point number [3.5] in Python, we'll get back a floating-point number:

>>> x = 2
>>> y = 3.5
>>> x + y
5.5

Python did not coerce the integer into a floating-point number; we don't have type coercion in Python. Instead, Python delegated to the integer and floating point numbers and asked those objects to add themselves together.

Whenever Python sees x + y, it calls the __add__ method on x passing y to it:

>>> x.__add__[y]
NotImplemented

In this case Python got NotImplemented back because integers don't know how to add themselves to floating-point numbers. This special NotImplemented value was returned by the__add__ method of the integer object to let Python know that x [an int] doesn't know how to support the + operator with y [a float].

When Python sees this special NotImplemented value, it then attempts to ask y whether it knows how to add itself to x. To do this Python call the __radd__ method on y, passing it x:

This adds the floating-point number to the integer from the right-hand side of the plus sign [r is for "right" in __radd__] and returns 5.5.

So no type coercion was done here, instead, one of these types of objects knows how to operate with the other type of object when used with the plus operator.

Python Objects Don't Support Type Coercion

A counterexample of this is strings.

What happens if we try to use the + operator between a string and a number in Python?

>>> name = "Trey"
>>> x
2
>>> name + x
Traceback [most recent call last]:
  File "", line 1, in 
TypeError: can only concatenate str [not "int"] to str

Many programming languages would make the string Trey2 above: they would concatenate that string and that number, by coercing the number into the string. In Python, we get an error instead.

The reason is that strings in Python don't know how to use the plus operator with numbers and numbers in Python don't know how to use the plus operator with strings, which means our code doesn't work.

So to actually accomplish what we're looking for, we need to explicitly convert the number to a string:

>>> name + str[x]
'Trey2'

We've made a new string out of that number 2, and we're concatenating it to our string name to get another string.

Summary

Python don't have type coercion. Python doesn't ever implicitly converts one object to another type of object.

You'll always either rely on at least one of the objects you're working with knowing how to operate with the other type of object or you'll have to explicitly convert one of your objects to another type of object.

Series: Overlooked Fundamentals

These topics are commonly overlooked by new Python programmers.

To track your progress on this Python Morsels topic trail, sign in or sign up.

A Python Tip Every Week

Need to fill-in gaps in your Python skills? I send weekly emails designed to do just that.

Watch as video

02:31

Table of Contents

Next Up 03:49

In Python, everything is an object. Classes are objects, instances of classes are objects, modules are objects, and functions are objects. Anything that you can point a variable to is an object.

What is the difference between type coercion and type conversion?

Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.

What is coercion in Python?

Coercion is the implicit conversion of an instance of one type to another during an operation which involves two arguments of the same type.

Is there type coercion in Python?

Many programming languages have something called type coercion; it's where the language will implicitly convert one object to another type of object in certain circumstances. Python does not have type coercion.

What is type conversion in Python with example?

Explicit Type Conversion in Python.

Chủ Đề