【问题标题】:Unsupported operands str & int不支持的操作数 string 和 int
【发布时间】:2018-01-02 05:40:35
【问题描述】:

我在大约第 5 行收到 TypeError: unsupported operands (str & int)。我已经查找了如何解决它,但没有任何效果(这是学校作业,我必须使用 ifelifelse 表格)。如果不声明它们 x 和 y,我似乎也无法定义变量。

我什至看不到if 之后的打印语句如何受到影响,因为我无法越过第 5 行错误。那里有什么问题?

Temperature=int(input("What's the temperature outside?"))
Type=input("Is this Fahrenheit or Celsius?")
  print("So it's " + str(Temperature) + " degrees " + Type + " outside.")
Conversion=input("Do you want to convert this to Fahrenheit or Celsius. (Type F or C.)")
if(Conversion.lower()=="c"):
  print(Temperature+ " degrees Celsius is " +str((Temperature * 1.8)+32) + " degrees Fahrenheit.")
elif(Conversion.lower()=="f"):
  print(Temperature+ " degrees Celsius is " +str((Temperature * 1.8)+32) + " degrees Fahrenheit.")
else:
  print("You need to type either fahrenheit or celsius when it asks you. Re-run the program.")

好吧,伙计们,我发现了我的问题,这是新代码。 str/int 错误来自未将 str 函数放在温度变量前面。我把它留在这里给任何想知道的人。很抱歉一开始没有提供完整的代码,我不想让它烦人。

Temperature=int(input("What's the temperature outside?"))
Type=input("Is this Fahrenheit or Celsius?")
  print("So it's " + str(Temperature) + " degrees " + Type + " outside.")
Conversion=input("Do you want to convert this to Fahrenheit or Celsius. (Type F or C.)")
if(Conversion.lower()=="f"):
  print(str(Temperature) + " degrees Celsius is " + str((Temperature* 1.8)+32) + " degrees Fahrenheit.")
elif(Conversion.lower()=="c"):
  print(str(Temperature)+ " degrees Fahrenheit is " +str((Temperature -32)*5/9) + " degrees Celsius")
else:
  print("You need to type either fahrenheit or celsius when it asks you. Re-run the program.")

【问题讨论】:

  • 你尝试过什么调试?
  • 此代码不会为我运行,但不是因为类型错误。始终测试您发布的代码。
  • 您没有提到Temprature的值是什么,以及为什么要使用Type?而且默认情况下,输入是字符串,您再次将其转换为字符串。为什么会这样?
  • 对不起,这是我的完整代码,我只显示了我遇到错误的部分。
  • 在 Python 2 中,使用 raw_input(),而不是 input()

标签: python-2.7 if-statement operands


【解决方案1】:

在输入之前将温度声明为 int。

Temperature=0

尝试使用 raw_input 代替 input。

Temperature=int (raw_input ("What's the temperature outside?"))

或者创建一个整数类型变量,然后将它分配到你需要的地方。

n=0
n=raw_input ("What's the temperature outside?")
Temperature=n

【讨论】:

  • 我的老师希望我们在使用 if、elif、else 函数的同时还要处理变量。我的一些同学使用了他们在网上找到的 def 函数,但她希望我们先用这个来展示我们的知识。实际上,我现在正在课堂上写这个。还是谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-11-08
  • 2015-01-17
  • 2016-09-07
  • 2022-01-03
  • 2013-12-17
  • 2018-12-13
  • 2018-04-16
  • 1970-01-01
相关资源
最近更新 更多