M&C7: We can mix types on expression. For example, why not write A = 5 + “Hero”?

We can mix types within an expression. For example, why not write A = 5 + “Hero”? 

Mixed type expressions are extremely common in two major areas. Programmers will frequently perform arithmetic using integer and floating point types. They will also try to use numbers with strings in an attempt to output a meaningful value. There are some internal mechanics of most programming languages that allow this type of functionality, but certain special cases can cause issues. Video Length: 3:30


Python Example 1: Combining an integer with a floating point. In Python, this can be completed without error due to arithmetic promotion of the integer to a floating point.

x = 4

y = 3.2

z = x + y      # computes 4.0 + 3.2

Python Example 2: Combining a string with an integer. In Python, this will cause a “Type Error”.

x = 3

y = "Chicken "

z = y + x      # can be fixed with an explicit cast

#  z = y + str(x)