2017-10-16 112 views
-1
def silly(n): 
    """requires: n is an int > 0 
    Gets n inputs from user 
    Prints 'Yes' if the inputs are a palindrome; 'No' otherwise""" 
    assert type(n) == int and n > 0 
    for i in range(n): 
     result= [] 
     elem = input('Enter something: ') 
     result.append(elem) 
     print(result) 

    if isPal(result): 
     print('Is a palindrome') 
    else: 
     print('Is not a palindrome') 

如果您尝试运行此函数,例如n = 3,为什么elem不会正确追加到结果?它将打印作为新的结果列表。这消息我的isPal函数。追加到列表中

回答

3

for循环的第一行用您的新列表替换您的result变量。

result= [] 

您应该在for循环之前执行此操作。

+0

这使得现在更有意义,谢谢! – Miraclefruit

+0

没问题 - 如果这解决了你的问题,不要忘记勾选这个答案:) – Shadow

2

问题在于你每次重新定义结果。

def silly(n): 
    """requires: n is an int > 0 
    Gets n inputs from user 
    Prints 'Yes' if the inputs are a palindrome; 'No' otherwise""" 
    assert type(n) == int and n > 0 
    result= [] 
    for i in range(n): 
     elem = input('Enter something: ') 
     result.append(elem) 
    print(result) 
3

交换这些行:

result = [] 
for i in range(n): 
    # ... 

,否则你会在每个迭代中重新分配result