0

I am supposed to have a while loop that asks for a number until the number is a negative. Then I am supposed to get a total of all of the numbers EXCEPT the negative number. As of right now my program adds up the absolute value of all the numbers input. any suggedtions on how to add all BUT the negative?

number=float(input("Enter a number: "))
total=number
while number>=0 and number<=100:
    number=float(input("Enter a number: "))
    total+=abs(number)
5
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by pyTony
0

You can put an "if" statement right above the addition that checks the value again.
...or you can redesign how you evaluate the terminating number.

0

You must also validate input:

total = 0.0
while True:
    reply = input("Enter a number: ")
    try:
        number = float(reply)
    except ValueError:
        print("Invalid value")
    else:
        if 0 <= number <= 100:
            total += number
        else:
            break
print("The sum is {0:.2f}.".format(total))

Edited by Gribouillis: n/a

0

Your original code would look something like this, but take note of the try/except as that is usual way of getting input.

number=0
while number>=0 and number<=100:
    ## will only add to total if the input from the previous loop is 0 <= number <= 100
    total+=abs(number)     ## adds number==zero on the first pass
    number=float(input("Enter a number: "))

Edited by woooee: n/a

0
number=0
while number>=0 and number<=100:
    ## will only add to total if the input from the previous loop is 0 <= number <= 100
    total+=abs(number)     ## adds number==zero on the first pass
    number=float(input("Enter a number: "))

The abs does not belong in loop, as the number is checked in range by while condition.

number=0
while number>=0 and number<=100:
    ## will only add to total if the input from the previous loop is 0 <= number <= 100
    total+=number     ## adds number==zero on the first pass
    number=float(input("Enter a number: "))

And this would crash when user inputs 'lOO', which Gribouillis' try..except would catch.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.