JayOsso
JayOsso

Reputation: 3

Changing condition statement from x >= 0 to x > 0

Just going through a Python 3.x self-study book. I've got a basic code, which allows user to enter a sequence of nonnegative int. When the user inputs a negative int, the sequence stops and a result is printed. It looks like that:

entry = 0
sum = 0
print("Enter numbers to sum, negative number ends list: ")

while entry >= 0:
    entry = int(input())
    if entry >= 0:
        sum += entry
print("Sum =", sum)

Now I got to a exercise questions part of the book. It asks if the condition of the if statement could have used

> 

instead of

>= 

Also if the condition of the while loop could use >

instead of

>=.

I have obviously tried both combinations and noticed that the > could be used in the if condition instead of >=, which would not affect the program. But if I would swap the >= for > in while statement the program would stop right after running it, showing Sum=0, not allowing the user to input any integers. Why swapping if condition doesn't change anything, but swapping while condition affects the program?

Upvotes: 0

Views: 61

Answers (2)

ElmoVanKielmo
ElmoVanKielmo

Reputation: 11316

Changing

if entry >= 0:
    sum += entry

into

if entry > 0:
    sum += entry

won't change the behavior of the program since adding 0 to any number doesn't change the value.
Changing while entry >= 0 into while entry > 0 would break the program because the loop would never be entered with the intialization of entry = 0.

Upvotes: 1

MatsLindh
MatsLindh

Reputation: 52862

If you read each statement in sequence, you can probably see what happens:

entry = 0

Entry is zero ...

while entry > 0:

While entry is larger than zero, do this ..

But since entry isn't larger than zero, the while loop never runs. The statement is checked before the loop is invoked the first time, so your program continues with the next statement (print) instead.

When you have >=, you also allow the value 0 - so "While entry is larger than, or equal to, zero" allows the loop to run.

Upvotes: 1

Related Questions