Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 input() Function

Python3 input() Function

Python3 Built-in Functions Python3 built-in 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 as int()、float())。

Function syntax


input([prompt])

Parameter Description:

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 >>>

print

(

"

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

)

print

(

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

(

)

)

print

(

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

print

(

"The area of the triangle is:"

,

format

(

s

,

'.2f'

)

)

Running result:


请输入三角形三边的长:3 4 5
三角形面积为: 6.00

Summary of common usage


Differences between Python2 and Python3

In Python2:

In Python3:

Core summary

In one sentence:


input() = 获取输入 + 返回字符串

Python3 Built-in Functions Python3 built-in function