用 Python 讀取鍵盤輸入
Python 提供了兩個內建函式來從標準輸入讀取一行文字,預設情況下,該文字來自鍵盤。這些函式是 −
- raw_input
- input
raw_input 函式
raw_input([提示]) 函式從標準輸入中讀取一行並將其作為字串(刪除尾隨換行符)返回。
#!/usr/bin/python str = raw_input("Enter your input: ") print "Received input is : ", str
它提示你輸入任何字串,並會在螢幕上顯示相同的字串。當我鍵入 "Hello Python!" 時,它的輸出如下 −
Enter your input: Hello Python Received input is : Hello Python
input 函式
input([提示]) 函式與 raw_input 等效,但它假設輸入為有效的 Python 表示式,並向你返回已計算的結果。
#!/usr/bin/python str = input("Enter your input: ") print "Received input is : ", str
對於輸入的輸入的內容,這會產生以下結果 −
Enter your input: [x*5 for x in range(2,10,2)] Recieved input is : [10, 20, 30, 40]
廣告