Skip to main content
 首页 » 编程设计

python之如何让 if 语句接受三个参数中的任何一个而不在 Python 中全部为真

2025年05月04日18hnrainll

所以,我正在做一个小项目。我正在制作一个基于文本的温度计算器,但是我在程序中遇到了 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 中建议的组合而且它们似乎都没有按照我想要的方式工作。我希望它工作的方式是让变量 temperature_type 只等于华氏温度之一,然后问另一个问题(此处未显示)。如果变量 temperature_type 不等于这三个中的任何一个,那么我想循环重复。我遇到的问题是,无论我输入什么,它总是询问温度。如果有人有答案,我会很高兴知道我做错了什么,我也很喜欢对逻辑的解释,因为我还不是最擅长这种逻辑的人。再次感谢您的回答和/或指导!

请您参考如下方法:

any和 all返回 True或 False ,而不是可以与 str 进行有意义比较的对象.全部非空str是“真实的”,所以你正在检查 if temperature_type == True and not True , 这当然永远不会过去。

你想要的逻辑可能是:

if temperature_type in temperatures: 

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