Week 2 - Section 1 - Controlling the flow v2
Chapter 3.7 - Calculating a sum
3.7 - Calculating a sum
A common operation in working with loops is to keep a running total. This “running total” code pattern is used a lot in this book. Keep a running total of a score, total a person's account transactions, use a total to find an average, etc. You might want to bookmark this code listing because we'll refer back to it several times. In the code below, the user enters five numbers and the code totals up their values.
print ("Calculation of the total of 5 numbers")
total = 0
for i in range(5):
new_number = int(input("Enter a number: " ))
total = total + new_number # or you can write total += new_number
print("The total is: ", total)
So how can we calculate this sum S=1+2+3+4+5+6+7+8+9+ ...... + 1000? What is the range of this numbers? Is it range(1000) or range (1,1001)? If you don't know try to find listing the range. Of course feel free to think something different
The commands are
>>>list(range(1000))
and
>>>list(range(1,1001))
A solution to the problem is :
print ("Calculation of the Sum of the 1000 first numbers")
total = 0
for i in range(1,1001): # or you can use range(1000) and add (i+1) to the total
total = total + i # or you can write total += i or total += i+1
print("The total is: ", total)
print ("What this program does?")
total = 0
for i in range(2,100,2):
# print ("The temporary total is : ", total)
# print ("The number i am going to add to the temporary total is :", i)
total += i
# print ("The temporary total after the addition of ",i, "is :", total)
# print()
print("The final total is: ", total)
Carefully remove the # signs and take care of indentation to see the program running and giving information about what is doing. This a form of debugging.
So this program calculated the sum of even numbers between 0 and 100. Can you modify it to calculate the odd numbers from 1 to 99? You need to change only one number, but you can find your own solution. The answer is 2500.