-2

I have a function that return or should return all the rows selected from a database table. However, it returns only the first rows. I don't quite understand why the rest rows are not returned when i use the 'return' keyword. The code is a bit long, so i'm including a sample code which is a bit similar terms of functionality. I believe if i can get a fix for this, i should be able to fix the one in the main code. My sample code is below. In this code, only the color yellow is printed. Please anybody know why?

def color_choser():
    colors = 'yellow', 'green', 'orange', 'blue', 'white', 'pupple', 'red', 'mangenta'
    for color in colors:
        return color
print(color_choser())
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
Mart
  • 39
  • 7

1 Answers1

2

When a function returns a value, it stops, so when you put that return statement inside the for loop, you are telling it to stop after the first run of the loop. You could simply return the colors tuple without the loop:

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'

or, if you need the loop for some reason (I'm guessing you aren't actually just printing that list of colors) you could append the values you want to a list and return that list:

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']