Python 将字符串中的 9 识别为大于 27 "if <this then this"



我已经开始了两天的学习之旅,所以请放松!我正在尝试组装一个基本的温度应用程序,除了输入个位数外,一切都运行良好,没有错误。如果我输入两位数,它正确地注册正确的响应,如:";是的,太热了"或";是的,太冷了"但它似乎认识到任何低于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")

当您应该比较整数时,您正在比较字符串。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")

这是比较字符串之间的区别:

>>> '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

最新更新