DEV Community

threadspeed
threadspeed

Posted on

Why is this 'raw_input' detected as an error in Python?

If you get this error, you may be using an old version of Python or using old documentation.

In Python 3, the raw_input() function is no longer available, it's now deprecated.

Python 3 is not backwards compatible with Python 2. You should be using Python 3 or newer. If you have old code, you'll have to port it. (what's different?)

PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input()
, use eval(input()).

input()

Python 3 comes with the method input() to take keyboard input. It returns data in the form of a string, so you can do this

    x = input("Enter x")
    print(x)

But if you check the type, with type(x) it will output that the data type is str. If you do not want that, you can cast the data.

    x = int(x)

You can also cast it to a data type directly, if you don't want to do input validation

    x = int(input("Enter x:"))

But it's wise to do input validation, a user might do this:

    >>> x = int(input("Enter x:"))
    Enter x:hello
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: invalid literal for int() with base 10: 'hello'
    >>> 

You could create a function for that

    >>> def inputi(s):
    ...     x = 0
    ...     try:
    ...         x = int(input(s))
    ...     except:
    ...         print("Wrong input, type integer.")
    ...         return -1
    ...     finally:
    ...         return x
    ... 
    >>> x = inputi("Enter x:")
    Enter x:5
    >>> x = inputi("Enter x:")
    Enter x:hello
    Wrong input, type integer.
    >>> 

If you are new to Python, this is a good starting point Learn Python or the Python shell tutorial

Top comments (0)