16.Python input () function: obtaining user input string

input () function used to generate a prompt to the user, and acquire the content input by the user. Since the input () function will always be placed in the user input string, the user can enter any content, input () function always returns a string.

For example the following procedure:

  1. = msg the INPUT ( "Please enter your value:" )
  2. print (type(msg))
  3. print(msg)

The first time you run the program, we enter an integer, runs as follows:

Please enter your value: 2
<class 'STR'>
2

The second time you run the program, we enter a float, run as follows:

Please enter your values: 1.2
<class 'STR'>
1.2

The third run the program, we enter a string, run as follows:

Please enter your value: the Hello
<class 'str'>
the Hello

As can be seen from the above process is running, no matter what kind of content input, you can always see the input () function returns a string, the program always converts user input to a string.

It should be noted that, Python  2.x provides a raw_input () function, the raw_input () function is equivalent to the Python 3.x in input () function.

The Python 2.x also provides an input () function, the input () function is more bizarre: require user input must be in line with Python syntax expression. Generally, a user can only enter an integer, floating point, complex, string and the like. Focus is formatted correctly, you must use double quotes such as the input string, otherwise Python will error.

Python 2.x to run using the above procedure, if an integer input, runs as follows:

Please enter your value: 2
<class 'int'>
2

Python 2.x to run using the above procedure, if a plurality of inputs, the process runs as follows:

Please enter your value: 2 + 3j
<type 'Complex'>
(3j + 2)

Python 2.x to run using the above procedure, if an input string, run as follows:

Please enter your value: the Hello
NameError: name 'the Hello' IS not defined

Reasons given above procedure are: Python 2.x the input () function requires the user must enclose the string enclosed in an input string.

In Python 2.x should try to use the raw_input () function to get user input, as in the raw_input Python 2.x () is equivalent to the Python 3.x in input ().

Guess you like

Origin www.cnblogs.com/youqc/p/12066558.html