Issue
Edit: This is what I am trying to do: I am asking the user to enter a month. then the code will lookup if the month is correct by checking every item in months_list. If not found I want him/her to enter the month again..
Here's the code:
months_list=["January", "February", "March", "April", "May", "June", "July"]
answer=raw_input("Month? \n")
while any(item.lower() != answer.lower() for item in months_list):
print("Sorry, didn't recognize your answer, try again")
answer=raw_input("Type in Month\n")
However this keeps looping regardless if the month is found in the list or not.. I hope this is a good clarifaction.. thank you all in advance
Solution
The problem is that any()
returns True
if any one of the elements in the iterable is True
, so your code keeps looping as long as the answer isn't equal to all the strings in months_list
—which is probably the opposite of what you want to happen. Here's a way to use it that stops or breaks-out of the loop if the answer matches any of the strings:
months_list = ["January", "February", "March", "April", "May", "June", "July"]
while True:
answer = raw_input("Month? ")
if any(item.lower() == answer.lower() for item in months_list):
break
print("Sorry, didn't recognize your answer, try again")
As others have pointed out, while it would simpler to use Python's in
operator, that way still results in a linear search, O(n), being performed…so an even better (faster) approach would be to use a set
of lower-cased month_names
, which would utilize a hash table based look-up, O(1), instead of a linear search:
months = set(month.lower() for month in ("January", "February", "March", "April",
"May", "June", "July"))
while True:
answer = raw_input("Month? ")
if answer.lower() in months:
break
print("Sorry, didn't recognize your answer, try again")
Further refinement
Depending on the nature of strings involved and why you're comparing them, it might be better to use the string casefold()
method instead of lower()
to do caseless string comparisons.
Answered By - martineau
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.