-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)
3
  • In the interpreter, practice calling float(str) with different strings. You need to understand when it works and when it raises this error. Commented Feb 17, 2016 at 21:24
  • For some reason, I can't see a question here. Commented Feb 17, 2016 at 21:25
  • Good point @Jasper! I've now added a question in the post. Commented Feb 17, 2016 at 21:36

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

@Jasper If you get a ValueError, you still need to check whether it was due to an empty input or some other bogus value, because an empty input is the special case for terminating the loop. So I'll stick with my answer.
Thanks for your feedback! How do I check if it's empty?
Look at @MaxNoe's answer.
Oh, you're right. Check for empty, then convert in a try: ... except: block.
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")

Comments

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:

1 Comment

Since OP seems to be pretty new to Python, you might want to explain the if not answer idiom.

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.