简体   繁体   中英

Appending into a list

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')

If you try running this function, with for example, as n = 3, why doesn't the elem append to the result properly? It keeps printing as new list of results. This messages up my isPal function.

The first line of your for loop replaces your result variable with a new list.

result= []

You should do this before the for loop instead.

Swap these lines:

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

Or you will be reassigning result in every iteration.

The issue is that you are redefining result each time.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM