I am trying to make sure a user only chooses an option between 0 and 2. If they don’t choose that, I want them to be able to try again. Nothing seems to be an infinite loop, but the program will never end.
The function I am trying to do this with is:
def make_user_choice():
while True:
try:
choice = int(input("Choose one: rock, paper, scissors? "))
except ValueError:
print("Enter a number.")
continue
if choice not in[0, 1, 2]:
print("Enter a number between 0 and 2")
continue
else:
if choice == 0:
return "rock"
elif choice == 1:
return "paper"
elif choice == 2:
return "scissors"
In the main class:
import round
user_score = 0
computer_score = 0
while user_score < 2 and computer_score < 2:
user_choice = round.make_user_choice()
computer_choice = round.make_computer_choice()
print(user_choice + " (you) vs. " + computer_choice)
if user_choice == computer_choice:
print("It's a tie!")
continue
if round.wins_matchup(user_choice, computer_choice):
print("You win!")
user_score = user_score + 1
else:
print("Computer wins!")
computer_score = computer_score + 1
print(round.format_score(user_score, computer_score))
but I don’t think the main class is the issue. It doesn’t seem like this program should keep running. The program doesn’t take more input after there is a winner, but the program still shows as running. The more I look at it, the more I think it is the editor I am using having some sort of bug. It is an editor in KhanAcademy Unit 4, Lesson 3 of intro to CS: Python
7
This is the simplified code. (Changed ‘rock’ into ‘stone’ as one of the known logic: paper wins between paper & stone as the paper covers the stone. I don’t know whether rock wins here. So change your code according to your requirement)
If you want to decide the winner out of say 10 rounds, Create a for loop
or while loop
for range(10).
import random
# Create a 2d list in such a way the 2nd element of each pair the winner
val_lst = [['stone','paper'],['paper','scissors'],['scissors','stone']]
# list of options
lst = ['stone', 'paper', 'scissors']
try:
user_choice = int(input("Choose one: stone, paper, scissors?n"))
except ValueError:
print('Enter a number')
# terminate the program in case of value error
exit()
# if user's number input is the index of lst, then value is the user's choice
user_choice = lst[user_choice]
# computer to select a random option
comp_choice = random.choice(lst)
# declare variables user and comp
user, comp = 0, 0
# Iterate thru val list
for x in val_lst:
# If user_choice & comp_choice pair in sublist, then the second element is winner
if user_choice in x and comp_choice in x:
if user_choice == x[1]:
user = user + 1
else:
comp = comp + 1
print(f'user_choice : {user_choice}')
print(f'comp_choice : {comp_choice}')
won = 'user' if user > comp else 'comp' if comp > user else 'tie'
print(f'result : {won}')
1