gpt4 book ai didi

python - 代码的行为不像是在满足条件时? [ python 3]

转载 作者:太空宇宙 更新时间:2023-11-04 10:27:54 25 4
gpt4 key购买 nike

所以我有以下功能:

def ask_question():
"""Asking a question which requires a yes or no response"""
response=input()
while response.lower()!="yes" or response.lower()!="no":
print("Invalid response! Answer must be 'Yes' or 'No'.")
response=input()
return response

然而,当我执行函数 ask_question() 并输入"is"或“否”时,它会得到响应“无效响应!答案必须是‘是’或‘否’。”

我这辈子都想不通为什么,我已经盯着它看了一段时间了。有人可以帮帮我吗?

最佳答案

您需要在循环中使用。但为什么?

根据 De Morgan's law , 你的情况

response.lower()!="yes" or response.lower()!="no":

等效于:(not A) or (not B)not (A and B) 相同 - 这不是您想要的(即not (Yes and No) 不会给你你想要的)。

因此,将您的查询更改为使用 将更改为:

response.lower()!="yes" and response.lower()!="no":

等同于 (not A) and (not B) 这与 not (A or B) 相同,这就是您想要的。换句话说:

if input is "not (Yes or No)", print invalid reponse msg

关于python - 代码的行为不像是在满足条件时? [ python 3],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28412502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com