📜  Python输入()函数

📅  最后修改于: 2022-05-13 01:55:42.482000             🧑  作者: Mango

Python输入()函数

Python input()函数用于获取用户输入。默认情况下,它以字符串的形式返回用户输入。

句法

参数

  • 提示:一个字符串,表示输入之前的默认消息(通常是屏幕)。但是,是否有提示消息是可选的。

返回: input() 返回一个字符串对象。即使输入的值是整数,它也会将其转换为字符串。

示例1:将用户的姓名和年龄作为输入并打印出来

默认情况下,输入返回一个字符串。所以姓名和年龄将被存储为字符串。

Python
# Taking name of the user as input 
# and storing it name variable
name = input("Please Enter Your Name: ")
  
# taking age of the user as input and 
# storing in into variable age
age = input("Please Enter Your Age: ")
  
# printing it
print("The name of the user is {0} and his/her age is {1}".format(name, age))


Python
# Taking number 1 from user as int
num1 = int(input("Please Enter First Number: "))
  
# Taking number 2 from user as int
num2 = int(input("Please Enter Second Number: "))
  
# adding num1 and num2 and storing them in
# variable addition
addition = num1 + num2
  
# printing
print("The sum of the two given numbers is {} ".format(addition))


Python
# Taking list1 input from user as list
list1 = list(input("Please Enter Elements of list1: "))
  
# Taking list2 input from user as list
list2 = list(input("Please Enter Elements of list2: "))
  
  
# appending list2 into list1 using .append function
for i in list2:
    list1.append(i)
  
# printing list1
print(list1)


输出:

示例 2:从用户那里获取两个整数并将它们相加。

在这个例子中,我们将研究如何从用户那里获取整数输入。要获取整数输入,我们将使用 int() 和 input()

Python

# Taking number 1 from user as int
num1 = int(input("Please Enter First Number: "))
  
# Taking number 2 from user as int
num2 = int(input("Please Enter Second Number: "))
  
# adding num1 and num2 and storing them in
# variable addition
addition = num1 + num2
  
# printing
print("The sum of the two given numbers is {} ".format(addition))

输出:

同样,我们可以使用 float() 来获取两个浮点数。让我们再看一个如何将列表作为输入的示例

示例 3:将两个列表作为输入并附加它们

Python

# Taking list1 input from user as list
list1 = list(input("Please Enter Elements of list1: "))
  
# Taking list2 input from user as list
list2 = list(input("Please Enter Elements of list2: "))
  
  
# appending list2 into list1 using .append function
for i in list2:
    list1.append(i)
  
# printing list1
print(list1)

输出: