Reputation: 107
I have some code here meant to allow me to keep creating floats until I input 0 to have it stop (the 0 is then deleted). These floats are supposed to be entered into a list. The issue I'm having is that each time the while loop is run, the float_list is overwritten.
again = True
float_count = 1
while (again):
float_list = [float(input("Float%d: " % i))for i in range(float_count, float_count + 1)]
last_float = float_list[-1]
if (last_float == 0):
again = False
del float_list[-1]
else:
float_count = float_count + 1
Is there any way to alter this code so all of the floats are entered into a list? Thanks!
Upvotes: 1
Views: 98
Reputation: 30288
This maybe a good option to use the alternative form of iter(fn, sentinel)
, e.g.:
float_list = [float(x) for x in iter(input, '0')]
If you need the prompt then you can create a helper function:
import itertools as it
fc = it.count(1)
float_list = [float(x) for x in iter(lambda: input('Float{}: '.format(next(fc))), '0')]
Or alternatively (most closely matches OP's attempt - would exit on 0
, 0.0
, 0.00
, etc.):
fc = it.count(1)
float_list = list(iter(lambda: float(input('Float{}: '.format(next(fc)))), 0.0))
With error handling:
def get_float():
fc = it.count(1)
def _inner():
n = next(fc)
while True:
try:
return float(input("Float{}: ".format(n)))
except ValueError as e:
print(e)
return _inner
float_list = list(iter(get_float(), 0.0))
Upvotes: 2
Reputation: 27361
A list comprehension really isn't appropriate here. Much simpler:
float_count = 1
float_list = []
while True:
val = input("Float%d: " % float_count)
if val == '0':
break
float_list.append(float(val)) # call float(val) to convert from string to float
float_count += 1
it might be more user friendly to not crash if the user didn't type a float, e.g.:
def read_float(msg):
while 1:
val = input(msg)
if val == '0':
return val
try:
return float(val)
except ValueError:
print("%s is not a float, please try again.." % val)
def read_float_list():
float_count = 1
float_list = []
while True:
val = read_float("Float%d: " % float_count)
if val == '0':
break
float_list.append(val) # now val has been converted to float by read_float.
float_count += 1
Upvotes: 1