Search code examples
pythonpython-3.xreturn

Returning multiple values from a loop w/o getting the "None"


Is there any way to return multiple results without having to create a blank tuple, add each iteration to it, and return the tuple?

I just want to get rid of the implicitly returned None at the end of loop.

from random import randint

class Lotto(object):
    def fir_num(self):
        print("First prize:")
        num = randint(000000, 999999)
        return "%06d" % num           #no problem for single value

    def sec_num(self):
        print("Second prizes:")
        i = 0
        while i <= 5:
            i += 1
            num = randint(000000, 999999)
            print("%06d" % num)       #if uses "return", the function returns only one result

L = Lotto()
print(L.fir_num())
print(L.sec_num())

Solution

  • You can only return once from a function. So the best would be to collect your result in a list and return the list:

    from random import randint
    
    def sec_num(count=5):
        return [randint(0, 999999) for _ in range(count)]
    
    for num in sec_num():
        print("%06d" % num)
    

    Output:

    710690
    816475
    087483
    572131
    292748
    

    Looks like you don't access self. Therefore, you don't need a class for the case you show in your example. Going with simple function seems preferable here.

    If you have many second prices, say a million or so, you can make your function more efficient using yield. This would turn your function into a generator. This is a whole new concept to understand and ne need for case but worthwhile to explore when you get deeper into Python.