Python input() 函數用於獲取用戶輸入。默認情況下,它以字符串的形式返回用戶輸入。
用法
input(prompt)
參數:
- Prompt:一個字符串,表示輸入之前的默認消息(通常是屏幕)。但是,是否有提示消息是可選的。
返回:input() 返回一個字符串對象。即使輸入的值是整數,它也會將其轉換為字符串。
例一:取的用戶的姓名和年齡作為輸入並打印
默認情況下,輸入返回一個字符串。所以姓名和年齡將被存儲為字符串。
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))
輸出:
示例 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)
輸出:
相關用法
- Tensorflow.js tf.input()用法及代碼示例
- Python input()和raw_input()的區別用法及代碼示例
- Python fileinput.input()用法及代碼示例
注:本文由純淨天空篩選整理自bistpratham大神的英文原創作品 Python input() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。