1
x=[]
while True:
    try:
        x.append(float(input('what are your numbers?\n')))
        if x.append('done'):
            break
    except:
        print('bad data')
        continue
print(len(x), sum(x), min(x), max(x))

In this code I want the user to provide numbers, skip strings and finally I want the loop when the user types in 'done' but it does not work, what am I doing wrong here?

0buz
  • 3,443
  • 2
  • 8
  • 29
Enrico
  • 25
  • 4
  • You cannot make a float of the string 'done' so the code goes to the except and continues looping – chatax Feb 21 '20 at 17:33
  • What do you expect `if x.append('done'):` to do? ` By the way, bare `except:` statements like this are bad practice, see https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except. – AMC Feb 21 '20 at 17:56

3 Answers3

3

Assign the input value to a variable first, so you can use it for the comparison and cast to float.

x=[]

while True:
    inp = input('what are your numbers?\n')
    if inp == 'done':
        break
    try:
        x.append(float(inp))   
    except ValueError:
        print('bad data')

print(len(x), sum(x), min(x), max(x))
alec
  • 5,799
  • 1
  • 7
  • 20
1

This code does not break when the input is `"done"

    if x.append('done'):
        break

This appends the string "done" to the list x. append returns None, so your condition is always False. break will work just fine -- you have to write your code to get there. Check the input for validity before you convert to float. During this process, check for "done":

    user_input = input('what are your numbers?\n')
    if user_input == "done":
        break
    # Continue checking the input
Prune
  • 76,765
  • 14
  • 60
  • 81
1

you need to check first if the input is 'done' before inserting to your list, because max will raise TypeError if any of list elements is not a number. Also continue is unnecessary in your implementation because it is last the statement in your loop:

x=[]
while True:
    try:
        data = input('what are your numbers?\n')
        if data == 'done':
            break
        else:
            num = float(data)
            x.append(num)
    except:
        print('bad data')

print(len(x), sum(x), min(x), max(x))
adnanmuttaleb
  • 3,388
  • 1
  • 29
  • 46