In this post we are going to discuss how you can find the sum of numbers between 1 to 100 using a while loop in Python:
Simple code:
num = 1
total = 0
while num <= 100:
total += num
num += 1
print(total)
Output:
5050
Code with comments:
#initialize the starting number and total to 0
num = 1
total = 0
#continue looping until the number reaches 100
while num <= 100:
# add the current number to the total
total += num # we can also use total = total + num
# increment the number by 1
num += 1
#print the final total
print(total)
Output:
5050
In the above code, we initialize the starting number and total it to 0.
We then use a while loop to continue adding numbers from 1 to 100 to the total variable. We increment the number by 1 at each iteration of the loop, and continue until we reach 100.
Finally, we print the total value, which is the sum of all the numbers between 1 and 100 using a while loop in python.
Discover more from Python Mania
Subscribe to get the latest posts sent to your email.