-2

Se eu digitar o seguinte no terminal do Python nenhum erro é retornado e é exibido o resultado normalmente.

No terminal:

>> 10 + "10"  # 20

Mas se eu colocar em variáveis e tentar somar é retornado um erro.

No arquivo:

n1 = 10
n2 = "10"

print(n1 + n2)

Erro:

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'

Porque no terminal é retornado erro, mas já no arquivo com o código não?

2
  • Acabei de testar a mesma coisa e os dois não funcionam 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' >>> 29/03/2020 às 0:53
  • Qualquer coisa é só fazer o casting do "10" para int assim: int("10") 29/03/2020 às 0:55

1 Resposta 1

2

Sua premissa está errada, a concatenação entre uma variável do tipo str e outra do tipo int não é possível em Python! Esse tipo de operação lança uma exceção do tipo 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'
>>>

A única maneira de tornar tal coisa possível é sobrecarregando o método mágico __add__() do tipo int, veja só:

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


n1 = Integer(10)
n2 = "10"

print(n1 + n2)

Saída:

20

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .