Siris Ruchal
Siris Ruchal

Reputation: 13

While loop with if statement

I am combining a while-loop with an if-statement to add a number from 0-24 if the number is even. I constantly go to an infinite loop.

 number = range(0,50)
 i = 0
 total = 0

 while number[i]<25:
     if number[i]%2==0:
         total+=number[i]
         i+=1
     print(total)

Upvotes: 0

Views: 49

Answers (1)

terolog
terolog

Reputation: 36

The problem is, that you are adding 1 to i inside the if statement. You could simplify your code like this:

total = 0
for i in range(0, 25):
    if i % 2 == 0:
        total += i
print(total)

Upvotes: 1

Related Questions