Maybe you could create like a helper function called something like get_int_input
that handles the vailidation:
from random import randint
MIN_NUM_GAMES = 3
MAX_NUM_GAMES = 11
CHOICES = ['rock', 'paper', 'scissors']
LOSER_TO_WINNER = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'}
def rock_paper_scissors():
user_choice = CHOICES[get_int_input('\nEnter 1 for rock, 2 for paper, or 3 for scissors: ', 1, 3) - 1]
computer_choice = CHOICES[randint(0, 2)]
if user_choice == computer_choice:
print(f'It is a draw, both you and the computer chose {user_choice}...')
return 0 # draw
elif LOSER_TO_WINNER[computer_choice] == user_choice:
print(f'You win! The computer threw {computer_choice} while you chose {user_choice}.')
return 1 # win
else:
print(f'You lose... The computer threw {computer_choice} while you chose {user_choice}.')
return -1 # loss
def get_int_input(prompt, min_num, max_num):
num = -1
while True:
try:
num = int(input(prompt))
if min_num <= num <= max_num:
break
print(f'Error: Integer outside of allowed range {min_num}-{max_num} inclusive, try again...')
except ValueError:
print('Error: Enter an integer, try again...')
return num
def main():
print('Welcome to my Rock, Paper, Scissors Game!\n')
num_games = get_int_input(f'Enter the number of games: ', MIN_NUM_GAMES, MAX_NUM_GAMES)
num_wins = num_losses = num_draws = 0
for _ in range(num_games):
game_outcome = rock_paper_scissors()
if game_outcome == 1:
num_wins += 1
elif game_outcome == -1:
num_losses += 1
else:
num_draws += 1
print(f'\nYou played {num_games} games, with {num_wins} win(s), {num_losses} loss(es), {num_draws} draw(s).')
print('Goodbye!')
if __name__ == '__main__':
main()
Example Usage:
Welcome to my Rock, Paper, Scissors Game!
Enter the number of games: 2
Error: Integer outside of allowed range 3-11 inclusive, try again...
Enter the number of games: 12
Error: Integer outside of allowed range 3-11 inclusive, try again...
Enter the number of games: 4
Enter 1 for rock, 2 for paper, or 3 for scissors: 3
You lose... The computer threw rock while you chose scissors.
Enter 1 for rock, 2 for paper, or 3 for scissors: 2
You win! The computer threw rock while you chose paper.
Enter 1 for rock, 2 for paper, or 3 for scissors: 1
It is a draw, both you and the computer chose rock...
Enter 1 for rock, 2 for paper, or 3 for scissors: 2
It is a draw, both you and the computer chose paper...
You played 4 games, with 1 win(s), 1 loss(es), 2 draw(s).
Goodbye!