Why is this an error?
"The correct answer to this multiple choice exercise is answer number " + 2
TypeError: Can't convert 'int' object to str implicitly
Why doesn't Python simply print the string and the integer together as the code instructed?
Thanks,
Phil
Python is not like some other languages like javascript, you need to cast the int to str in order to perform concatenation. Just accept it. This yields to ugly code. That is why more advanced str.format() or f-string are preferred and they offer more advantages. check
https://docs.python.org/3/library/string...ing-syntax and string formatting mini-language.
Function of adding is example of polymorphism (the ability of different objects to respond to the same message differently).
In Python context this means that function of adding is defined in different datatypes. Adding can be used on different datatypes with different results.
Adding a + b is 'syntactic sugar' on a.__add__(b). This means that any class which has implemented __add__ method supports adding (between instances of the class). For integers it's 'classic' adding: 1 + 1 -> 2, but in case of lists it's actually concatenation [1, 2] + [3, 4] -> [1, 2, 3, 4]
Due to polymorphism adding is not supported between all datatypes i.e instances of all datatypes (obviously it supported between numerics) because it is defined to deliver different results. If you have adding and concatenation it's hard to find common ground and "In the face of ambiguity, refuse the temptation to guess."
I like
TypeError
s.
With JavaScript you can do this:
Array(16).join("wat" - 1) + " Batman!";
Output:
"NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN Batman!"