Python input() Function

Python 内置函数Python Built-in Functions

In Python3.x, the input() function accepts standard input data and returns it as string type.

In Python2.x, input() is equivalent toeval(raw_input(prompt)), used to get console input.

raw_input() treats all input as strings and returns string type. However, input() has its own characteristics when dealing with pure numeric input; it returns the type of the number entered (int, float).

Note:Both input() and raw_input() can receive strings, but raw_input() directly reads console input (it can receive any type of input). For input(), it expects to read a valid Python expression, meaning when you input a string you must enclose it in quotes, otherwise it will raise a SyntaxError.

Unless there is a special need for input(), in general we recommend using raw_input() to interact with users.

Note:In Python3, input() receives str type by default.

Function Syntax

input([prompt])

Parameter description:

  • prompt: prompt message

Examples

Python2.x: input() requires inputting a Python expression

>>>a = input("input:") input:123 # input integer >>> type(a) <type 'int'> # integer type >>> a = input("input:") input:"example" # correct, string expression >>> type(a) <type 'str'> # string >>> a = input("input:") input:example # error, not an expression Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'example' is not defined <type 'str'>

Python2.x: raw_input() treats all input as strings

>>>a = raw_input("input:") input:123 >>> type(a) <type 'str'> # string >>> a = raw_input("input:") input:example >>> type(a) <type 'str'> # string >>>

More Content

Python3.x input explanation

Difference between raw_input() and input() in Python2.x and Python3.x

Python 内置函数Python Built-in Functions

Other Extensions