top of page
Writer's pictureHSS

Introducing for loop in python

Imagine you are calculating the sum from 1 to 54321. Even if you know the shortcut or have the calculator, I’m sure it will take you a while to get the right answer. However, if you let the computer do the job, it will almost give you the answer immediately, and the same thing applies to basically all sequences and series problems. As long as we know the math formula, we can just let the computer do the calculation. It’s not only efficient but also promising you a correct answer, as long as the input code is flawless.


That brings us to today’s topic, writing a for loop in a programming language. For loop is simply a statement that allows the code to repeat itself until a certain condition is satisfied. For example, I want to calculate the sum of 1 to 10, so I will make the loop repeat itself 10 times, and each time, the current number will be added to the previous sum.


In Python, it is written as:


sum = 0 // declaring a variable that stores the current sum


For i in range(11): // the condition that needs to meet in order to execute the for loop

sum+=i // the variable “sum” adds the current value of i each time

print(sum) // print the result






This can be explained as: at first, the sum starts at 0, and the first value of i is also 0, so when sum+i (0+0), the answer is still 0. Then i becomes 1, and since “i” is still smaller than 11, the for loop will run again, and this time, i becomes 1 instead of 0. Therefore, sum+i (0+1) makes sum=1. Then i becomes 2, and since 2 or i is still smaller than 11, the for loop will repeat again. This time, sum = 1, and i = 2, so sum+i (1+2) = 3, and so on. The loop will stop repeating itself when i is no longer smaller than 11, then it will execute the next line, printing out the value of “sum”


22 views0 comments

Recent Posts

See All

Comments


Post: Blog2 Post
bottom of page