So I have the following function:
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
Yet when I execute the function ask_question() and type "yes" or "no", it comes up with the response "Invalid response! Answer must be 'Yes' or 'No'."
I can't figure out for the life of me why and i've been staring at it for a while now. Can someone help me out?
You need to use and
in your loop. But why?
According to De Morgan's law , your condition
response.lower()!="yes" or response.lower()!="no":
Is equivalent to: (not A) or (not B)
which is the same as not (A and B)
- which is not what you want (ie not (Yes and No)
does not give you what you want).
Therefore changing your query to use the and
would change to this:
response.lower()!="yes" and response.lower()!="no":
which is equivalent to (not A) and (not B)
which is the same as not (A or B)
which is what you want. In other words:
if input is "not (Yes or No)", print invalid reponse msg
Your code checks prints the message if the input in lower case is not "yes"
, or the input in lower case is not "no"
, which is True
pretty much for all possible inputs the user can give. Of course you could do if response.lower() != "yes" and response.lower() != "no":
but it would not be very pythonic.
Instead you'd probably want to do the following with the in
operator:
def ask_question():
"""Asking a question which requires a yes or no response"""
while True:
response = input("Please answer 'yes' or 'no'> ").lower()
if response not in ('yes', 'no'):
print("Invalid response! Answer must be 'yes' or 'no'.")
else:
return response
This code also ensures that the the user has answered correctly the second time when prompted.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.