我的学习之旅已经进行了两天,所以轻松一点!我正在尝试编写一个基本的温度应用程序,除了输入个位数之外,一切都运行得很好,没有错误。如果我输入两位数,它会正确地记录正确的响应,例如:“是的,这太热了”或“是的,这太冷了”,但它似乎将任何小于10的值识别为大于32且不小于27,从而给出“太热”的响应。
temperature = range(-30,55)
temperature = input("What is the temperature in Celcius? ")
print("Temperature: " + str(temperature) + " degrees Celcius")
if temperature < str(27):
print ("Plant is too cold")
if temperature < str(27):
sum = 27 - int(temperature)
print("Recommended temperature increase:" + str(sum) + " degrees Celcius")
print("Remember to keep your plant between 27 and 32 degrees!")
elif temperature > str(32):
print ("Plant is too warm")
if temperature > str(32):
sum = int(temperature) - 32
print("Recommended temperature decrease:" + str(sum) + " degrees Celcius")
print("Remember to keep your plant between 27 and 32 degrees!")
elif temperature > str(27) and temperature < str(32):
print ("Plant temperature is nominal")发布于 2021-06-25 00:49:20
这是比较字符串之间的区别:
>>> '9'>'27'
True和整数:
>>> 9>27
False比较不同的类型是错误的:
>>> '9'>27
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'要解决此问题,请将字符串转换为int:
>>> int('9')>int('27')
False发布于 2021-06-25 01:15:35
当你应该比较整数时,你却在比较字符串。Python自动接受字符串形式的输入,因此将其转换为整数,如下所示。
temperature = int(input("What is the temperature in Celcius? "))专业提示:在将输入转换为整数之前,最好先验证输入是否为数字,以避免错误。你在这里尝试过这样做:
temperature = range(-30,55)但是该语句没有将温度变量的参数设置为只允许-30到55之间的数字。相反,它只是使温度等于一个范围(-30,55),使用isdigit()方法和条件语句来验证是否只接收到正确的输入。为此,您将需要一个while循环,该循环要求具有特定条件的输入,直到接受输入为止。
while True:
temperature = input("What is the temperature in Celcius? ")
if temperature.isdigit():
temperature = int(temperature)
if temperature >= -30 and temperature <= 55:
break
else:
# temperature not in range
else:
# temperature is not a digit像这样比较整数。请注意,我在比较过程中没有使用str()方法,也没有重复的条件语句。我还使用了else语句,因为温度小于27和大于32已经涵盖了所有其他情况,因此唯一的其他选择是在27和32之间。
if temperature < 27:
print ("Plant is too cold")
sum = 27 - temperature
print("Recommended temperature increase:" + str(sum) + " degrees Celcius")
print("Remember to keep your plant between 27 and 32 degrees!")
elif temperature > 32:
print ("Plant is too warm")
sum = temperature - 32
print("Recommended temperature decrease:" + str(sum) + " degrees Celcius")
print("Remember to keep your plant between 27 and 32 degrees!")
else:
print ("Plant temperature is nominal")https://stackoverflow.com/questions/68119516
复制相似问题