Python while Method for Calculating Odd Sums Within 100

  • 2021-06-28 12:56:56
  • OfStack

As follows:


sum = 0
n = 99
while n > 0:
  sum = sum + n
  n = n - 2
print(sum)

As long as the condition is satisfied, the cycle will continue and exit when the condition is not satisfied.For example, if we want to calculate the sum of all odd numbers within 100, we can use the while loop:

In the loop the internal variable n decreases continuously until it becomes -1, the while condition is no longer satisfied, and the loop exits.


#100 Sum of odd numbers within 
sum = 0
for i in range(0,100):
  if i%2==1:
    sum += 1
print(sum)
 

Related articles: