2016-09-01 63 views
1

我正在使用python3編寫一個函數,要求用戶輸入一定次數,然後應該將所有輸入編譯到列表中。我已經能夠獲得函數來輸入沒有問題,但是當我嘗試打印列表時,它說沒有任何問題。如何將輸入從for循環編譯到列表中

def get_list(t): 
n = [] 
for i in range (1,t+1): 
    try: 
     x = input("Give me the next integer in the list: ") 
    except ValueError: 
     print("Input must be an integer.") 
    n.append(x) 

>>> list1 = get_list(3) 
Give me the next integer in the list: 3 
Give me the next integer in the list: 43 
Give me the next integer in the list: 32 
>>> print(list1) 
None 

我也嘗試過在那裏將存儲響應爲列表,但它只會做函數一次:

>>> def get_list(t): 
n = [] 
for n in range(t): 
    try: 
     n = int(input("Give me the next integer in the list: ")) 
     return n 
    except ValueError: 
     print("Input must be an integer.") 
list.append(n) 

>>> list1 = get_list(3) 
Give me the next integer in the list: 8 
>>> list1 
8 
+2

你的函數不返回任何東西:) –

回答

2

你缺少你的功能的回報!修復像這樣的代碼:

def get_list(t): 
    n = [] 
    for i in range (1,t+1): 
     try: 
      x = input("Give me the next integer in the list: ") 
     except ValueError: 
      print("Input must be an integer.") 
     n.append(x) 
    return n 

得到這個樣本結果:

>>> y = get_list(3) 
Give me the next integer: 1 
Give me the next integer: 2 
Give me the next integer: 3 
>>> print(y) 
[1, 2, 3] 
+0

謝謝!我完全忘了確保有回報! – fuk