For Python Beginners — The Art of Accumulating and Regurgitating
Title sounds strange I know, but if you’re just getting started with learning Python, this might be a very important coding concept that you’ll see yourself using again and again. I’ve probably explained this hundreds of times to different students (sometimes the same student) and here it is so hopefully less tutors need to explain this again to their students!
Accumulating and Regurgitating in a Nutshell
We need to apply this concept if we want to accumulate multiple variables from a For loop or a While loop. Accumulation here can refer to sum of numbers, string concatenation, appending to a list etc etc.
Let’s say we want to find the sum of numbers from 1 to 10. This is how we can do this using this concept:
total = 0
for n in range(1, 11):
total += nprint(total)
1) Initialising the variable to be accumulated in
At the start, notice that I define total=0. As I know that my final output (sum of numbers from 1 to 10) is an integer, I create an empty integer outside of my for loop.