简体   繁体   English

Python:我的函数将打印连续输出,但不会返回它们。

[英]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. 更改时,它将连续打印y。 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(). 所以我希望addone()连续从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. 当我运行它时,我只会得到1的输出,即2。我已经阅读了有关生成器的信息,但是我不确定这是否是我需要使用的输出。 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. 您似乎缺少了生成器的概念addtrinumbs应该产生值而不是返回值。 (It will apparently never terminate, but, for a generator , that's OK). (显然它将永远不会终止,但是对于生成器来说 ,这是可以的)。

addone will take the generator as the argument and loop over it: addone将生成器作为参数并在其上循环

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. 当函数addtrinumbs在第一个循环中查看return语句时,它将退出该函数,并返回相关值。 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 . 因此,采用list2 = [] ,而不是return y ,而是执行list2.append(y) ,然后最终返回列表, return list2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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