1

I was under the impression that adding the following if statement in my while loop makes python pick only the odd values of i that are smaller than 7 and sums them. However, this is not the case.

Here's my code:

i = 0

sum = 0

while i < 7:

    if (i % 2) == 1:

        sum += i

        i += 1

I expect sum to be 9 but an infinite loop occurs, causing the sum to be infinite.

I can't seem to understand how. Any help is appreciated. Thanks in advance!

Moaz
  • 11
  • 1
  • 4
    You only increment `i` inside the `if`, so if the condition is not meant, `i` stays the same forever – Adam.Er8 Jun 25 '19 at 11:56

3 Answers3

1

You only increment i inside the if, so if the condition is not meant, i stays the same forever

i = 0

sum = 0

while i < 7:

    if (i % 2) == 1:

        sum += i

    i += 1

print(sum)

Output:

9

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
0

As you keep conditioning i % 2, but if it doesn't go through, the i never changes, it will always exit the if statement, to solve it:

i = 0

sum = 0

while i < 7:

    if (i % 2) == 1:

        sum += i

    i += 1

print(sum)

You have to unindent by 4 spaces your i += 1 line.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

For similar cases it is better to use for loop than while loop. Especially if you have long loops. link

sum = 0
for i in range(7):
    if (i % 2) == 1:
        sum += i
Robot Mind
  • 321
  • 1
  • 6