关于python:如何使用返回语句修复函数而不返回所有行

How to fix function with return statement not returning all the rows

本问题已经有最佳答案,请猛点这里访问。

我有一个函数,它返回或应该返回从数据库表中选择的所有行。但是,它只返回第一行。我不太明白当我使用'return'关键字时,为什么没有返回其余的行。代码有点长,所以我要包含一个示例代码,它与功能性术语有点相似。我相信如果我能解决这个问题,我就能解决主代码中的问题。我的示例代码如下。在这个代码中,只打印黄色。有人知道为什么吗?

1
2
3
4
5
def color_choser():
    colors = 'yellow', 'green', 'orange', 'blue', 'white', 'pupple', 'red', 'mangenta'
    for color in colors:
        return color
print(color_choser())


当函数返回一个值时,它将停止,因此当您将返回语句放入for循环中时,您将告诉它在循环的第一次运行之后停止。您只需返回颜色元组而不返回循环:

1
2
3
4
5
6
def color_choser():
    colors = 'yellow', 'green', 'orange', 'blue', 'white', 'pupple', 'red', 'mangenta'
    return colors
print(color_choser())

>>>'yellow', 'green', 'orange', 'blue', 'white', 'pupple', 'red', 'mangenta'

或者,如果您出于某种原因需要循环(我猜您实际上不只是打印颜色列表),您可以将想要的值附加到列表中并返回该列表:

1
2
3
4
5
6
7
8
9
10
11
12
def color_choser():
  colorArray = []
  colors = 'yellow', 'green', 'orange', 'blue', 'white', 'pupple', 'red', 'mangenta'

  for color in colors:
    colorArray.append(color)

  return colorArray

print(color_choser())

>>>['yellow', 'green', 'orange', 'blue', 'white', 'pupple', 'red', 'mangenta']