Python Forum

Full Version: Help with simple tip calculator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can someone please fix my code for a simple tip calculator? I am new to Python.
price_meal = raw_input("How much did your meal cost?")
tip = raw_input("How much do you want to tip, in decimal form?")

price_meal += price_meal * tip
print "Your total cost is %s." % (price_meal)

Also how can I round the price of the meal after adding the tip to two decimal places? Thanks.
Please use python tags when posting code. I put them in for you this time. See the BBCode link in my signature below for instructions.

You need to convert your variables to numbers before you do math with them. In this case you should use float, as in float(price_meal) or float(tip). Note that you can put the float around the raw_input, to convert it as it is typed in.

I see from the raw_input that you are using Python 2.7 or lower. You should learn with Python 3. In just over a year support for 2.7 will stop.
Sorry missed the rounding question. You can round with the round function, as in round(price_meal, 2). However, I would use string formatting for this (%.2f instead of %s). But look into the format method of strings. It's newer, faster, and more powerful.
(Oct-23-2018, 01:32 AM)ichabod801 Wrote: [ -> ]Sorry missed the rounding question. You can round with the round function, as in round(price_meal, 2). However, I would use string formatting for this (%.2f instead of %s). But look into the format method of strings. It's newer, faster, and more powerful.

Thanks for answering. I was wondering, would %.2f work with the format method of strings? Or do I have to do it another way?
The format method would look like 'Your total cost is ${:.2f}.'.format(price_meal). You can see the full format method syntax here.
You should use a version so this work.
Which mean 3.6 or preferably 3.7.
price_meal = float(input("How much did your meal cost? "))
tip = float(input("How much do you want to tip, in decimal form? "))
price_meal += price_meal + tip
print(f'Your total cost is {price_meal:.2f}.')
f-string is the newest way.
Install for Windows Python 3.6/3.7 and pip installation under Windows,
for Linux so comes newer distros like Ubuntu 18.10 and Mint 19 with Python 3.6.5 as default install.