Why is error returned if you add a String with a Number?

Asked

Viewed 59 times

-2

If I type the following in the terminal of the Python no error is returned and the result is displayed normally.

In the terminal:

>> 10 + "10"  # 20

But if I put in variables and try to add up is returned an error.

In the archive:

n1 = 10
n2 = "10"

print(n1 + n2)

Error:

Traceback (most recent call last):
File "c:/Users/Desktop/test-py/test.py", line 5, in <module>
print(n1 + n2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Because in the terminal error is returned, but already in the file with the code?

  • I just tested the same thing and both do not work Python 3.7.5 (default, Nov 20 2019, 09:21:52) [GCC 9.2.1 20191008] on linux Type "help", "copyright", "Credits" or "License" for more information. >>> n1 = 10 >>> N2 = "10" >>> n1 + N2 Traceback (Most recent call last): File "<stdin>", line 1, in <module> Typeerror: Unsupported operand type(s) for +: 'int' and 'str' >>> 10 + "10" Traceback (Most recent call last): File "<stdin>", line 1, in <module> Typeerror: Unsupported operand type(s) for +: 'int' and 'str' >>>

  • Anything is just casting "10" to int like this: int("10")

1 answer

2


Your premise is wrong, the concatenation between a variable of type str and another of the kind int not possible in Python! This type of operation throws an exception of type TypeError:

$ python3
Python 3.6.8 (default, Aug  7 2019, 17:28:10) 
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 10 + "10"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>

The only way to make such a thing possible is to overload the magical method __add__() of the kind int, look at you:

class Integer(int):
    def __add__(self, other):
        return Integer(int(self) + int(other))


n1 = Integer(10)
n2 = "10"

print(n1 + n2)

Exit:

20

Browser other questions tagged

You are not signed in. Login or sign up in order to post.