This forum is now read-only. Please use our new forums! Go to forums
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
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.
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
1 comments
Awesome! Thanks!