TypeError:无法转换' int'隐含地反对str

时间:2015-01-23 23:19:14

标签: python

我是新手。我已经开始在Ubuntu上使用python。我的版本是Python3.4 我写了以下代码&得到错误:

>>> g=input("Enter number here: ")
Enter number here: 43
>>> g+7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> a= input("Enter:")
Enter:43
>>> a +32
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> a+32
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> 

可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

input将返回str,您必须将其转换为int才能使用它进行数字操作

>>> g = int(input('enter a number:'))
enter a number: 5

>>> g + 7
12

转化前

>>> g = input('enter a number:')
enter a number: 5

>>> type(g)
<class 'str'>

转化后

>>> g = int(input('enter a number:'))
enter a number: 5

>>> type(g)
<class 'int'>

答案 1 :(得分:0)

尝试:

>>> int(g)+7

......和:

>>> int(a) + 32

答案 2 :(得分:0)

也许你可以试试这个...... 在python 3.4中,input()被转换为字符串。你可以拨打g,结果是'43' ..这个字符串..
所以转换为integer

>>> g=input("Enter number here: ")
Enter number here: 43
>>> g+7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>> 
>>> g
'43'
>>> int(g)+7
50
>>>