【问题标题】:Keep getting error code - TypeError: unsupported operand type(s) for -: 'int' and 'str'不断收到错误代码 - TypeError: unsupported operand type(s) for -: 'int' and 'str'
【发布时间】:2016-08-30 13:27:14
【问题描述】:

我正在尝试制作一个程序,该程序总是产生两个三位数之和,从其他两个三位数之差得出,如 1089,前提是最初选择的数字的第一位和第三位相差两个或更多的。我会澄清一下,我对此很陌生,只知道非常基础的知识。这就是我到目前为止所拥有的。

num1 = input("Choose a three digit number whose first and third digits vary by at least two numbers.")

num2 = num1[2] + num1[1] + num1[0]

if int(num1) < int(num2):

    difference = int(num2) - (num1)
else:

    difference = int(num1) - (num2)

newNum1 = str(difference)

newNum2 = newNum1[2] + newNum1[1] + newNum1[0]

ten89 = int(newNum1) + int(newNum2)

print ("If you chose your three-digit number correctly your should have gotten 1089 and you got," ,ten89)

我不断收到错误代码 -

TypeError: unsupported operand type(s) for -: 'int' and 'str' - for the line - difference = int(num2) - (num1).

我尝试将该行中的 int 更改为 str 以及其他。如果有人能告诉我哪里出错了,我将不胜感激。谢谢!

【问题讨论】:

  • 您似乎忘记在此处添加intdifference = int(num2) - (num1) 和此处:difference = int(num1) - (num2)

标签: python string int


【解决方案1】:

您收到此错误是因为 num1 是一个字符串。

input 返回的所有内容都是字符串。您需要转换为int 才能使用数学运算。

 >>> num1 = input("Choose a three digit number whose first and third digits vary by at least two numbers.")
 >>> ..... 123
 >>> print(type(num1))
 >>> <class 'str'>

【讨论】:

    猜你喜欢
    • 2020-04-04
    • 2021-03-27
    • 2020-04-14
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多