Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading