如何让if语句接受三个参数中的任何一个,而在Python中所有参数都不是真的

2024-10-02 12:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,我在做一个小项目。我正在制作一个基于文本的温度计算器,但是我在程序中遇到了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类型不等于这三个类型中的任何一个,那么我想循环重复。我的问题是,无论我输入什么,它总是要求温度。如果有人有答案,我会很高兴知道我做错了什么,我也会喜欢逻辑的解释,因为我还不是这种逻辑的最好的。再次感谢您的回答和/或指导!你知道吗


Tags: true类型inputiftype逻辑温度running
3条回答

或:

while 1:
    if input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n").lower() in temperatures:
        break
    print("Please enter a valid input.")

说明:

allany返回TrueFalse,因此不起作用,所以使用in

我删除了running,因为只需使用1

您也可以执行True,请参见:

>>> 1==True
True

anyall返回TrueFalse,而不是可以有意义地与str进行比较的对象。所有非空的str都是“truthy”,所以您要检查if temperature_type == True and not True,这当然永远不会通过。你知道吗

你想要的逻辑可能是:

if temperature_type in temperatures:

在您的设计中,不可能有人输入多种温度类型,因此您不需要任何等价的all测试,您只需要知道输入的字符串是否与三个已知字符串中的一个匹配。你知道吗

下面是一个简单的检查版本,它只检查输入字符串是否是有效的温度之一。它使用in操作符检查所提供的字符串是否在temperatures中。你知道吗

running = True
fahr = "fahrenheit"
cel = "celsius"
kel = "kelvin"
temperatures = [fahr, cel, kel]

while running:
    temperature_type = str.lower(input("What is the current temperature unit you are using? \nFahrenheit, Celsius, or Kelvin?\n"))
    if temperature_type in temperatures:
        break
    print("Please enter a valid input.")

相关问题 更多 >

    热门问题