trying to fix this code for tipping.
Let's add a tipping function. I've created the bare-bones of the function, which will take in the cost of the meal, and ask for a percentage to tip on the meal. You do the rest!
def tip(cost):
percentage = input("What percent would you like to tip? ")
tip = round(cost * percentage, 2)
print("The tip amount of", percentage, "% is ", tip)
return tip
the first part does not seem to work
after that, I run
cost, items = order(menu)
print("Your order is", items)
cost = round(cost + tax("vt", cost, tax_rate), 2)
cost = round(cost + tip(cost), 2)
print("Your total cost is", cost)
You have to convert the input to float in order to perform mathmatical operation . Otherwise it will multiply the string with number and return a repeated string.
def tip(cost):
percentage = float(input("What percent would you like to tip? "))
tip = round(cost * percentage, 2)
print("The tip amount of", percentage, "% is ", tip)
return tip
Related
I'm trying to write a small program that calculates the discount of a coupon and then return the total with a 6% sales tax applied. I've done some searching, but I think I'm having trouble understanding the placement of the syntax. If there's a more direct answer already posted, I'll take the link! Thanks in advance.
#Apply discount amount to item price and return with 6% sales tax
#Function to perform discount calculation
def calcDisc():
newTotal = iPrice * (iDisc / 100)
print('The new total is: ', newTotal)
return newTotal
#Function to show total with 6% sales tax
def calcDiscPlusTax():
taxTotal = newTotal * 0.6
print('The total with tax is: ', taxTotal)
#Variable for item price
iPrice = float(input('Please enter the item price: '))
#Variable for item with discount applied
iDisc = float(input('Please enter the discount amount: '))
calcDisc()
calcDiscPlusTax()
As a general rule, values that you use inside the function should be parameters to the function, just like values that you need to return to the caller should be returned by the function. For example:
#Apply discount amount to item price and return with 6% sales tax
#Function to perform discount calculation
def calcDisc(iPrice, iDisc):
newTotal = iPrice * (iDisc / 100)
print('The new total is: ', newTotal)
return newTotal
#Function to show total with 6% sales tax
def calcDiscPlusTax(newTotal):
taxTotal = newTotal * 0.6
print('The total with tax is: ', taxTotal)
At the time you call the function, you pass it arguments that tell it what values to use for its defined parameters:
#Variable for item price
iPrice = float(input('Please enter the item price: '))
#Variable for item with discount applied
iDisc = float(input('Please enter the discount amount: '))
newTotal = calcDisc(iPrice, iDisc)
calcDiscPlusTax(newTotal)
The arguments and parameters don't need to have the same names; the parameter is used inside the function definition, and the argument is a value that exists outside of it (in the scope where the function is called). So you can also call your functions with different variable names:
#Variable for item price
price = float(input('Please enter the item price: '))
#Variable for item with discount applied
discount = float(input('Please enter the discount amount: '))
subtotal = calcDisc(price, discount)
calcDiscPlusTax(subtotal)
or even no variable names at all:
calcDiscPlusTax(
calcDisc(
float(input('Please enter the item price: ')),
float(input('Please enter the discount amount: '))
)
)
OK, so first things first, you're calling your functions, but you're not passing values to those functions, so when you calculate something in your functions it will be lost after their execution ends.
calcDist uses iPrice and iDisc variables, however those variables does not exist in that space. Solution to this could be:
def calcDisc(price, disc):
total = price * (disc / 100)
print('The new total is: ', total)
return total
In the calcDiscPlusTax() you're using newTotal but that function does not know what's that:
def calcDiscPlusTax(total):
taxTotal = total * 0.6
print('The total with tax is: ', taxTotal)
So while calling those functions you have to pass parameters to them, to let them know about values you provided:
total = calcDisc(iPrice, iDisc)
calcDiscPlusTax(total)
Also, the function arguments don't have to be the same name as the parameters, please take a look at how I've called calcDisc (with iPrice, iDisc), and how I retrieve arguments in the function (just price and disc, but could be num1 and num2 as well)
You can find more by searching for python variable scope
As a side note, please rename functions and variables according to Python guidelines, which will be new_total, calc_disc_plus_tax, calc_disc, and so on.
If you define a variable outside of a function, it won't know what that is within a function unless you provide it as a variable
A = 5
def SomeFunction():
print(A)
Will actually throw an error because the SomeFunction doesn't actually have access to information outside of itself. Think about your functions as being a separate room, if you need something from the living room - you need to go get it and bring it in. So in your case, you've defined iPrice and iDisc, but your functions don't have access to that data. There's a couple ways to fix it. The first being providing them as variables:
#Function to perform discount calculation
def calcDisc(iprice,idisc):
newTotal = iPrice * (iDisc / 100)
print('The new total is: ', newTotal)
return newTotal
#Function to show total with 6% sales tax
def calcDiscPlusTax(newtotal):
taxTotal = newTotal * 0.6
print('The total with tax is: ', taxTotal)
#Variable for item price
iPrice = float(input('Please enter the item price: '))
#Variable for item with discount applied
iDisc = float(input('Please enter the discount amount: '))
NewTotal = calcDisc(iPrice,iDisc)
print( calcDiscPlusTax(NewTotal) )
So here what we've done is add in variables to our functions and we're passing those inputs into them, recording the output to NewTotal, and then passing that value as a variable to the calcDiscPlusTax.
However, there is another option --- check "globally" for the variables. For this approach, what we do is tell the function to essentially "go look outside for a variable called xyz and remember it", which would look like:
#Function to perform discount calculation
def calcDisc():
global iPrice,iDisc
newTotal = iPrice * (iDisc / 100)
print('The new total is: ', newTotal)
return newTotal #<--- NOTE*
#Function to show total with 6% sales tax
def calcDiscPlusTax():
global newTotal
taxTotal = newTotal * 0.6
print('The total with tax is: ', taxTotal)
NOTE* However, keep in mind that when you 'return' something from a function, it doesn't create a variable -- it just sends that info out. So, make sure when you 'return newTotal' that you have a variable to record that output. I added that in the other example but that would look something like
#Function to perform discount calculation
def calcDisc():
global iPrice,iDisc
newTotal = iPrice * (iDisc / 100)
print('The new total is: ', newTotal)
return newTotal
someVariableName = calcDisc()
And now you can use your output data anywhere! :)
I am trying to build a future value calculator using inputs but running into trouble with the math. Can someone please advise on a solution? Also, how could I convert the responses into integers or floats before calculating?
present= input("What is the present value?")
rate = input("What is the rate of return?")
periods = input("What is the number of periods?")
answer = {present} * (1 + {rate} ** {periods})
print(f"The future value is", int(answer))
Just put float around them (a decimal number)
present= float(input("What is the present value?"))
rate = float(input("What is the rate of return?"))
periods = float(input("What is the number of periods?"))
answer = present * (1 + rate ** periods)
print(f"The future value is", str(answer))
You need to convert your inputs to numbers (either float or int) before doing math on them. The curly-brace syntax isn't needed when you're doing math operations (in that context it's interpreted as a set literal, which is not what you want here), but it is used within f-strings to format variables as strings.
present= float(input("What is the present value?"))
rate = float(input("What is the rate of return?"))
periods = int(input("What is the number of periods?"))
answer = present * (1 + rate) ** periods
print(f"The future value is {answer}")
(edit) also, I think you want to raise (1 + rate) to the power of periods rather than the way you had the parentheses.
you can use int() to convert input into integer.
present= int(input("What is the present value?"))
rate =float( input("What is the rate of return?"))
periods = int( input("What is the number of periods?"))
answer = present * (1 + rate ** periods)
print(f"The future value is", int(answer))
The first thing to note is that your formula for future value is incorrect. It should be pv*(1+r)^n, rather than pv*(1+r^n). This is assuming your rate (r) corresponds to the rate for each period.
Here some quick code that does what you are probably looking for:
pv = float(input("what is the pv? "))
r = float(input("what is the rate? "))
n = float(input("how many periods? "))
print("The future value is {}".format(pv*(1+r)**n))
Output:
what is the pv? 1
what is the rate? 0.05
how many periods? 10
The future value is 1.628894626777442
I created a program that calculates how much money is saved after a "percentage off" is applied. The user is able to input the price of the product as well as the percentage off. After the program does the calculation, how do I continuously loop the program so that the user can keep using it without me having to click "run" each time in the console.
def percent_off_price():
price = amount * percent
amount = float(input('Enter the price of your product: '))
percent = float(input('Enter the percentage off: '))
price = amount * percent
print('You will save $',price,'off! Your total is: $',amount - price,)
Put the whole code segment in a while loop which runs always but it is the worst thing you would want:
while True:
amount = float(input('Enter the price of your product: '))
percent = float(input('Enter the percentage off: '))
price = amount * percent
print('You will save $',price,'off! Your total is: $',amount - price,)
You can also put a check to run it for controlled amount. Hence it would only run if the amount entered is a positive value:
flag= True
while flag:
amount = float(input('Enter the price of your product: '))
if amount <0:
flag=False
percent = float(input('Enter the percentage off: '))
price = amount * percent
print('You will save $',price,'off! Your total is: $',amount - price,)
Lastly if you want to run it for a fixed no. of times (Let's say 10) you can go for a for loop:
for i in range(10):
amount = float(input('Enter the price of your product: '))
percent = float(input('Enter the percentage off: '))
price = amount * percent
print('You will save $',price,'off! Your total is: $',amount - price,)
You can do:
while True:
percent_off_price()
I didn't have any problems writing this much, but the output numbers are a little wonky. Sometimes I'll get something like 83.78812, for example, and I'd rather round it up to 83.79.
Here's the code itself:
#This is a simple tax calculator based on Missouri's tax rate.
while True:
tax = 0.076
cost = float(raw_input("How much does the item cost? $"))
taxAmount = tax * cost
final = taxAmount + cost
if cost > 0:
print "Taxes are $" + str(taxAmount) + "."
print "The total cost is $" + str(final) + "."
else:
print 'Not a valid number. Please try again.'
I've seen people mention that I should be using ints instead of floats, but my tax-rate is over three characters past the decimal. Furthermore, typing in a string results in an error that crashes the program, but I'd rather it simply give an error message and loop back to the beginning. I don't know how to fix either of these things.
"typing in a string results in an error that crashes the program, but I'd rather it simply give an error message and loop back to the beginning."
To do this, you can use a while loop with try & catch That will keep on prompting for the item cost until it gets appropriate value
Use round() method to round up your value. It takes two parameters, first one is the value and second one is the position where to round up.
Format your result with python string formatting using the placeholder %.2f (2 digits after decimal point)
tax = 0.076
cost = 0
parsed = False
while not parsed:
try:
cost = float(raw_input("How much does the item cost? $"))
parsed = True
except ValueError:
print 'Invalid value!'
taxAmount = tax * cost
final = taxAmount + cost
if cost > 0:
print "Taxes are $%.2f." % round(taxAmount, 2)
print "The total cost is $%.2f." % round(final, 2)
else:
print 'Not a valid number. Please try again.'
You should use round:
round(final,2)
relatively new to programming in python, thank you for all the fast help that was provided on my last question I had on another python project. Anyways, Ive written a new program for a project in python that produces a bill for a catering venue. This is my code below, everything runs fine, and I get the intended results required for the project, The two problems I am experience are, 1. I need the cost of the desert to not print---> 3.0 but ---> $3.00, essentially, how can I print dollar signs, and round e.x 3.0 --> 3.00, or 45.0--> 45.00..and with dollar signs before prices. Sorry if something like this has been asked..
import math
# constants
Cost_Per_Desert = 3.00
Tax_Rate = .075
Gratuity_Tips = .15
Adult_Meal_Cost = 12.75
Child_Meal_Cost = .60*12.75
Room_Fee = 450.00
Less_Deposit = 250.00
def main():
# Input Section
Name = input("\n\n Customer:\t\t\t ")
Number_Of_Adults = int(input(" Number of Adults:\t\t "))
Number_Of_Children = int(input(" Number of Children:\t\t "))
Number_Of_Deserts = int(input(" Number of Deserts:\t\t "))
print("\n\nCost Of Meal Per Adult:\t\t" , Adult_Meal_Cost)
print("Cost of Meal Per Child:\t\t" , round(Child_Meal_Cost,2))
print("Cost Per Desert:\t\t" , round(Cost_Per_Desert,2))
# Processing/Calculations
Total_Adult_Meal_Cost = Adult_Meal_Cost* Number_Of_Adults
Total_Child_Meal_Cost = Child_Meal_Cost* Number_Of_Children
Total_Desert_Cost = Cost_Per_Desert* Number_Of_Deserts
Total_Food_Cost = Total_Adult_Meal_Cost + Total_Child_Meal_Cost + Total_Desert_Cost
Total_Taxes = Total_Food_Cost * Tax_Rate
Tips = Total_Food_Cost * Gratuity_Tips
Total_Bill = Total_Food_Cost + Total_Taxes + Tips + Room_Fee
# Output Section
print("\n\n Total Cost for Adult Meals: \t", Total_Adult_Meal_Cost)
print(" Total Cost for Childs Meals: \t", Total_Child_Meal_Cost)
print(" Total Cost for Desert: \t", Total_Desert_Cost)
print(" Total Food Cost: \t\t", Total_Food_Cost)
print("\n\n Plus 7.5% Taxes: \t\t", round(Total_Taxes,2))
print(" Plus 15.0% Tips: \t\t", round(Tips,2))
print(" Plus Room Fee: \t\t", Room_Fee)
print("\n\n Total Bill: \t\t\t", round(Total_Bill,2))
print(" Less Deposit: \t\t\t", Less_Deposit)
print("\n\nBalance Due: \t\t\t", round(Total_Bill - Less_Deposit,2))
print("\n\n\n\n\t\t Thank You For Using Passaic County Catering Services. ")
main()
input("\n\n\n\n\nPress Enter to Continue")
Let's say cost of desert is $3.00
cost = 3
print("${0:.2f}".format(cost))
Output:
$3.00
When you need to add a $ sign you just simply put a $ sign in your string.
If you would like to fix the decimal number places you just need basic string formatting, like:
print('pi is %.2f' % 3.14159)
and the output would be pi is 3.14
You might wanna like to read: https://docs.python.org/2.7/library/string.html#formatspec