3

For a practice problem in my homework, i'm making a guessing game that starts off by asking for a number. I'm trying to implement a way that prints "invalid input" when given a string, but i get an error message. here is my code:

def get_input():
    '''
    Continually prompt the user for a number, 1,2 or 3 until
    the user provides a good input. You will need a type conversion.
    :return: The users chosen number as an integer
    '''
    guess=int(input("give me 1,2,3"))
    while True:
        if guess==1 or guess==2 or guess==3:
            return guess
        else:
            print "Invalid input!"

        guess=int(input("give me 1,2,3"))

I get this message when I put in a string such as

hello/System/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 /Users/bob/PycharmProjects/untitled/warmup/__init__.py

give me 1,2,3hello

Traceback (most recent call last):
  File "/Users/bob/PycharmProjects/untitled/warmup/__init__.py", line 51, in <module>
    get_input()
  File "/Users/bob/PycharmProjects/untitled/warmup/__init__.py", line 43, in get_input
    guess=int(input("give me 1,2,3"))
  File "<string>", line 1, in <module>
NameError: name 'hello' is not defined

Process finished with exit code 1
Mazdak
  • 105,000
  • 18
  • 159
  • 188
magersaber
  • 25
  • 2
  • 3

2 Answers2

5

You need to use raw_input for python2, input tries to evaluate the string so it looks for a variable called name and errors as there is no variable called name defined anywhere. You should never use input in python2, it is equivalent to eval(raw_input()) which has obvious security risks.

So to spell it out more clearly, don't use input to take input from a user in python2, use raw_input() and in your case take the raw_input using a try/except catching a ValueError.

def get_input():
    '''
    Continually prompt the user for a number, 1,2 or 3 until
    the user provides a good input. You will need a type conversion.
    :return: The users chosen number as an integer
    '''

    while True:
        try:
            guess = int(raw_input("give me 1,2,3"))
            if guess in (1, 2, 3):
                return guess
        except ValueError:
            pass
        print("Invalid input!")

The fact you are just cheking for 1,2 or 3 means you could also just do the casting after you confirm:

def get_input():
    '''
    Continually prompt the user for a number, 1,2 or 3 until
    the user provides a good input. You will need a type conversion.
    :return: The users chosen number as an integer
    '''

    while True:
        guess = raw_input("give me 1,2,3")
        if guess in ("1", "2", "3"):
            return int(guess)
        print("Invalid input!")
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
1

You should to verify the input type before converting into a int:

guess = raw_input("give me 1,2,3")

while True:
   if guess == '1' or guess == '2' or guess == '3':
      return int(guess)
   else:
      print "Invalid input!"

   guess = raw_input("give me 1,2,3")
gre_gor
  • 6,669
  • 9
  • 47
  • 52
Shapi
  • 5,493
  • 4
  • 28
  • 39
  • `raw_input` always returns a string, `gess` doesn't exist and `else: pass` is completely useless. – gre_gor Oct 03 '15 at 18:55
  • @gre_gor you're right, i was a bit distracted. i assume my mistake here, sorry. – Shapi Oct 03 '15 at 18:59
  • Now you are using `is` to test for equality, not a good idea! Also `else:pass` is redundant. – Padraic Cunningham Oct 03 '15 at 19:04
  • should i use `==` instead `is`? – Shapi Oct 03 '15 at 19:06
  • 1
    yep. `is` would work at least using cpython but it is an implementation detail that should never be relied upon. `is` should be used for identity, `==` to test if two values are equal not necessarily the same object in memory – Padraic Cunningham Oct 03 '15 at 19:12
  • You still have a typo. And what is `get_input` doing here exactly? – gre_gor Oct 03 '15 at 19:13
  • 1
    @gre_gor is a suggestion to pass the input to function `arg`. Thx Padraic. – Shapi Oct 03 '15 at 19:15
  • Your code is supposed to be inside that function and that function doesn't expect any arguments. – gre_gor Oct 03 '15 at 19:19
  • You still have a typo and he wants the input returned not just printed. – gre_gor Oct 03 '15 at 19:42
  • @gre_gor i've noticed but dont makes sence, if you use a `return` in a function it will be used after, and you expect a int in this case, if not he return nothing. that dont makes sence to me but i edited it – Shapi Oct 03 '15 at 19:46
  • This function never returns nothing since it's in an infinite loop and keeps asking for input. The only way to break from the loop, is to provide a valid input. – gre_gor Oct 03 '15 at 20:03
  • @ok thats a good observation, i didnt look in that way, but if the intended is the return it should be a return then :) – Shapi Oct 03 '15 at 20:06