【发布时间】:2018-01-02 05:40:35
【问题描述】:
我在大约第 5 行收到 TypeError: unsupported operands (str & int)。我已经查找了如何解决它,但没有任何效果(这是学校作业,我必须使用 if、elif、else 表格)。如果不声明它们 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