所以,我在做一个小项目。我正在制作一个基于文本的温度计算器,但是我在程序中遇到了if语句的问题,正如这个问题的标题所示。你知道吗
这是我遇到问题的代码。你知道吗
running = True
fahr = "fahrenheit"
cel = "celsius"
kel = "kelvin"
temperatures = [fahr, cel, kel]
while running == True:
try:
temperature_type = str.lower(input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n"))
except ValueError:
print("I do not understand. Please try again.")
continue
if temperature_type == any(temperatures) and not all(temperatures):
break
else:
print("Please enter a valid input.")
continue
似乎我看不到的逻辑有问题,我尝试了多种组合,甚至是从this post建议的组合,但它们似乎都没有按我希望的方式工作。我希望它的工作方式是让可变温度类型仅等于一个温度,比如华氏度,然后问另一个问题(这里没有显示)。如果variable temperature类型不等于这三个类型中的任何一个,那么我想循环重复。我的问题是,无论我输入什么,它总是要求温度。如果有人有答案,我会很高兴知道我做错了什么,我也会喜欢逻辑的解释,因为我还不是这种逻辑的最好的。再次感谢您的回答和/或指导!你知道吗
或:
说明:
all
和any
返回True
或False
,因此不起作用,所以使用in
我删除了
running
,因为只需使用1
您也可以执行
True
,请参见:any
和all
返回True
或False
,而不是可以有意义地与str
进行比较的对象。所有非空的str
都是“truthy”,所以您要检查if temperature_type == True and not True
,这当然永远不会通过。你知道吗你想要的逻辑可能是:
在您的设计中,不可能有人输入多种温度类型,因此您不需要任何等价的
all
测试,您只需要知道输入的字符串是否与三个已知字符串中的一个匹配。你知道吗下面是一个简单的检查版本,它只检查输入字符串是否是有效的温度之一。它使用
in
操作符检查所提供的字符串是否在temperatures
中。你知道吗相关问题 更多 >
编程相关推荐