2016-09-01 60 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