25 Sep

What is Type Coercion?

Type coercion refers to the automatic conversion of one data type to another, usually performed by the Python interpreter. 

This type of conversion occurs when mixing data types in operations or assignments. It is an implicit process, meaning that it occurs automatically without the programmer specifying it. 

Note: In some cases, this can lead to unexpected results, especially when working with large or complex data sets. However, it can also simplify code by eliminating the need for explicit type casting.

JS

  • Type coercion is automatic. 
  • This means that if you try to perform an operation on two values of different types, the values will be automa­tically converted to the same type before the operation is performed.

Number to String Conversion

// The Number is converted to string and then '+' concatenates both strings   

var yearWithName = 2023 + 'Girish';
console.log(yearWithName); // 2023Girish

var nameWithYear = 'Girish' + 2023; 
console.log(nameWithYear); // Girish2023
 
// The Boolean value true is converted to string 'true' and then '+' concatenates both the strings

var trueValue = true + 'Value';  
console.log(trueValue); // trueValue

     String to Number Conversion

// When an operation like subtraction (-), multiplication (*), division (/) or modulus (%) is performed, all the values that are not number are converted into the number data type, as these operations can be performed between numbers only.

var numberStringSubtraction = 10 - '5';
console.log(numberStringSubtraction)

var numberStringMultiplication = 10 * '5';
console.log(numberStringMultiplication)

var numberStringDivision = 10 / '5';
console.log(numberStringDivision)

var numberStringModulus = 10 % '5';
console.log(numberStringModulus)

Boolean to Number

// The Boolean value true is converted to number 1 and then operation is performed

var increaseNumberByOne = true + 2;  

// The Boolean value false is converted to number 0 and then operation is performedvar 

keepTheNumberSame = false + 2;

The Equality Operator

// Should output 'true' as string '10' is coerced to number 10
var x = (10 == '10');
console.log(x);  // true

// Should output 'true', as boolean true is coerced to number 1
var y = (true == 1);  
console.log(y); // true

// Should output 'false' as string 'true' is coerced to NaN which is not equal to 1 of Boolean true
var z = (true == 'true');
console.log(x); // false


Python

  • Type coercion is not automatic and not supported in the python. 
  • Although Type casting is supported, where you must explicitly convert values to the desired type before performing an operation on them.
  • But, wait, understand some below cases:

Numeric Types and Coercion

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

Python did not coerce the integer into a floating-point number. 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:

>>> y.__radd__(x)
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

>>>  concatenateMe = "concatenateMeWithNumber"
>>> x
2
>>> concatenateMe + x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

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. 

To accomplish the above, we need to explicitly convert (perform type casting) the number to a string:

>>> concatenateMe + str(x)


Comments
* The email will not be published on the website.