Comparing input() and raw_input() in Python with Examples

In Python, both input() and raw_input() are used to read input from the user, but they behave differently.

input() Function

The input() function reads a line of text from the user and evaluates it as Python code. This means that if the user enters a valid Python expression, it will be executed and the result will be returned.

Example:

result = input("Enter a number: ")
print(result)  # prints the result of the evaluated expression

If the user enters 2 + 2, the input() function will evaluate the expression and return the result 4.

raw_input() Function

The raw_input() function reads a line of text from the user and returns it as a string without evaluating it as Python code. This means that the user’s input is returned verbatim, without any processing.

Example:

result = raw_input("Enter a number: ")
print(result)  # prints the raw input string

If the user enters 2 + 2, the raw_input() function will return the string "2 + 2" without evaluating it.

Key Differences

Python 2:

  • raw_input() reads input as a string.
  • raw_input() is not available in Python 3.

Python 3:

  • input() reads input as a string.
  • input() in Python 3 is equivalent to raw_input() in Python 2.

Compatibility Note

In Python 2, input() behaves differently than in Python 3. In Python 2, input() evaluates the user input as Python code and returns it as a result. To get the behavior of raw_input() in Python 2, you should use raw_input() instead.

Python 2: input() Compatibility

If you want to maintain compatibility with both Python 2 and Python 3, you can define input() in Python 2.

# Define input() for Python 2
try:
    input = raw_input
except NameError:
    pass

# Usage in Python 2
name = input("Enter your name: ")
print("Hello, " + name)

By defining input() in this way in Python 2, you can use it like in Python 3, ensuring compatibility across Python versions.