Although I have passed Codecademy loop lesson, but I still don’t understand how to use loops correctly. In other words, I really have a big problem in using loops . For example:
def over_nine_thousand(lst):
all_sum = 0
for i in lst:
all_sum += i
return all_sum
print(over_nine_thousand([8000, 900, 120, 5000])) # prints 8000 instead of 14020
In the code above, I want to sum all list numbers with function called over_nine_thousand
that takes in lst
as a parameter but print(over_nine_thousand([8000, 900, 120, 5000]))
only prints the first element 8000. Why is this happening ?? please help me understand how loops actually work and how to use range()
function because whenever I write loops, they don’t work correctly.
Hello! It isn’t your use of range()
-or the lack thereof, it is your placement of return
. return
stops a function, and therefore any loop within that function, when you have
The return
actually stops the loop from looping, and gives the data back to the caller. So, in your case, return all_sum
returns the value of all_sum
after just one iteration over the lst
list.
To your question about range()
. If you just want to loop over a list (or string/other iterable), then you don’t need range()
. If you want to loop over a series of numbers, or you want to deal with indexes (in a list, string, etc), then you could use range()
.
I hope this helps!
2 Likes
Thank you so much for explaining how to use range()!
1 Like
But can we reverse the loop? I mean can we make the loop go from right to left instead of left to right? If so, how to do that?
Yes. You can use the range()
function. You the order for the parameters? “Start, stop, step”. So, if you want to go from the right of a list, you can use:
range(end_of_list, beginning_of_list, step_number)
#end_of_list should be the correct list index to start at the index of the last element of the list
#beginning_of_list should be the correct index to have the last iteration iterating over the first element of the list
#step_number-the increments or decrements you want the loop to iterate in
Here is a good article on range()
.
2 Likes