0
print('Input a list of numbers to do statistics on them. Type stop to end the list.')

while True:
    number_list = []
    stop_input = False

    while stop_input == False:
        user_input = input('-> ')

        if float(user_input):
            number_list.append(user_input)                    

        elif user_input == 'stop':
            stop_input = True

    print('Sum:', sum(number_list))

The error is as follows:

if float(user_input):

ValueError: could not convert string to float: 'stop' (line 10).

I am typing input in as

1.0

2.0

3.0

stop

2
  • 1
    A couple of things: you don't need to compare with boolean, that's the point. Just do if not stop_input instead of if stop_input == False. Moreover, your error comes from your input: if you try to enter letters, the function to convert your input to float (a decimal number) will fail. So you need to either catch the exception, or change your logic. Commented Apr 16, 2018 at 20:46
  • 1
    float("Not a float literal") will raise an exception, not return False. You'll have to catch it. Commented Apr 16, 2018 at 20:46

1 Answer 1

2

float('stop') will raise an exception that you have to catch with a try: ... except ...: ... block.

Additionally, float(user_input) evaluates to False when user_input is 0.0 (or 0), so that number would never be added to the list.

You can change:

if float(user_input):
    number_list.append(user_input)

elif user_input == 'stop':
    stop_input = True

to:

try:
    number_list.append(float(user_input))
except ValueError:
    if user_input == 'stop':
        stop_input = True

to fix your program.

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

1 Comment

Just want to add that the Boolean type is a subclass of the int class (since Python 2.3). That's why float(user_input) evaluates to False in an if-statement when it's value is 0.

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.