【问题标题】:How to make a while loop with 2 conditions?如何制作具有 2 个条件的 while 循环?
【发布时间】:2022-11-02 19:21:09
【问题描述】:

我想检查变量“类型”是否等于“视频”、“音频”或带有 while 循环的错误类型,但它不适用于 2 个条件。当我只输入 'while type != "video":' 它工作得很好,但是当我添加 'or type!= "audio":' 它停止工作你能帮我解决它吗?

type = input("Do you want a video or an audio? (answer by video or audio) \n >> ")
while type != "video" or type!= "audio":
    print('Error! select an existing type')
    type = input("Do you want a video or an audio? (answer by video or audio) \n >> ")
if type == "video":
    video_dwld()
elif type == "audio":
    audio_dwld()

【问题讨论】:

  • 作为程序员,您需要了解De Morgan''s laws
  • 你的意思是:while type != "video" and type!= "audio":
  • 通常的英语语法并不总是适用于编程语言。我们无法区分英语中的“或”和“异或”,但这就是你想要的。 (德语也一样)因为我们也没有xor 关键字,所以我们最终使用andnot
  • 更好的是:while type not in {"video", "audio"}:。但是你真的不应该将你的变量命名为type,因为你现在覆盖了内置的type

标签: python while-loop


【解决方案1】:

正如@quamrana 评论的那样,您似乎在循环,而type 不等于支持的值之一。

这是总是不等于支持的值之一,因为它最多等于其中一个。

提示:使用 Python 的强大功能:

supported_types = ("audio", "video")
while media_type not in supported_types:
    media_type = input(...)

另一个提示:请求宽恕比请求许可更容易:使用dict 来构造处理程序,并使用try/except 来处理错误。


handlers = {
    "audio": audio_dwld,
    "video": video_dwld
}


while True:
    try:
        media_type = input(...)
        handle = handlers[media_type]
        handle()
    except KeyError:
        print("a useful error message") 
    else:
        break

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2017-05-03
    • 1970-01-01
    • 2019-10-10
    • 2022-11-04
    • 2013-09-29
    • 2013-08-07
    相关资源
    最近更新 更多