Python教程(2.5)——控制檯輸入

寫Python程序時,你可能但願用戶與程序有所交互。例如你可能但願用戶輸入一些信息,這樣就能夠讓程序的擴展性提升。編程

 

這一節咱們來談一談Python的控制檯輸入。編程語言

 

輸入字符串

 

Python提供一個叫作input()的函數,用來請求用戶輸入。執行input()函數時,程序將會等待用戶在控制檯輸入信息,當用戶輸入換行符(即enter)時,返回用戶輸入的字符串。函數

 

例如:spa

 

>>> name = input()

 

這將會等待用戶輸入一行信息。注意接下來的一行開頭處沒有>>>命令提示符,由於>>>是指示用戶輸代碼的,這裏不是代碼。code

 

具體例子(輸入的字符串爲Charles,你也能夠輸入別的):blog

 

>>> name = input()
Charles >>> print('You entered:', s)
You entered: Charles

 

但這裏也有一個問題:不瞭解程序的用戶,看見程序等待輸入,不知道要輸入什麼。若是有提示文字不就更好了嗎?若是你學過其它編程語言,你可能會這樣寫:字符串

 

print('Enter your name:')
name = input()

 

然而Python提供了更簡潔的寫法:input()能夠接受一個參數,做爲提示文字:input

 

>>> name = input('Enter your name: ')

 

這樣,等待輸入就變成這個樣子了(仍以Charles爲例):ast

 

Enter your name: Charles

 

一個完整的例子:class

 

>>> 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爲單位。

相關文章
相關標籤/搜索