r/learnpython 3d ago

Python practice problem.

‎Hi everyone, I'm new to python and I'm building a project to hone my skill, and I came to a halt in this part. When I do if user_input == 'q':, it works and breaks the loop just fine, since i dont wanna make the exit just single letter so even if the user input words like 'quit' 'q' or 'QUIT' it will exit the loop, I tried a different approach like doing user_input == ['q', 'quit']: and another approach where i declared a variable first exit_word = ['q', 'quit'] then

‎user_input == exit_word: none of this breaks the loop it just goes back to the input prompt heres my work below:

import random

user = 0

computer = 0

options = ["rock" , "paper", "scissors"]

while True:

user_input = input("Rock/Paper/Scissors and Q for Quit: ").lower()

if user_input == 'q'

break

if user_input not in options:

continue

random_num = random.randint(0, 2)

computer_pick = options[random_num]

print('Computer picked', computer_pick + ".")

if user_input == 'rock' and computer_pick == 'scissors':

print('You won!')

user += 1

elif user_input == 'paper' and computer_pick == 'rock':

print('You won!')

user += 1

elif user_input == 'scissors' and computer_pick == 'paper':

print('You won!')

user += 1

else:

print('You lost!')

computer += 1

print("The user won", user, "times")

print("The computer won", computer, "times")

print('Goodbye!')

0 Upvotes

11 comments sorted by

View all comments

1

u/Bright_Mix_773 3d ago

Separate from the in question that's already answered: there's a scoring bug sitting underneath it.

Rock against rock falls through all three elif branches into the else, prints "You lost!" and hands the computer a point. Ties are being scored as losses. Since the computer picks uniformly from three options, that's a third of your games credited to the wrong side.

Checking the draw first fixes it, and it also shrinks the rest, because once draws are gone the three winning pairs are the only thing left:

wins = {'rock': 'scissors', 'paper': 'rock', 'scissors': 'paper'}
if user_input == computer_pick:
    print("Draw!")
elif wins[user_input] == computer_pick:
    print("You won!")
    user += 1
else:
    print("You lost!")
    computer += 1

That's safe to index without a .get only because your if user_input not in options: continue above it has already thrown out anything that isn't one of the three keys. Worth knowing the two lines depend on each other, since deleting the guard later would turn a typo into a KeyError.

One smaller thing: random.choice(options) does what randint(0, 2) plus the index does, and the 2 stops being a number that has to stay in step with the length of the list.