Есть несколько проблем с кодом в его нынешнем виде:
- Неверные операторы равенства.
Я бы также предложил не использовать =
с обоими операторы <
и >
просто для лучшей согласованности. Тем более, когда есть отдельная проверка регистра специально для ==
.
Проблема сравнения температуры в виде строки состоит в том, что значения сравниваются лексикографически. Несколько примеров для объяснения проблемы:
"14" is less than "67"
Это верно, но проблема связана с разной длиной строки температуры
"3" is more than "26" lexicographically
-> Погода жаркая
"100" is less than "26" lexicographically
-> Холодный день
Лучше убедиться, что мы конвертируем температуру и сравниваем их как целые числа.
Алфавиты, отличные от числа, не обрабатываются. Я использую
isdecimal()
, чтобы проверить это. (
подробности см. В этом ответе )
temperature = input("What is the temperature? ")
if not temperature.isdecimal():
print("Temperature entered '{}' is not an int!".format(temperature))
else:
temperature = int(temperature)
if temperature == 26:
print("The weather is average")
elif temperature > 26:
print("The weather is hot")
elif temperature <= 26:
print("It's a cold day")
else:
print("Invalid")
Результат
What is the temperature? 17
It's a cold day
What is the temperature? 26
The weather is average
What is the temperature? 3
It's a cold day
What is the temperature? 100
The weather is hot
What is the temperature? dsf86
Temperature entered 'dsf86' is not an int!
What is the temperature? 34.23
Temperature entered '34.23' is not an int!