I would like to check for valid input when the user inputs a choice between 'r', 'p', 's' How would I go about doing this? And where in my code do I put it?
I've already tried adding this in the beginning and it didn't work:
possible_choices = ["r", "p", "s"]
def play():
user = input(
"What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: "
).lower
computer = random.choice(["r", "p", "s"])
if user not in possible_choices:
print('Uh oh! Please select a valid option', play())
entire code:
import random
game_loop = True
def play():
user = input(
"What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: "
).lower
computer = random.choice(["r", "p", "s"])
if user == computer:
return f"Tie! Computer chose {computer}"
# r > s, s > p, p > r
if win_or_lose(user, computer):
return f"You won! Computer chose {computer}"
return f"You lost! Computer chose {computer}"
def win_or_lose(player, opponent):
if (
(player == "r" and opponent == "s")
or (player == "s" and opponent == "p")
or (player == "p" and opponent == "r")
):
return True
def play_again():
p_a = input("Play again? (y/n): ")
if p_a == "y":
print(play())
elif p_a == "n":
quit()
else:
print("oof! Please choose correct option: (y/n)")
play_again()
print(play())
while game_loop == True:
play_again()
I recommend a while loop, implemented like this:
def play():
choices = ['r','p','s']
while True:
user = input(
"What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: "
).lower()
if user in choices:
break
else:
print('choose again')
continue
...
This structure checks if the input is in the list of choices, and if it is not the user tries again. Also the parenthesis on the.lower() were added.
Some more information on this type of thing can be found here
Answer:
def play():
choices = ["r", "p", "s"]
computer = random.choice(["r", "p", "s"])
while True:
user = input(
"What's your choice? 'r' for rock, 'p' for paper, 's' for scissors: "
)
if user in choices:
break
else:
print("Please choose a correct choice.")
continue
if user == computer:
return f"Tie! Computer chose {computer}"
# r > s, s > p, p > r
if win_or_lose(user, computer):
return f"You won! Computer chose {computer}"
return f"You lost! Computer chose {computer}"
def win_or_lose(player, opponent):
if (
(player == "r" and opponent == "s")
or (player == "s" and opponent == "p")
or (player == "p" and opponent == "r")
):
return True
def play_again():
while True:
p_a = input("Play again? (y/n): ")
if p_a == "y":
print(play())
elif p_a == "n":
quit()
else:
print("Please choose correct option..")
play_again()
print(play())
while True:
play_again()
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.