Reputation: 11
Apologies for basic nature of this query - this is almost my first Python script.
I want the user to enter a two character string corresponding to a playing card (eg 2c, 3s) and for the program to check two things: first, whether it's in the list of valid cards, and second, whether that card has already been entered. If either condition is failed, I want the user to be prompted to re-enter the card. What I have written does each of those things, but it doesn't do them simultaneously - eg, if the card is invalid, the user is prompted, but if the re-entered card is already on the list, no prompt occurs. I can't see how to get both things tested at once.
Anyway, here is what I have:
posscards=["ac",
"2c",
"3c",
"4c",
"5c" #and so on]
for x in range(0, decksize):
answer=raw_input("next card? ")
while answer not in posscards:
answer = raw_input("not a possible card - try again: ")
while answer in deck1:
answer = raw_input ("you've already had that one - try again: ")
deck1.append(answer)
Upvotes: 0
Views: 160
Reputation: 366003
Instead of two while
loops, you can use a single while
loop with two if
conditions. For example:
prompt = "next card? "
while True:
answer = raw_input(prompt)
if answer not in posscards:
prompt = "not a possible card - try again: "
elif answer in deck1:
prompt = "you've already had that one - try again: "
else:
deck1.append(answer)
break
It might be a little more readable if you factored it out into a function:
def get_card():
while True:
answer = raw_input(prompt)
if answer not in posscards:
prompt = "not a possible card - try again: "
elif answer in deck1:
prompt = "you've already had that one - try again: "
else:
return answer
Now, every time you call get_card
, it's guaranteed to (eventually) return an answer. So, your main loop can look like this:
deck1 = []
for x in range(decksize):
answer = get_card()
deck1.append(answer)
And you can turn that into a one-liner:
deck1 = [get_card() for x in range(deck size)]
Upvotes: 3
Reputation: 8685
by the way I don' see deck1 anywhere. make sure you declare before you try to append things to it.
deck1 = []
while answer not in posscards and answer in deck1:
answer = raw_input("not a possible card or card already entered- try again: ")
Upvotes: 0