Menu ▾ ▴

input problems

SiKing
2009-02-18
2013-03-15
  • SiKing

    SiKing - 2009-02-18

    Hello.
    I am still new to python, so I am not sure if the following is a problem with pydev, python, or me.

    I am trying to use the input(prompt) function to read a number from the user. If the user does supply a number everything is fine. However, if the user supplies a non-number, say something like "three", then the program crashes with an error:
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1, in <module>
    NameError: name 'three' is not defined

    What am I doing wrong?

     
    • Fabio Zadrozny

      Fabio Zadrozny - 2009-02-18

      If you're using version 2.x, I think that you want raw_input(), which gets the text the user enters -- input() actually does eval(raw_input()).

      Cheers,

      Fabio

       
    • Steve Holden

      Steve Holden - 2009-02-18

      You appear to be using Python 2.X. Unlike the newer 3.0, in older versions of Python the input() function takes a string from the user, evaluates it as a Python expression, and then returns the result of the evaluation. So, since you haven't established a variable called "three" the attempted evaluation raises an exception.

      Try using the raw_input() function, but note: this returns a string, so you will have to convert that to a floating-point or integer number by applying either the float() or the int() function. If the format of the input does not allow it to be converted a ValueError exception will be raised, so you'll have to be prepared to catch that.

       
    • SiKing

      SiKing - 2009-02-18

      Shortly after posting my question, I found: http://docs.python.org/tutorial/errors.html#handling-exceptions
      I am just surprised that Python does (did?) not have such functionality already built in.

      Thank You!