Reputation: 25
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?
Upvotes: 1
Views: 65
Reputation: 3604
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))
Upvotes: 1
Reputation: 77837
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
Upvotes: 1
Reputation: 6112
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))
Upvotes: 3