Python For loop multiple returns(Python For循环多次返回)
问题描述
我应该用 python 为我的一门计算机科学课程编写一个函数.该函数应该接受一个 startValue 然后递增它直到达到 numberOfValues .到目前为止,这是我的功能:
I am supposed to write a function for one of my computer science classes in python. The function is supposed to take in a startValue and then increment it until numberOfValues is reached. This is my function so far:
def nextNValues(startValue, increment, numberOfValues):
result = int(0)
for i in range(0, numberOfValues):
increase = i * increment
result = startValue + increase
return result
我这样称呼它:
print(nextNValues(5,4,3))
问题是输出只有 13.我怎样才能让它在每次增加时返回一个数字.例如,5、9、13?我以前的函数一直有这个问题,但我只是在没有太多逻辑的情况下添加和删除东西来让它工作.我做错了什么?
The problem is that the output is only 13. How do I make it so it returns a number each time it increments. For example, 5, 9, 13? I have been having this problem with my previous functions but I have just been adding and removing things without much logic to get it to work. What am I doing wrong?
推荐答案
这是 发电机.
长话短说,只需使用 yield
而不是 return
:
Long story short, just use yield
instead of return
:
def nextNValues(startValue, increment, numberOfValues):
result = int(0)
for i in range(0, numberOfValues):
increase = i * increment
result = startValue + increase
yield result
您的代码的客户端可以在一个简单的循环中使用它:
The clients of your code can then use it either in a simple loop:
for value in nextNValues(...):
print(value)
如果需要,他们可以通过 list
转换得到一个列表.例如,如果需要打印结果:
Or they can get a list if needed by converting it with list
.
For example, if one needed to print the result:
print(list(nextNValues(...)))
这篇关于Python For循环多次返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python For循环多次返回


基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01