1

I'm building a rock,paper and scissor simulator where you can play with the AI.

print('1.Rock 2.Scissors 3.Paper')
choice = int(input('Input your choice:\n')) 

One part of the code asks the user to input what he wants to show. If the player wants to play rock,paper,scissor. So for example if someone wants to use rock he would input 1. I would like to don't let the user input any other number or letter, or if he inputs to show an error and ask again the question.

What should I use? I'm thinking about using if, but I think that there exists a better way.

frfahim
  • 515
  • 9
  • 21
prossellob
  • 779
  • 7
  • 13
  • 1
    Using `if` is an excellent way to address your need. – DYZ Mar 05 '17 at 21:18
  • And how can I stop the user from using Ctrl + letter? If they press Ctrl + letter the program will crash. – prossellob Mar 05 '17 at 21:19
  • You must validate the input before calling `int()`. Read about exception handling. – DYZ Mar 05 '17 at 21:20
  • Look up try and except. – Pike D. Mar 05 '17 at 21:21
  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – wwii Mar 05 '17 at 22:04

2 Answers2

1

Here's one way:

while True:
    try:
        selection = int(input("Input your choice:\n"))
        if selection < 1 or selection > 3: #Valid number but outside range, don't let through
            raise ValueError
        else: #Valid number within range, quit loop and the variable selection contains the input.
            break
    except ValueError: #Invalid input
        print("Enter a number from 1 to 3.")
anonymoose
  • 819
  • 2
  • 11
  • 25
  • I don't understand very well what does "raise ValueError" It calls the except? Sorry, I'm a beginner. – prossellob Mar 05 '17 at 21:25
  • Yes, "raise ValueError" effectively makes the code go to the except statement. If you want a more complete definition, check the [python documentation on raising exceptions](https://docs.python.org/3/tutorial/errors.html#raising-exceptions). – anonymoose Mar 05 '17 at 21:27
  • Thanks :) I'll take a look at it :) – prossellob Mar 05 '17 at 21:30
0

Using an if is not a problem.

It would look like this:

if not (1 <= choice <= 3):
    raise ValueError()

You can also use a regular expression to check the input.