Python3 input() Function
input() The function gets user input from standard input (the keyboard) and returns astring (str) type。
Note:
input()No matter what is entered, the return value is always a string. For numeric calculations, you must convert the type manually (such asint()、float())。
Function syntax
input([prompt])
Parameter Description:
- **prompt:** optional, the message prompting the user for input
Example
input() Gets user input and returns it as a string.
Basic usage of input()
name
=
input
(
"
Please enter your name:
"
)
Please enter your name: Xiao Ming >>>
(
"
Hello,
"
,
name
)
Hello, Xiao Ming
Even if a number is entered, the return value is still a string.
Type issues (a common pitfall)
a
=
input
(
"
Please input a number:
"
)
Please input a number:
123
type
(
a
)
<
class
'
str
'
**Note:** a value obtained directly from input() cannot be used in numeric calculations.
Incorrect example:
>>> a = input("请输入数字:")
>>> print(a + 1)
TypeError: can only concatenate str (not "int") to str
Correct way:
>>> a = int(input("请输入数字:"))
>>> print(a + 1)
input() receives multiple values
split() It splits the input on spaces into an array of strings.
Example
Enter multiple values (separated by spaces)
a
,
b
,
c
=
input
(
"Please enter three numbers:"
)
.
split
(
)
Convert the types
a
=
int
(
a
)
b
=
int
(
b
)
c
=
int
(
c
)
(
a
,
b
,
c
)
Use map() Type conversion can be done all at once, making the code more concise.
Recommended approach (advanced)
Complete splitting + conversion in one step
a
,
b
,
c
=
map
(
int
,
input
(
"Please enter three numbers:"
)
.
split
(
)
)
(
a
,
b
,
c
)
Practical example: calculating the area of a triangle
Enter the three sides of the triangle
a
,
b
,
c
=
map
(
int
,
input
(
"Please enter the lengths of the three sides:"
)
.
split
(
)
)
Compute the semi-perimeter
p
=
(
a + b + c
)
/
2
Calculate the area with Heron's formula
s
=
(
p *
(
p - a
)
(
p - b
)
(
p - c
)
)
**
0.5
(
"The area of the triangle is:"
,
format
(
s
,
'.2f'
)
)
Running result:
请输入三角形三边的长:3 4 5
三角形面积为: 6.00
Summary of common usage
input("提示"): input with a promptinput(): input without a promptint(input()): get an integerfloat(input()): get a floatinput().split(): get multiple stringsmap(int, input().split()): get multiple integers (recommended)
Differences between Python2 and Python3
In Python2:
raw_input(): returns a stringinput(): executes the expression (a security risk)
In Python3:
- Only
input() - is retained, uniformly returning a string, which is safer and easier to understand
Core summary
In one sentence:
input() = 获取输入 + 返回字符串
- Returns a string by default
- The type must be converted before calculations
- For multiple inputs, split() + map() is recommended
Python3 built-in function