2016-11-11 63 views
0

,如果你實現它這樣我熟悉的分裂()函數是如何工作的:Python的輸入()函數

def sayHello(): 
    name = input("whats you´re name?:") 
    print("hello", name) 

在這種情況下,輸入功能,只希望從用戶的一個輸入。 但在這種情況下究竟發生了什麼?

def test(): 
    str1, str2 = input().split() 
    print(str1, str2) 

語法:

a, b = input() 

這是一種方式,要求2個輸入用戶在同一時間,或當你會用嗎?

+0

這是[參考](https://docs.python.org/3/reference/simple_stmts.html#assignment-statements)中描述的賦值的特例('如果目標列表是逗號分隔的目標列表......「),通常稱爲[解包](https://en.wikibooks.org/wiki/Python_Programming/Tuples#Packing_and_Unpacking)。 – bereal

回答

1

這僅長度爲2

的字符串工作剛剛嘗試這樣的事情在IPython中:

In [9]: a, b = input() 
"hallo" 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-9-3765097c12c0> in <module>() 
----> 1 a, b = input() 

ValueError: too many values to unpack 

In [10]: a, b = input() 
"ha" 

In [11]: a 
Out[11]: 'h' 

In [12]: b 
Out[12]: 'a' 

In [13]: a, b = input() 
"a" 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
<ipython-input-13-3765097c12c0> in <module>() 
----> 1 a, b = input() 

ValueError: need more than 1 value to unpack 

所以,不,這不是一個正確的方式,要求2個輸入。

2

這確實對Python 2和Python 3的

Python 3中的input()不同的事情是Python 2中的raw_input(),並且總是會返回一個字符串。

當您在a, b, = (1, 2)中執行元組解包時,右側的元素數量必須與左側的名稱數量相匹配。如果他們不這樣做,你會得到一個ValueError。由於字符串是可迭代的,如果用戶輸入兩個字符長的字符串,則a, b = input()將起作用。任何其他字符串都會導致程序崩潰。

要讓用戶一次輸入多個輸入,請在提示中明確定義格式,例如inp = input('Please input your first and last name, separated by a comma: '),然後解析輸入:first_name, last_name = inp.split(',')

請注意,如果您的程序輸入的字符串不正確,但多於或少於一個逗號,仍然會導致程序崩潰,但這樣做相當簡單,可以檢查,通知用戶並再次嘗試。

在Python 2上,input()試圖將值強制爲自然的Python值,所以如果用戶輸入[1, 2],input()將返回一個Python列表。這是一件壞事,因爲您仍然需要自己驗證和清理用戶數據,而您可能希望改爲使用"[1, 2]"

+0

感謝您的幫助!但是當我在控制檯中嘗試這個c,d = input(),然後輸入2 3或2,3時,它會讀取Valuerror太多的值以便解壓縮。爲什麼是這樣 ? – Fanny

+0

假設你在使用Python 3,這是因爲輸入'2,3'會導致input()返回一個長度爲4的可迭代字符串「2,3」。'c,d = 「2,3」'set'c =「2」','d =「3」',然後用盡變量,但仍然有一些字符串需要消耗。你需要做的是'c,d = input()。split(',')'或者'inp = input()'然後'c,d = inp.split(',')'對你更有意義。 –