Python: String will not convert to float -
i wrote program few hours ago:
while true: print 'what me double?' line = raw_input('> ') if line == 'done': break else: float(line) #doesn't seem work. why? result = line*2 print type(line) #prints string? print type(result) #prints string? print " entered value times 2 ", result print 'done! enter close' as far can tell, should working fine.the issue when input value, example 6, receive 66 instead of 12. seems portion of code:
float(line) is not working , treating line string instead of floating point number. i've been doing python day, rookie mistake. help!
float(line) not convert in-place. returns float value. need assign float variable.
float_line = float(line) update: better way first check if input digit or not. in case not digit float(line) crash. better -
float_line = none if line.isdigit(): float_line = float(line) else: print 'error: input needs digit or float.' note can catching valueerror exception first forcefully converting line , in except handle it.
try: float_line = float(line) except valueerror: float_line = none any of above 2 methods lead more robust program.
Comments
Post a Comment