Search code examples
pythonfunctioncontinuous

Python: My function will print continuous outputs but will not return them.


First of all I could not figure out an appropriate title for this. Secondly, I am pretty new to programming. Anyway, I have this function:

def addtrinumbs():
    x = 1
    list1 = []
    while x > 0:
        list1.append(x)
        x = x + 1
        y = sum(list1)
        print y

This will continuously print y as it changes. What I want to do is this:

def addtrinumbs():
    x = 1
    list1 = []
    while x > 0:
        list1.append(x)
        x = x + 1
        y = sum(list1)
        return y

def addone(numbers):   
    x = numbers + 1   
    print x

addone(addtrinumbs())

So I want addone() to continuously take inputs from addtrinumbs(). I feel like there is a real fundamental and simple concept that I am missing. When I run it, I only get 1 output, which is 2. I have read about generators and I am not sure if that is what I need to be using. I think I understand what they are used for but I cannot find an example that is related to my problem. Any help or steering in the right direction would be nice, thanks.


Solution

  • You appear to be missing the concept of generators -- addtrinumbs should yield values rather than return them. (It will apparently never terminate, but, for a generator, that's OK).

    addone will take the generator as the argument and loop over it:

    for x in numbers:
        print(x+1)
    

    This will emit an unending stream of numbers -- there had better be an exit condition somewhere -- but, it's the general concept to use.