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!

1
  • 4
    You only increment i inside the if, so if the condition is not meant, i stays the same forever Commented Jun 25, 2019 at 11:56

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.