Raw_input () and input (), python2raw_input in Python2
Both are python built-in functions that interact with users by reading input from the console. However, their functions are different. Here are two small examples.
>>> raw_input_A = raw_input("raw_input: ")raw_input: abc >>> input_A = input("Input: ")Input: abcTraceback (most recent call last): File "<pyshell#1>", line 1, in <module> input_A = input("Input: ") File "<string>", line 1, in <module>NameError: name 'abc' is not defined >>> input_A = input("Input: ")Input: "abc" >>>
>>> raw_input_B = raw_input("raw_input: ")raw_input: 123 >>> type(raw_input_B) <type 'str'>>>> input_B = input("input: ")input: 123>>> type(input_B)<type 'int'>>>>
Example 1 shows that both functions can receive strings, but raw_input () directly reads the input from the console (any type of input can be received ). For input (), it is expected to be able to read a valid python expression, that is, you must enclose the string with quotation marks, otherwise it will cause a SyntaxError.
Example 2 shows that raw_input () treats all input as strings and returns the string type. Input () has its own characteristics when dealing with pure numeric input. It returns the type of the entered number (int, float). At the same time, we know in Example 1 that input () accept valid python expressions. For example, input (1 + 3) returns 4 of the int type.
View Built-in Functions and learn:
input([prompt]) Equivalent to eval(raw_input(prompt))
In essence, input () is implemented using raw_input (). It only calls the eval () function after raw_input () is called. Therefore, you can even use the expression as input () and it calculates the value of the expression and returns it.
However, in Built-in Functions, a statement is written as follows: Consider using the raw_input () function for general input from users.
Unless you have special requirements for input (), we generally recommend that you use raw_input () to interact with users.
-------
When I took a written test at a company today, I used raw_input () to accept integers (returns strings) and then used a line of statements to return integer data. Cup. At that time, I was not sure I could use the input () function! It is hereby recorded.