使用Python中的示例的input()函数

Python input() 功能

input()函数是一个库函数,用于获取用户输入,它在控制台上显示给定的消息,等待输入并以字符串格式返回输入值。

语法:

    input(prompt)

Parameter(s): promot –将在控制台上显示的字符串值/消息。

返回值: str –以字符串格式返回用户输入。

示例

    Input:
    text = input("Input any text: ")
    
    # 如果用户输入的是“ Hello world!”"Hello world!"
    print("The value is: ", text)
    
    Output:
    Input any text: Hello world!

示例1:输入一个字符串并打印它及其类型

# python代码演示示例
# of input() function

# 用户输入
text = input("Input any text: ")

# 打印值 
print("The value is: ", text)

# 打印类型
print("return type is: ", type(text))

输出结果

Input any text: Hello world!
The value is:  Hello world!
return type is:  <class 'str'>

示例2:输入不同类型的值并打印它们及其类型

# python代码演示示例
# of input() function

# 输入1
input1 = input("Enter input 1: ")
print("type of input1 : ", type(input1))
print("value of input1: ", input1)

# 输入2
input2 = input("Enter input 2: ")
print("type of input2 : ", type(input2))
print("value of input2: ", input2)

# 输入3
input3 = input("Enter input 3: ")
print("type of input3 : ", type(input3))
print("value of input3: ", input3)

输出结果

Enter input 1: 12345
type of input1 :  <class 'str'>
value of input1:  12345
Enter input 2: 123.45
type of input2 :  <class 'str'>
value of input2:  123.45
Enter input 3: Hello [email protected]#$
type of input3 :  <class 'str'>
value of input3:  Hello [email protected]#$

输入整数和浮点值

没有直接函数可用于以整数值或浮点值进行输入。

input()函数从任何类型的用户处获取输入,例如整数,浮点数,字符串,但以字符串格式返回所有值。如果我们需要整数或浮点类型的值,则需要对其进行转换。

为了将输入转换为整数,我们使用 int() 功能。

要以浮点形式转换输入,我们使用 float() 功能。

示例3:用于输入整数和浮点值的Python代码

# python代码演示示例
# of input() function

# 输入一个整数
num = int(input("Enter an integer value: "))
print("type of num: ", type(num))
print("value of num: ", num)

# 输入一个浮点值
num = float(input("Enter a float value: "))
print("type of num: ", type(num))
print("value of num: ", num)

输出结果

Enter an integer value: 12345
type of num:  <class 'int'>
value of num:  12345
Enter a float value: 123.45
type of num:  <class 'float'>
value of num:  123.45