'Python Loop and Range function
Can anyone please explain this python code, how the answer is "5050" ?
total = 0
for number in range(0, 101):
total += number
print(total)
Solution 1:[1]
what happen is when run the this code is the for loop going to add the number to the total variable so in the first loop the total = 0 and the number = 0 so the total will equal to 0 in the second loop the total = 0 and the number = 1 so the total will equal to 1 in the second loop the total = 1 and the number = 2 so the total will equal to 3 and so on in the last loop : the total = 4950 and the number = 100 so the total will equal to 5050 and this is output you've got
hope you understood
Solution 2:[2]
total = 0
for number in range(0, 101):
total = total + number
Initially total equals 0, range function range function sorts values from 0 to 101. The for loop adds 1 to the total value in the first step, At this stage the total is equal to 1, In the next step, the number 2 comes from the range function and adds 2 to the total value. Total is equal to 3 in the final case. The number produced by the range function is added to the total value each time. This situation continues until the for loop is completed and in the last step the total equals 5050. I hope I was able to explain.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hamici Mossab |
Solution 2 | Onur Akyol |