-1

I'm trying to write a small program to calculate numbers from the user. There's also some conditions to check if the number is positive or the user just hits enter. For some reason, I can't get the data variable to convert into a float.

The error occurs on line 5 where I get the error "ValueError: could not convert string to float:" I've tried so many combinations now, and tried to search StackOverflow for the answer, but without any luck.

How can I convert the input into a float? Thanks in advance for any help!

sum = 0.0

while True:

    data = float(input('Enter a number or just enter to quit: '))

    if data < 0:
        print("Sorry, no negative numbers!")
        continue
    elif data == "":
        break
    number = data
    sum += data

print("The sum is", sum)

4 Answers4

1

Instead of having the user press enter to quit, you can instead write:

sum = 0.0

while True:
    data = float(input('Enter a number or "QUIT" to quit: '))

    if data.upper() != "QUIT":

        if data < 0:
            print("Sorry, no negative numbers!")
            continue
        elif data == "":
            break
        number = data
        sum += data

print("The sum is", sum)
TimRin
  • 77
  • 7
0

You can't convert an empty string to a float.

Get the user's input, check if it's empty, and if it's not, then convert it to a float.

John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

You can check if the data is empty before convert to float with this way:

sum = 0.0

while True:

    data = input('Enter a number or just enter to quit: ')

    if data != "":
        data = float(data);
        if data < 0:
           print("Sorry, no negative numbers!")
           continue
        number = data
        sum += data 
        print("The sum is", sum)
     else:
        print("impossible because data is empty")
PRVS
  • 1,612
  • 4
  • 38
  • 75
0

You have to first check for the empty string and then convert it to float.

Also you might want to catch malformed user input.

sum = 0.0

while True:

    answer = input('Enter a number or just enter to quit: ')

    if not answer:   # break if string was empty
        break
    else:        
        try:
            number = float(data)
        except ValueError:   # Catch the error if user input is not a number
            print('Could not read number') 
            continue
        if number < 0:
            print('Sorry, no negative numbers!')
            continue
        sum += data

print('The sum is', sum)

In python, empty things like '' compare like False, it's idiomatic to use this in comparisons with if not <variable> or if <variable>.

This also works for empty lists:

>>> not []
True

And for None

>>> not None
True

And pretty much everything else that could be described as empty or not defined like None:

MaxNoe
  • 14,470
  • 3
  • 41
  • 46
  • Since OP seems to be pretty new to Python, you might want to explain the `if not answer` idiom. – Jasper Feb 17 '16 at 21:32