寫Python程序時,你可能希望用戶與程序有所交互。例如你可能希望用戶輸入一些信息,這樣就可以讓程序的擴展性提高。
這一節我們來談一談Python的控制台輸入。
輸入字符串
Python提供一個叫做input()的函數,用來請求用戶輸入。執行input()函數時,程序將會等待用戶在控制台輸入信息,當用戶輸入換行符(即enter)時,返回用戶輸入的字符串。
例如:
>>> name = input()
這將會等待用戶輸入一行信息。注意接下來的一行開頭處沒有>>>命令提示符,因為>>>是指示用戶輸代碼的,這里不是代碼。
具體例子(輸入的字符串為Charles,你也可以輸入別的):
>>> name = input() Charles >>> print('You entered:', s) You entered: Charles
但這里也有一個問題:不了解程序的用戶,看見程序等待輸入,不知道要輸入什么。如果有提示文字不就更好了嗎?如果你學過其它編程語言,你可能會這樣寫:
print('Enter your name:') name = input()
然而Python提供了更簡潔的寫法:input()可以接受一個參數,作為提示文字:
>>> name = input('Enter your name: ')
這樣,等待輸入就變成這個樣子了(仍以Charles為例):
Enter your name: Charles
一個完整的例子:
>>> fname = input('Enter your first name: ') Enter your first name: Charles >>> lname = input('Enter your last name: ') Enter your last name: Dong >>> print('Your name: %s, %s' % (lname, fname)) Your name: Dong, Charles
輸入數字
那輸入數字呢?你可能會想這么做:
>>> height = input('Enter your height, in centimeters: ')
然后輸出:
>>> print('You\'re', height, 'cm tall.')
也沒有問題。
但如果這樣寫:
>>> print('You\'re 1 cm taller than', height - 1, 'cm.')
你會得到:
Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for -: 'str' and 'int'
注意最下面一行:
TypeError: unsupported operand type(s) for -: 'str' and 'int'
意思是說,-兩邊的參數分別是str和int,而-運算符不能用在這兩種類型之間!
原來,input()返回的是一個str,返回值被賦給height,因此height也是str類型。height-1就是str和int進行減法了。
那怎么辦呢?聯系之前說的類型轉換知識,把input()的返回值轉換成我們所需要的int類型就可以了:
>>> height = int(input('Enter your height, in centimeters: '))
現在再試一下,是不是沒有問題了。
輸入非str變量的格式:
var = type(input(text))
var為輸入變量,type為要輸入的類型,text為提示文字。
不過這里還有一個小問題:無法在一行輸入多個數字。這個問題將在后面解決。
小結
1. 使用input()進行輸入。
2. 對於非字符串類型,需要進行轉換,格式為type(input(text))。
練習
1. 要求用戶輸入身高(cm)和體重(kg),並輸出BMI(Body Mass Index)。BMI=體重/(身高**2),體重單位為kg,身高單位為m。下面是一個例子:
Enter your height, in cm: 175 Enter your weight, in kg: 50 Your BMI: 16.3265306122449
注意輸入的身高需要轉換成以m為單位。
