【问题标题】:TypeError: bad operand type for unary +: 'str' pythonTypeError:一元+的错误操作数类型:'str'python
【发布时间】:2015-10-20 13:36:01
【问题描述】:
number=int(input("Please enter a number:     "))

for b in range(1,11):
    b=int(b)
    output=int (number) *int (b)
    print(+str (b) +" times "+ str (number) +" is " +output)

我希望程序询问一个数字,然后打印它的时间表,最多为 10*number,但是我不断收到此错误。顺便说一句,我正在做 GCSE 计算。

Traceback (most recent call last):
File "C:\Users\jcowp_000\Documents\School\Lutterworth\Computing\Documents_-_-___________---________---______-_-_-_-__-__\Python\Python manual tasks.py", line 21, in <module>
print(+str (b) +" times "+ str (number) +" is " +output)
TypeError: bad operand type for unary +: 'str'

【问题讨论】:

  • 你为什么要b = int(b)b 已经是 int。另外,+str(b) 你想做什么?
  • 我要它打印,比如1乘5就是5,2乘5就是10,等等
  • 尾随 + 不应该在那里,您还应该将输出转换为字符串。否则 Python 将不知道您是要执行字符串连接还是数字相加。
  • 在我的例子中 str(b) 是 1 或 2
  • 如何将输出转换为字符串

标签: python operands


【解决方案1】:

我认为这就是你想要做的:

number = int(input("Please enter a number:     "))

for b in range(1,11):
    output = int(number) * b   # b is already an int, you can use it directly in computations
    print(str(b) + " times " + str(number) + " is " + str(output))

请注意+str(b) 的语法不正确,还请注意您不能将" is"(即str)与output(即int)连接起来。

【讨论】:

  • 听起来很讽刺
  • 虽然这个答案是正确的,但我想指出int(b) 没有意义,正如@Donald 在上面的 cmets 中所建议的那样。你可以简单地做output = int(number) * b
【解决方案2】:
number=int(input("Please enter a number:     "))

for b in range(1,11):
    b=int(b)
    output=int (number) *int (b)
    print(b, "times",number,"is",output)

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 2013-08-11
  • 2013-03-28
  • 2019-02-17
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多