SoFunction
Updated on 2024-11-12

Python built-in functions of raw_input and input code analysis

Both of these are built-in python functions that interact with the user by reading input from the console. But they don't have the same functionality. Let's take two small examples.

 >>> raw_input_A = raw_input("raw_input: ")
 raw_input: abc >>> input_A = input("Input: ")
 Input: abc
 Traceback(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' >
  >>>

As you can see in Example 1, both functions can take strings, but raw_input() reads input directly from the console (it can take any type of input). input(), on the other hand, expects to read a legal python expression, i.e., you must enclose the string in quotes when you type it, otherwise it will raise a SyntaxError.

Example 2 shows that raw_input() treats all input as a string and returns the string type. input(), on the other hand, has its own characteristics when treating purely numeric input; it returns the type of the number entered (int, float); and as you know from Example 1, input() accepts legal python expressions, e.g., input( 1 + 3 ) will return 4 of type int.

Check out Built-in Functions to find out:

input([prompt])
Equivalent to eval(raw_input(prompt))

input() is essentially the same thing as raw_input(), except that you call raw_input() followed by eval(), so you can even take an expression as an argument to input() and it will compute the value of the expression and return it.

nevertheless Built-in Functions There's a line in there that goes like this.:Consider using the raw_input() function for general input from users.

Unless there is a specific need for input(), we generally recommend using raw_input() to interact with the user.

summarize

The above is the entire content of this article on Python built-in functions of raw_input() and input() code analysis, I hope it will help you. Interested friends can continue to refer to this site:Python Object-Oriented Programming Fundamentals Explained (II)Python explore the ModelForm code detailspython in requests to crawl to the web page content appears garbled problem solution introductionetc., if there are deficiencies, welcome to leave a message to point out. Thank you friends for the support of this site!