Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is difference between raw_input() and input() functions in Python?
When working with user input in Python, developers often encounter two functions: input() and raw_input(). Understanding their differences is crucial for writing compatible code across Python versions.
Python input() Function
The input() function reads input from the user and returns it as a string. However, its behavior differs significantly between Python 2.x and Python 3.x versions.
Python 3.x input() Behavior
In Python 3.x, input() always returns a string, regardless of what the user enters ?
num_1 = input("Enter value of num_1: ")
num_2 = input("Enter value of num_2: ")
print("Values are", num_1, num_2)
print("Type of num_1:", type(num_1))
print("Type of num_2:", type(num_2))
Enter value of num_1: 10 Enter value of num_2: 20 Values are 10 20 Type of num_1: <class 'str'> Type of num_2: <class 'str'>
Python 2.x input() Behavior
In Python 2.x, input() evaluates the input as Python code, which can be dangerous ?
# Python 2.x behavior (dangerous)
num = input("Enter a number: ") # If user enters 10, type is int
name = input("Enter name: ") # If user enters hello, causes NameError
Python raw_input() Function
The raw_input() function was available only in Python 2.x and always returned input as a string, making it safer than Python 2.x's input().
Syntax and Usage
# Python 2.x only
var_1 = raw_input("Enter a value: ")
print(var_1)
print(type(var_1)) # Always <type 'str'> in Python 2.x
Key Differences
| Function | Python Version | Return Type | Safety |
|---|---|---|---|
raw_input() |
2.x only | Always string | Safe |
input() (Python 2.x) |
2.x only | Evaluates as code | Dangerous |
input() (Python 3.x) |
3.x only | Always string | Safe |
Migration Between Versions
When migrating from Python 2.x to 3.x, replace raw_input() with input() ?
# Python 2.x equivalent to Python 3.x
# Python 2.x: raw_input("Enter name: ")
# Python 3.x: input("Enter name: ")
name = input("Enter your name: ")
age = input("Enter your age: ")
# Convert to appropriate type if needed
age = int(age)
print(f"Hello {name}, you are {age} years old")
Enter your name: Alice Enter your age: 25 Hello Alice, you are 25 years old
Best Practices
Always validate and convert input to the required data type ?
try:
age = int(input("Enter your age: "))
print(f"Your age is {age}")
except ValueError:
print("Please enter a valid number")
Enter your age: 25 Your age is 25
Conclusion
Python 3.x's input() function behaves like Python 2.x's raw_input(), always returning strings. Python 2.x's input() was dangerous as it evaluated code. When migrating to Python 3.x, replace raw_input() with input().
