【问题标题】:Getting error in python code [duplicate]python代码中出现错误[重复]
【发布时间】:2015-01-18 11:46:06
【问题描述】:

我是python的新手

我用python写了一段代码..

#!/usr/bin/python
s = raw_input('--> ')
print eval('s+1')

我遇到这样的错误

  [root@python ~]# python 2.py
  --> 2
  Traceback (most recent call last):
  File "2.py", line 3, in <module>
  print eval('s+1')
  File "<string>", line 1, in <module>
  TypeError: cannot concatenate 'str' and 'int' objects

可能是什么原因..

【问题讨论】:

标签: python eval


【解决方案1】:

s 将是一个字符串,由raw_input 返回。然后你尝试eval(你不应该这样做)s + 1。 1 是一个整数,正如错误告诉您的那样,您不能将字符串添加到整数。

如果您打算将s 变成int,您可以转换它。

s = int(raw_input('--> '))

但同样,不要使用eval

s = int(raw_input('--> '))
print s + 1

【讨论】:

  • 非常感谢.. 成功了..
猜你喜欢
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-06
  • 2016-11-04
  • 1970-01-01
  • 2017-03-15
相关资源
最近更新 更多