Differences between input and raw_input

In the tutorial, I read that there is a difference between input and raw_input . I found that they changed the behavior of these functions in Python 3.0. What is the new behavior?

And why in the python console interpreter is this

 x = input() 

Sends an error, but if I put it in a .py file and run it, is it not?

+7
python
source share
3 answers

In python 2.x, raw_input() returns a string, and input() evaluates the input in the execution context in which it is called

 >>> x = input() "hello" >>> y = input() x + " world" >>> y 'hello world' 

In python 3.x, input been canceled, and a function formerly known as raw_input is now input . Therefore, you need to manually call compile and eval if you want to use the old functions.

 python2.x python3.x raw_input() --------------> input() input() -------------------> eval(input()) 

In 3.x, the above session is as follows

 >>> x = eval(input()) 'hello' >>> y = eval(input()) x + ' world' >>> y 'hello world' >>> 

So, you probably made a mistake in the interpreter because you did not put quotation marks around your input. This is necessary because it is being evaluated. Where do you get the name error?

+14
source share

input () vs raw_input ()

raw_input collects the characters the user enters and presents them as a string. input () does not just evaluate the numbers, but treats all the input as Python code and tries to execute it. A knowledgeable but malicious user can enter a Python command that can even delete a file. Stick to raw_input () and convert the string to the desired data type using Python's built-in conversion functions.

Also input () is not secure due to user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised.

+3
source share

Simple:

  • raw_input() returns string values
  • while input() returns integer values

Example:

one.

 x = raw_input("Enter some value = ") print x 

Output:

 Enter some value = 123 '123' 

2.

 y = input("Enter some value = ") print y 

Output:

 Enter some value = 123 123 

Therefore, if we execute x + x = , it will output as 123123

while if we do y + y = It will output as 246

+3
source share

All Articles