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

标签 python python-3.x if-statement

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

最佳答案

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

你想要的逻辑可能是:

if temperature_type in temperatures:

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

关于python - 如何让 if 语句接受三个参数中的任何一个而不在 Python 中全部为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51923309/

相关文章:

python : Overriding a method from a third-party module (Tkinter)?

python - GridLayout 中的小部件相互重叠

具有字典属性的 Python 对象在每次循环迭代中附加,而不是被垃圾收集

javascript - 数据表内的条件

r - 如何在R Studio中的for循环中包含计数过程?

python - 在假设函数中执行数据库查询时列出超出范围的索引

python - 将指针从 python var 传递到 c lib

Python 的字符串格式在 mysql 中应用时会引发错误

java - 简化单元测试的多个 if-else 语句

python - 使用 pip freeze > requirements.txt 将复制特定于该目录的库?