The function below is supposed to ask the user to enter a choice of rock paper or sciessors and output an error mesage if the user enters an invalid choice and then ouput a message if they won, drew or lost against the computer.

def rockPaperScissors():
    import random
    choice=raw_input("please enter your choice: ")
    computerIndex = random.randint(1,3)
    if computerIndex == 1:
        computer = "rock"
    elif computerIndex == 2:
        computer = "scissors"
    else:
        computer = "paper"

Recommended Answers

All 11 Replies

This must do the trick with the win, lose & draw. I gave it a play again option.

Unfortunately I don't know how to solve the 'invalid choice' thing if the user enters a String. I'd like to know that too.

def rockPaperScissors():
    import random
    choice=int(raw_input("please enter your choice(1 = rock, 2 = scissors, 3 = paper): "))
    if choice == 1:
        choice = 'rock'
    elif choice == 2:
        choice = 'scissors'
    elif choice == 3:
        choice = 'paper'
    else:
        print 'Not an option! Choose again!'
        rockPaperScissors()
        
    computerIndex = random.randint(1,3)
    if computerIndex == 1:
        computer = 'rock'
    elif computerIndex == 2:
        computer = 'scissors'
    elif computerIndex == 3:
        computer = 'paper'

    if (choice == computer):
        print choice, ' vs ', computer, ' -> Draw!'

    if choice == 'rock':
        if computer == 'scissors':
            print choice, ' vs ', computer, ' -> Player wins!'
        elif computer == 'paper':
            print choice, ' vs ', computer, ' -> Computer wins!'

    if choice == 'scissors':
        if computer == 'paper':
            print choice, ' vs ', computer, ' -> Player wins!'
        elif computer == 'rock':
            print choice, ' vs ', computer, ' -> Computer wins!'

    if choice == 'paper':
        if computer == 'rock':
            print choice, ' vs ', computer, ' -> Player wins!'
        elif computer == 'scissors':
            print choice, ' vs ', computer, ' -> Computer wins!'

def play_again():
    again = True
    while again == True:
        pagain = int(raw_input('Play Again? (1 = Y/ 0 = N): '))
        if pagain == 1:
            rockPaperScissors()
        elif pagain == 0:
            print 'Good Bye!'
            again = False
        else:
            play_again()

rockPaperScissors()
play_again()

Greetz

commented: very helpful!! +1

Here's a technique commonly used to sanitize input:

keep_going = True
while keep_going:
    choice=int(raw_input("please enter your choice(1 = rock, 2 = scissors, 3 = paper): "))
    if choice == 1:
        choice = 'rock'
        keep_going = False
    elif choice == 2:
        choice = 'scissors'
        keep_going = False
    elif choice == 3:
        choice = 'paper'
        keep_going = False
    else:
        print 'Not an option! Choose again!'

I could have written it a little better, but I think you get the idea. Good Luck.

import random

def rockPaperScissors():
    #choice = raw_input("please enter your choice: ")  #I take away this to make a point
    computerIndex = random.randint(0,2)  
    if computerIndex == 1:
        computer = "rock"
        print computer  #test print
    elif computerIndex == 2:
        computer = "scissors"
        print computer  #test print
    else:
        computer = "paper"
        print computer  #test print
        
rockPaperScissors()

Think of what your function should do,now user input has no function.

for the error mesage.... i have tried making this code?.. is this right? coz i get an error when i try to use it..

import random
    choices = set("""1 = rock, 2 = scissors, 3 = paper""".strip().split())
    while True:
        choice=int(raw_input("please enter your choice(1 = rock, 2 = scissors, 3 = paper): ")).strip()
    if choice in choices:
        return choice
    else:
          print("Invalid colour '{0}'.".format(choice))
          print("Possible values are {0}".format(tuple(choices)))

this is my current error

choice=int(raw_input("please enter your choice(1 = rock, 2 = scissors, 3 = paper): ")).strip()
ValueError: invalid literal for int() with base 10: 'g'

Yes you use python 3.x i see(when you post make a note that you use python 3.x)
Python 3 has no raw_input only input.

return choice you can not use return if you dont make a function.

So this is how it should bee.

import random

choices = set("""1 = rock, 2 = scissors, 3 = paper""".strip().split())
while True:
    choice = input("please enter your choice(1 = rock, 2 = scissors, 3 = paper): ").strip()
    if choice in choices:
        print(choice)          #test print
        print (type(choice))   #se what input returns,you can make it a integer later if you need that
        break                  #and break out of the while loop
    else:
        print("Invalid colour '{0}'.".format(choice))
        print("Possible values are {0}".format(tuple(choices)))

Yes you use python 3.x i see(when you post make a note that you use python 3.x)
Python 3 has no raw_input only input.

return choice you can not use return if you dont make a function.

So this is how it should bee.

import random

choices = set("""1 = rock, 2 = scissors, 3 = paper""".strip().split())
while True:
    choice = input("please enter your choice(1 = rock, 2 = scissors, 3 = paper): ").strip()
    if choice in choices:
        print(choice)          #test print
        print (type(choice))   #se what input returns,you can make it a integer later if you need that
        break                  #and break out of the while loop
    else:
        print("Invalid colour '{0}'.".format(choice))
        print("Possible values are {0}".format(tuple(choices)))

end quote.

I still get error when a user enters a string as a choice?.. is this because i need to create another function to return the value?

 choice = input("please enter your choice(1 = rock, 2 = scissors, 3 = paper): ").strip()
  File "<string>", line 1, in <module>
NameError: name 'k' is not defined

Ok make it simpler.

import random

choices = ['rock', 'paper', 'scissors']
while True:
    choice = input("please enter your choice(rock-scissors-paper): ")
    if choice in choices:
        print(choice)          #test print
        print (type(choice))   #se what input returns,you can make it a integer later if you need that
        break                  #and break out of the while loop
    else:
        print("Invalid colour '{0}'.".format(choice))
        print("Possible values are {0}".format(tuple(choices)))


comp = random.choice(choices)  #comp
human = random.choice(choices) #human

print ("Comp: %s\nHuman: %s" % (comp, human)) #test print

#now figuere out how to define winner

Tips you can use index.

>>> choices = ['rock', 'paper', 'scissors']
>>> choices.index('rock')
0
>>> choices.index('paper')
1
>>> human_rand = choices.index(human)
>>> human_rand
2
>>>

Ahh when user input is should be like this off course.

comp = random.choice(choices)  #comp
human = choice                 #human

thx for the help you have given but i am quite lost now, I just need help with how i could give an error message to the user if they enter a string instead of a integer...

I just need help with how i could give an error message to the user if they enter a string instead of a integer...

You can use a dictionary like this.
Now user can only input 123 to get past meny, anything else give error message and loop back.
Yes more easy for user to just type a number than write rock,paper........everytime.

import random

choices = {'1': 'rock', '2': 'paper', '3': 'scissors'}
choice_comp = ['rock', 'paper', 'scissors']

while True:
    choice = input("please enter your choice | 1:rock 2:paper 3:scissor")
    if choice in choices:
        print (choices[choice])  #test print
        print (type(choice))     #se what input returns,you can make it a integer later if you need that
        break                    #and break out of the while loop
    else:
        print("Invalid choice '{0}'.".format(choice))
        print('Possible values are 1-2-3')


comp = random.choice(choice_comp)  #comp
human = choices[choice]            #human

print ("Comp: %s\nHuman: %s" % (comp, human)) #test print

#now figuere out how to define winner

You can also use a try-exception

def input_user():
    try:
        x = int(raw_input('Type a number: '))
    except ValueError: #or whatever error it is 
        print 'Wrong Input! Try again!'
        input_user():

Greetz

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.