End-To-End Example: Tip Calculator

The following code calculates the amount of tip you should leave based on the amount of the check and percentage you would like to tip.


In [1]:
total = float(input("Enter Amount of Check: "))
tip = float(input("Enter the Tip Percentage: "))
tip_amount = total * tip
print ("You should leave this amount for a tip $%.2f" % (tip_amount))


Enter Amount of Check: 100
Enter the Tip Percentage: 15
You should leave this amount for a tip $1500.00

The Issues

The issue with this program is that its not smart with the tip percentage. When I enter 15 is assumes 1500% not 15%.

With our knowledge of strings and parsing we can make this program more intelligent:

  • When you enter 0.15 it uses 0.15
  • When you enter 15 it assumes you meant 0.15 (divides by 100)
  • When you enter 15% it assumes you meant 0.15 (removes the %, then divides by 100)

Likewise we should do the same for currency input. Assuming the user might enter a $


In [3]:
# exploring how to parse percentages
x = "15 %"
y  = float(x.replace('%',''))
if y >=1:
    y = y/100
print(y)


Out[3]:
0.15

In [4]:
## Function: percentage - parses string input into a float as a percentage
## Arguments: text
## Returns float
def percentage(text):
    number = float(text.replace('%',''))
    if number >1:
        number = number /100
    return number

## Function: currency - parses string input into a float as currency
## Arguments: text
## Returns float
def currency(text):
    number = float(text.replace('$',''))
    return number

In [7]:
total = currency(input("Enter Amount of Check: "))
tip = percentage(input("Enter the Tip Percentage: "))
tip_amount = total * tip
print ("You should leave this amount for a tip $%.2f" % (tip_amount))


Enter Amount of Check: 100
Enter the Tip Percentage: .15
You should leave this amount for a tip $15.00

In [ ]: