Skip to content
Advertisement

how do I return a list containing print statements?

So i am working on this function that takes a list as a parameter containing positive int, negative int, and the number 0 (zero). I have written the function using a while function with nested if statements to determine the value of each integer. Here is an example:

def Signs1(numList):
num = 0
while num < len(numList):
    if numList[num] > 0:
        print('p')
    elif numList[num] == 0:
        print('z')
    else:
        print('n')
    num += 1

My question is how do i return each print statement in a List order, like so: [‘p’, ‘p’, ‘p’, ‘n’, ‘z’, ‘n’]

I have tried including the (end=” “) function to return them all on one line which works fine but i want to return them using a return function. Is this possible and if so how would one go about to do this?

Advertisement

Answer

With while loop, initialize an empty list (res), use its length as counter in while loop. Check element of numlist using length of res as index, append it to res, and return res :

def Signs1(numList):
    res = []
    while len(res) < len(numList):
        if numList[len(res)] > 0:
            res.append('p')
        elif numList[len(res)] == 0:
            res.append('z')
        else:
            res.append('n')
    return res

numlist = [2,6,-1,3,0,-4,1,5]
result = Signs1(numlist)
print(result)

# ['p', 'p', 'n', 'p', 'z', 'n', 'p', 'p']
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement