Reputation: 95
Here's what I have at this point:
def checkPlayerCardInput(answer):
while True:
for x in range(len(player1Cards)):
if answer.lower() == player1Cards[x]:
return player1[x]
What I don't know is how to repeat the loop if the user misspells a word or enters something incorrect entirely?
In this scenario, player1Cards
is equal to a list of 5 strings. I'm simply trying to match the answer
(which is input previously by the user via raw_input
) to one of those strings and return
that answer (which, in this case, is the item from the player1
list that contains the rest of the data for the "card" returned).
If the answer is incorrect, I would like the loop to start with a fresh raw_input answer from the user.
Upvotes: 0
Views: 1240
Reputation: 13626
To check that an item is contained in a list use in
operator. Like this:
if answer.lower() in player1CArds:
#...
Use a while
loop to keep asking for raw_input
until you're given a string found in the list.
Upvotes: 4
Reputation: 39406
The else
keyword can be use in your case. Used in conjonction with for
, the else clause is executed when the range was exhausted without exiting the loop (break or return) :
for x in range(len(player1Cards)):
if answer.lower() == player1Cards[x]:
return player1[x]
else:
# Here, your user input matches nothing.
However, you can use the in
keyword of list
:
if answer.lower() in player1Cards:
# equivalent to your for loop
Or the opposite, not in
:
if answer.lower() not in player1Cards:
# Typo, or the user inputed a non-existing card
Upvotes: 0
Reputation: 14873
Does this do what you want?
def checkPlayerCardInput(answer):
while True:
for x in range(len(player1Cards)):
if answer.lower() == player1Cards[x]:
return player1[x]
answer = raw_input('incorrect answer!')
Upvotes: 0