Python Forum
Why is this an error? (string and integer) - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why is this an error? (string and integer) (/thread-12591.html)



Why is this an error? (string and integer) - pcsailor - Sep-02-2018

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


RE: Why is this an error? (string and integer) - buran - Sep-02-2018

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.html#format-string-syntax and string formatting mini-language.


RE: Why is this an error? (string and integer) - pcsailor - Sep-02-2018

Thanks,
okay,
Quote:Just accept it

phil


RE: Why is this an error? (string and integer) - perfringo - Feb-05-2020

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."


RE: Why is this an error? (string and integer) - DeaD_EyE - Feb-05-2020

I like TypeErrors.

With JavaScript you can do this:
Array(16).join("wat" - 1) + " Batman!";
Output:
"NaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaNNaN Batman!"