3.input
輸入
Syntax
input(prompt)
prompt:A String, representing a default message before the input.
※input()進來的都是字串,由資料轉換函式來決定資料型態。※
【Single input 單一輸入】
【輸入字串的語法】:字串變數 = input('[提示文字]')
※無提示文字稱為「隱性輸入」,有提示字串稱為「顯性輸入」,提示字串可以用單或雙引號表示。
※參加線上測驗時不需要提示文字※
輸入字串範例:name = input('姓名:')
Q3-1_打招呼
輸入:Allen
輸出:歡迎光臨Python世界,Allen
【輸入數字的語法】:數字變數 = int( input('[提示文字]') )
輸入數字範例:num = int( input('輸入數字:') )
Q3-2_BMI值計算
輸入:體重(公斤)、身高(公尺)
輸出:BMI #BMI公式 = 體重 / 身高的平方
【Multi input 多項輸入】
Multi Character or String: Fixed string numbers seperate by seperator.
Syntax:str1,str2,... = input(prompt).split(seperator)
seperator:Default is blank.
利用input函式的字串解析函式split(),即可輸入連續的字元(串)。
str1, str2 = input().split()
print(str1, str2) #str1,str2是字串,最多輸入2個、超過則「unpack error」。
Input: 1 2,Output: 1 2 #str1, str2是字元
Input: abc def,Output: abc def
String List
Syntax:str_list = input(prompt).split(seperator)
str_list = input().split()
print(str_list) #str_list是字(元)串串列,不限定輸入元素數量。
Input: 1 2 3 4 5 6,Output: ['1', '2', '3', '4', '5', '6'] #字元串列
Input: abc def,Output: ['abc', 'def'] #字串串列
Multi Numberic: 固定數量的數字
Syntax:num1,num2,... = map( int, input(prompt).split(seperator) )
num1, num2, num3 = map(int,input().split())
print(num1+num2+num3) #num1,num2,num3是數字
Input: 1 2 3,Output: 6 #數字相加
Numberic List: 數字串列
Syntax:num_list = [ int(i) for i in input(prompt).split(seperator) ]
利用input函式結合串列解析式,即可輸入連續的數值。(串列形式)
num_list = [int(i) for i in input().split()]
print(num_list) #num_list是數字串列
Input: 1 2 3,Output: [1, 2, 3] #串列前後有中括號
Syntax:num1_list = list( map(int, input(prompt).split(seperator) ) )
num1_list = list( map(int, input().split()) )
print(num1_list) #num1_list是數字串列
Input: 1 2 3,Output: [1, 2, 3] #串列前後有中括號
字串串列轉數字串列
Convert String List to Numberic List
str = input(prompt).split(seperator)
num2_list = [ int(i) for i in str.split(seperator) ] 或
num2_list = list( map(int, str.strip().split(seperator) ) )
《避免執行視窗提早關閉》
在程式最後一行加上:tmp = input('按Enter結束...')
參考文獻
map()函數:https://www.wongwonggoods.com/python/python-map/