5

I'm writing a script that needs some very simple input from the user, and upon doing my research on this I am in a dilemma trying to work out the safest way to do it.

I only want an integer and stumbled across (what I thought was) a nice piece of code similar to (doing this from memory):

def getNumeric(prompt):
  while True:
    response = input(prompt)
    try:
      return int(response)
    except ValueError:
      print "please enter a number:",

This mostly worked, but if the user just pressed [enter] then it crashed. Turns out, I'm using python < 3, and the author wrote this for 3+. So now I have to rewrite for 2.7 to suit my needs. But how do I write it to cater for EITHER platform <3 and 3+?

I am writing something that could be used by others and want to make it the most portable I can. Should I bother?

As an aside, I am doing this for the Raspberry Pi, should I upgrade my python to 3, or leave it where it is (2.7.3)?

1
  • try changing 'input(prompt)' to 'raw_input(prompt)'. Commented Jul 20, 2013 at 10:58

2 Answers 2

6

My suggestion is to upgrade the Pi to Python 3. There's no point developing Python code for two separate versions (unless it's a library, which you'd use much more precautions than just sharing functions). You can do:

# Python 3.x
def getNumeric(prompt):
    while True:
        try:
            res = int(input(prompt))
            break
        except ValueError:
            print("Numbers only please!")
    return res

For Python 2.7.x, use raw_input() instead of input(). input() in Python 2 is not considered save since it evaluates the string given (and can be malicious).

Sign up to request clarification or add additional context in comments.

5 Comments

Text and Numbers work great, but in 2.7 (3 untested), if the user hits enter without any input I get:
SyntaxError: unexpected EOF while parsing
fixed (in 2.7) if I use raw_input. Thanks
The command input() is not safe in Python 2, because it evaluates the input string. It can also create a new program or run any program. It is not worse than an access to the console, but unsafe e.g. if the input is redirected remotely. An example of input __import__('os').system('sh')
@hynekcer Yea agreed, I'm going to change this (almost) 7 year old answer
0

Try:

def getNumeric(prompt):
  while True:
    response = input(prompt)
    try:
      if isinstance(response, int):
          return int(response)
      else:
          print "please enter a number:"
    except ValueError:
      print "please enter a number:"

1 Comment

Apart from the compulsory parentheses to put around the arguments of the print functions, it doesn't work with Python 3.X, since input() always yields a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.