python如何從鍵盤輸入數據?
python從鍵盤輸入數據的方法:
在python中使用raw_input()、input()、sys.stdin等方法獲取從鍵盤輸入的數據。
1、使用raw_input()函數獲取從鍵盤輸入的數據
python raw_input() 用來獲取控制台的輸入。raw_input() 將所有輸入作為字符串看待,返回字符串類型。
>>>a = raw_input("input:") input:123 >>> type(a) <type 'str'> # 字符串 >>> a = raw_input("input:") input:runoob >>> type(a) <type 'str'> # 字符串 >>>
2、使用input()方法獲取從鍵盤輸入的數據
input() 函數接受一個標准輸入數據,返回為 string 類型。
示例:
>>>a = input("input:") input:123 # 輸入整數 >>> type(a) <type 'str'> # 字符串 >>> a = input("input:") input:"runoob" # 正確,字符串表達式 >>> type(a) <type 'str'> # 字符串 >>> a = input("input:") input:runoob # 報錯,不是表達式 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> NameError: name 'runoob' is not defined <type 'str'>
3、使用sys.stdin方法獲取
import sys try: while True: print('Please input a number:') n = int(sys.stdin.readline().strip('\n')) #strip('\n')表示以\n分隔,否則輸出是“字符串+\n”的形式 print('Please input some numbers:') sn = sys.stdin.readline().strip()#若是多輸入,strip()默認是以空格分隔,返回一個包含多個字符串的list。 if sn == '': break sn = list(map(int,sn.split())) #如果要強制轉換成int等類型,可以調用map()函數。 print(n) print(sn,'\n') except: pass