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))
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:
0.15
it uses 0.15
15
it assumes you meant 0.15
(divides by 100)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]:
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))
In [ ]: