0

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.

Ubik88
  • 3
  • 3
  • you might want to look here https://stackoverflow.com/questions/22265569/understanding-yield-in-python – b10n1k Jan 18 '15 at 04:07

3 Answers3

1

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.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
0

When a function returns something, the function will automatically break and exit the function. See more about this on this question. One option you have is to first append what you want return to a list and then return that list.

Community
  • 1
  • 1
michaelpri
  • 3,521
  • 4
  • 30
  • 46
0

When the function addtrinumbs looks at the return statement in the first loop, it exits the function, returning the concerned value. That is why it is returning only one value. You need to store the values in a list or something, then return the list. So, take a list2 = [] and instead of return y, do list2.append(y) and then eventually return the list, return list2.

theharshest
  • 7,767
  • 11
  • 41
  • 51