新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python的輸入函數(shù)
Python的輸入函數(shù)是input(),它用于從用戶獲取輸入,在Python中,我們可以使用input()函數(shù)來獲取用戶輸入的任何數(shù)據(jù)類型,如字符串、整數(shù)、浮點數(shù)等。input()函數(shù)的基本語法如下:

user_input = input("提示信息:")
"提示信息:"是一個可選參數(shù),用于向用戶顯示提示信息,當用戶運行程序時,程序會暫停并等待用戶輸入,用戶可以輸入任何字符,然后按回車鍵,程序?qū)⒗^續(xù)執(zhí)行,并將用戶輸入的內(nèi)容作為字符串存儲在變量user_input中。
下面是一些使用input()函數(shù)的示例:
1、獲取字符串輸入:
name = input("請輸入您的名字:")
print("您好," + name + "!")
2、獲取整數(shù)輸入:
age = int(input("請輸入您的年齡:"))
print("您已經(jīng)" + str(age) + "歲了。")
3、獲取浮點數(shù)輸入:
height = float(input("請輸入您的身高(厘米):"))
print("您的身高是" + str(height) + "厘米。")
4、獲取多個輸入:
name = input("請輸入您的名字:")
age = int(input("請輸入您的年齡:"))
height = float(input("請輸入您的身高(厘米):"))
print("您好," + name + "!您已經(jīng)" + str(age) + "歲了,身高是" + str(height) + "厘米。")
5、使用默認值:
name = input("請輸入您的名字(默認為張三):") or "張三"
print("您好," + name + "!")
6、限制輸入次數(shù):
attempts = 0
while attempts < 3:
user_input = input("請輸入一個數(shù)字(最多嘗試3次):")
try:
number = int(user_input)
print("您輸入的數(shù)字是:" + str(number))
break
except ValueError:
attempts += 1
print("無效輸入,請重新輸入,您還有" + str(3 attempts) + "次機會。")
else:
print("很遺憾,您沒有成功輸入一個數(shù)字。")
7、將輸入內(nèi)容轉(zhuǎn)換為其他數(shù)據(jù)類型:
user_input = input("請輸入一個數(shù)字(整數(shù)或浮點數(shù)):")
try:
number = int(user_input)
print("您輸入的數(shù)字是:" + str(number))
except ValueError:
try:
number = float(user_input)
print("您輸入的數(shù)字是:" + str(number))
except ValueError:
print("無效輸入,請輸入一個整數(shù)或浮點數(shù)。")
8、使用列表接收多個輸入:
items = []
while True:
item = input("請輸入一個項目(按回車鍵結(jié)束):")
if item == "":
break
items.append(item)
print("您輸入的項目有:", items)
9、使用split()方法分割輸入內(nèi)容:
user_input = input("請輸入您的郵箱地址:")
username, domain = user_input.split("@")
print("用戶名是:" + username)
print("域名是:" + domain)
10、使用strip()方法去除輸入內(nèi)容的空格和換行符:
user_input = input("請輸入您的郵箱地址:")
email = user_input.strip()[:1] # 去掉最后一個換行符(如果有)
print("您的郵箱地址是:" + email)
Python的input()函數(shù)非常強大,可以方便地獲取用戶輸入的各種數(shù)據(jù)類型,通過組合使用input()函數(shù)和其他Python功能,我們可以編寫出各種實用的程序。
當前文章:Python的輸入函數(shù)
文章轉(zhuǎn)載:http://www.fisionsoft.com.cn/article/dpjhici.html


咨詢
建站咨詢
