Let's say I write a for loop that will output all the numbers 1 to x:
x=4
for number in xrange(1,x+1):
print number,
#Output:
1
2
3
4
Now, putting that same for loop into a function:
def counter(x):
for number in xrange(1,x+1):
return number
print counter(4)
#Output:
1
Why do I only obtain one value when I put the for-loop into a function?
I have been evading this problem by appending all the results of the for-loop to a list, and then returning the list.
Why does the for loop append all the results, and not just one?:
def counter(x):
output=[]
for number in xrange(1,x+1):
output.append(number)
return output
What is the best method of returning all the values, appending to a list seems very inefficient.
returnreturns from a function. You may be interested inyieldbut that will require learning whatreturndoes in the first place. - squiguy