Skip to content

Conversation

@abdouZent
Copy link

No description provided.

Copy link

@OkeyChukwude OkeyChukwude left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @abdouZent ,

I spotted a SyntaxError in your proposed change. You omitted the !=operator when comparing user and 's'.

More over if the operator wasn't omitted, there would be another SyntaxError because the continue statement can only be used within loops.

A possible way to achieve what you intended (i.e prompting the user to input either 'r' or 'p' or 's' whenever the input from the user is not either of the three letters) is to have a recursive function that request for the input, checks if the right input is provided by the user and calls itself whenever the input is not one of the required inputs.

The code snippet below shows a possible implementation of your proposed change:

import random

def play():
    user = get_user_input()
    computer = random.choice(['r', 'p', 's'])

    if user == computer:
        return 'It\'s a tie'

    # r > s, s > p, p > r
    if is_win(user, computer):
        return 'You won!'

    return 'You lost!'

def get_user_input():
    # gets user inputs and check if it's appropriate
    # recalls itself until an appropriate input is entered
    user_input = input("What's your choice? 'r' for rock, 'p' for paper, 's' for scissors\n")
    if (user_input != 'r' and user_input != 'p' and user_input != 's'):
        print("please choose either r, p or s! ")
        user_input = get_user_input()
    return user_input

def is_win(player, opponent):
    # return true if player wins
    # r > s, s > p, p > r
    if (player == 'r' and opponent == 's') or (player == 's' and opponent == 'p') \
        or (player == 'p' and opponent == 'r'):
        return True

print(play())

Also in the is_win function, I think @kying18 implementation is really readable and straight to the point and there is practically no need changing it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants