简体   繁体   中英

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.

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 some where -- but, it's the general concept to use.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM