2017-10-16 111 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