This forum is now read-only. Please use our new forums! Go to forums

banner
Close banner
0 points
Submitted by Juan Hidalgo
almost 10 years

Function to convert to float

I’m writing the tip calculator program, and want to add a function to convert the numbers to float, but it doesn’t seem to work:

meal = raw_input('Enter meal price: ')
def floatify(x):
try:
    x = float(x)
except:
    print 'Error, enter a numeric value'
    quit()
floatify(meal)
tax = raw_input('Insert tax: ')
floatify(tax)
tip = raw_input('Insert tip: ')
floatify(tip)
price = meal + (meal * tax) + (meal * tip)
print 'Your total cost is', price

When I call the function ‘floatify’, it looks like the “except” part is ok, so if I enter anything else than a number, the program quits. But it is not converting the number to a float, and I can’t find why

Any help?

Answer 536efc707c82ca2e96003611

1 vote

Permalink

with just calling floatify meal you are NOT changing the value of the meal-variable. meal = floatify(meal) does change it. Within your floatify definition you are NOT returning anything. so prior to your except include line: return float(x) But as i have been reading about this try/except/else business the question stands out: x=float(x) is not a test…. float(x) would be a test.

points
Submitted by Leon
almost 10 years

1 comments

Juan Hidalgo almost 10 years

Awesome! Thanks!