Write a program that will ask the user for the cost of a meal, compute the tip for the meal (18%), compute the tax on the meal (8.25%), and then displays the cost of the meal, the tip amount for the meal, the tax on the meal, and the total of the meal which is a sum of the cost, tip, and tax amount
Here is my code:
def get_cost():
meal = float(input('Enter cost of meal: '))
while meal < 0:
print('Not possible.')
meal = float(input('Enter cost of meal: '))
return meal
def compute_tip():
tip = get_cost()*.18
return tip
def compute_tax():
tax = get_cost()*.0825
return tax
def compute_grand_total():
total = get_cost() + compute_tip() + compute_tax()
return total
def display_total_cost():
meal1 = print('Cost:', format(get_cost(), '.2f'))
tip3 = print('Tip:', format(compute_tip(), '.2f'))
tax3 = print('Tax:', format(compute_tax(), '.2f'))
total2 = print('Total:', format(compute_grand_total(), '.2f'))
return meal1, tip3, tax3, total2
def main():
m, t, ta, to = display_total_cost()
print('Cost:' , format(m, '.2f'))
print('Tip:', format(t, '.2f'))
print('Tax:', format(ta, '.2f'))
print('Total:', format(to, '.2f'))
main()
Output on Python Shell:
Enter cost of meal: 19.95
Cost: 19.95
Enter cost of meal: 19.95
Tip: 3.59
Enter cost of meal: 19.95
Tax: 1.65
Enter cost of meal: 19.95
This may be a very simple fix but how can I fix this where it doesn't ask for meal again? I'm still starting out.
Call get_cost() once and assign it to a variable; then pass that as a parameter to the other functions.
def compute_tip(meal):
return meal * .18
def compute_tax(meal):
return meal * .0825
def display_total_cost():
meal = get_cost()
return meal, compute_tip(meal), compute_tax(meal), compute_grand_total(meal)
You are calling get_cost() over and over again internally and that's why you are unable to find where the problem is. See you call it only once in the display_total_cost function but you are calling some other functions like compute_tip,compute_tax and compute_grand_total where all of them are internally calling the get_cost() function and that's why the programme asks you for multiple inputs.
Now, as suggested by everyone else you can store the return value in a variable and then pass it to all the other functions as an argument.
You also have a trivial main function in your programme which does the same thing as the display_total_cost function.
meal1 = print('Cost:', format(get_cost(), '.2f')) this is not the correct syntax.You can not use print statement after the assignment operator i.e. = Even though it won't raise any errors but why would you write extra things when you could just do a print statement cause using a print statement with assignment operator won't assign the variable with a value.
You also have another trivial function compute_grand_total you need not call functions again and again just to calculate previously calculated values unless and until you have a memory bound and you can not store values.
Fix it the following way:
def get_cost():
meal = float(input('Enter cost of meal: '))
while meal < 0:
print('Not possible.')
meal = float(input('Enter cost of meal: '))
return meal
def compute_tip(meal):
tip = meal*.18
return tip
def compute_tax(meal):
tax = meal*.0825
return tax
def display_total_cost():
meal = get_cost()
print('Cost:', format(get_cost(), '.2f'))
tip = compute_tip(meal)
print('Tip:', format(tip, '.2f'))
tax = compute_tax(meal)
print('Tax:', format(tax, '.2f'))
print('Total:', format(meal + tip + tax, '.2f'))
display_total_cost()
Related
I'm very new to coding and I've managed to create the equation but I just can't wrap my head around the function side of things - The task is to create a menu which adds 20% VAT - 10% discount and 4.99 delivery fee - I was originally going to repeat the equation and change the price variable but a function would be much better and will require less coding but I just can't figure out how to perform it - Any help would be appreciated.
def menu():
print("[1] I7 9700k")
print("[2] GTX 1080 graphics card")
print("[3] SSD 2 Tb")
price = 399;
discount_percentage = 0.9;
taxed_percentage = 1.2;
Delivery_cost = 4.50;
Vat_price = (price*taxed_percentage)
Fin_price = (Vat_price*discount_percentage)
Final_price = (Fin_price+Delivery_cost)
print("Final price including delivery:", "£" + str(Final_price))
menu()
option = int(input("Enter your option: "))
while option != 0:
if option ==1:
print("I will add equations later :)")
elif option ==3:
print("I will add")
else:
print("You numpty")
print()
menu()
option = int(input("Enter your option: "))```
Since you already have a function for menu() I am going to assume the difficulty is in passing the values. You can define the function as follows:
def get_total_price(price, discount, tax, delivery_cost):
price *= tax
price *= discount
price += delivery_cost
return price
product_price = get_total_price(399, 0.9, 1.2, 4.50)
If the tax, discount and delivery are the same each time, you can hard-code those values into the function and only give the price as a variable as such:
def get_total_price(price):
price *= 1.2
price *= 0.9
price += 4.5
return price
product_price = get_total_price(399)
Hey, I am having trouble with calculating VAT on different prices. If
priceR250 then the VAT rate=7.5%. When I run
my code I receive None for the VAT amount.
item_price1 = int(input("Enter the item price: R "))
def vat_calc(price):
if price<100:
vat_amount=price*0.15
elif price>101 and price<249:
vat_amount=price*0.10
else:
vat_amount=price*0.075
print("VAT amount: R", vat_calc(item_price1))
You never return anything, add a return statement at the end of your function:
item_price1 = int(input("Enter the item price: R "))
def vat_calc(price):
if price<100:
vat_amount=price*0.15
elif price>101 and price<249:
vat_amount=price*0.10
else:
vat_amount=price*0.075
return vat_amount
print("VAT amount: R", vat_calc(item_price1))
You forgot to return the vat amount, add return vat_amount to the end of your function.
# Create a class called "Loan":
# Data fields in the Loan class include: Annual Interest Rate(Float),\
# Number of years of loan(Float), Loan Amount(Float), and Borrower's Name(string)
class Loan:
# Create the initializer or constructor for the class with the above data fields.
# Make the data fields private.
def __init__(self, annualInterestRate, numberOfYears, loanAmount, borrowerName):
self.__annualInterestRate=annualInterestRate
self.__numberOfYears=numberOfYears
self.__loanAmount=loanAmount
self.__borrowerName
# Create accessors (getter) for all the data fields:
def getannualInterestRate(self):
return self.__annualInterestRate
def getnumberOfYears(self):
return self.__numberOfYears
def getloanAmount(self):
return self.__loanAmount
def getborrowerName(self):
return self.__borrowerName
# Create mutators (setters) for all the data fields:
def setannualInterestRate(self):
self.__annualInterestRate=annualInterestRate
def setnumberOfYears(self):
self.__numberOfYears=numberOfYears
def setloanAmount(self):
self.__loanAmount=loanAmount
def setborrowerName(self):
self.borrowerName=borrowerName
# Create a class method: getMonthlyPayment -
def getMonthlyPayment(self,loanAmount, monthlyInterestRate, numberOfYears):
monthlyPayment = loanAmount * monthlyInterestRate / (1
- 1 / (1 + monthlyInterestRate) ** (numberOfYears * 12))
return monthlyPayment;
# Create a class method: getTotalPayment -
def getTotalPayment(self):
monthlyPayment = self.getMonthlyPayment(float(self.loanAmountVar.get()),
float(self.annualInterestRateVar.get()) / 1200,
int(self.numberOfYearsVar.get()))
self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
totalPayment = float(self.monthlyPaymentVar.get()) * 12 \
* int(self.numberOfYearsVar.get())
self.totalPaymentVar.set(format(totalPayment, '10.2f'))
def main():
loan1=Loan()
print(input(float("Enter yearly interest rate, for exmaple, 7.25: ", loan1.annualInterestRate())))
print(input(float("Enter number of years as an integer: ", loan1.getnumberOfYears())))
print(input(float("Enter loan amount, for example, 120000.95: ", loan1.getloanAmount())))
print(input(float("Enter a borrower's name: ", loan1.getborrowerName())))
print("The loan is for", loan1.getborrowerName())
print("The monthly payment is", loan1.getMonthlyPayment())
print("The total payment is", loan1.getTotalPayment())
print(input("Do you want to change the loan amount? Y for Yes OR Enter to Quit"))
print(input(float("Enter a new loan amount: ")))
print("The loan is for", loan1.getborrowerName())
print("The monthly payment is", loan1.getMonthlyPayment())
print("The total payment is", loan1.getTotalPayment())
main()
For some reason my program is not running. I'm trying to allow the user to change the loan amount and reprint the new loan information. I don't know what I'm doing wrong, and classes/OOP is new to me, so I'm struggling dearly as I've been doing procedural-only for the past year. I am aware that this is filled with numerous errors... but I have nowhere to begin. All the tutorials for classes online are extremely vague and theoretical, and do not broach specific examples/scenarios like the one I'm facing with.
Any help would be appreciated.
The error message generated by the interpreter is more than enough.
TypeError: __init__() takes exactly 5 arguments (1 given)
You need to pass whatever input you are taking from the user as arguments into the class constructor Loan(). The other methods are just for returning class variables, but all the initialization is done in your constructor.
Also, your constructor definition is wrong, correct this line :
self.__borrowerName=borrowerName
I am new to python and I am not sure where I am wrong with my code
I could really use help.
# this program will get hourly rate, pay rate validate.
# and then will calculate the gross pay.
pay = [7.50, 18.26]
time = [0, 41]
def main():
getRate(pay)
getHours(time)
grossPay(pay, time)
def getRate(pay):
pay_rate = float(input('Enter your hourly pay rate: '))
while pay_rate < 7.50 or pay_rate > 18.25:
print('Pay rate must be between $7.50 and $18.25')
print('Enter a valid pay rate.')
pay_rate = float(input('Enter your hourly pay rate: '))
def getHours(time):
get_hours = float(input('Enter hours worked: '))
while get_hours < 0 or get_hours > 40:
print('Hours must be between 0 and 40!')
print('Enter a valid number of hours.')
get_hours = float(input('Enter hours worked: '))
def grossPay(pay_rate, get_hours):
result = pay_rate * get_hours
print(result)
main()
In your functions, you never return the results of your pay rate or your hours.
Change your main function to include saving the return values, like
def main():
rate = getRate(pay)
hours = getHours(time)
grossPay(rate, hours)
And in your getRate and getHours functions, include a return statement of your pay_rate and get_hours variables, like
def getRate(pay):
pay_rate = float(input('Enter your hourly pay rate: '))
while pay_rate < 7.50 or pay_rate > 18.25:
print('Pay rate must be between $7.50 and $18.25')
print('Enter a valid pay rate.')
pay_rate = float(input('Enter your hourly pay rate: '))
return pay_rate # As you want to get the value captured back to where the function was called from
The error is caused by this line from grossPay:
result = pay_rate * get_hours
because you are calling grossPay like
grossPay([7.50, 18.26], [0, 41])
Your functions aren't doing what you think they do... you are passing an argument, and generating a new value, but you are not returning that value entered by the user.
I think you must redefine
def grossPay(pay_rate, get_hours):
for hrs, rate in zip(pay_rate, get_hrs):
result = hrs * rate
print(result)
I'm trying to create a program that asks for actual value of a piece of property and display the assessment value and property tax. The county collects property taxes on the assessment value of property, which is 60% of the property's actual value. The property tax is $.72 for each $100 of the assessment value.
Any suggestions on what I did wrong?
#Create a program that asks for th actual value of a piece of property
# and display tge assessnebt value and property tax.
ASSESSED_VALUE = .60
PROPERTY_TAX=.72 *(ASSESSED_VALUE/ 100.00)
def main():
property_value = float(input('Enter property value: '))
def calcu_value(property_value)
assessed_value = property_value *assessed_value
property_tax = property_value * property_tax
# display totals of
def display_calcu
print(property_value)
format ('total_sales tax, '.2f'))
print(property_tax)
format ('total_sales tax, '.2f'))
# Call the main function
main()
There are quite a few syntax problems. Simplifying a bit (and I'm just taking a quick run at this), try this:
#Create a program that asks for th actual value of a piece of property
# and display tge assessnebt value and property tax.
ASSESSED_VALUE = .60
PROPERTY_TAX=.72 *(ASSESSED_VALUE/ 100.00)
def main():
property_value = float(input('Enter property value: '))
assessed_value = property_value * ASSESSED_VALUE
property_tax = property_value * PROPERTY_TAX
print("Property value: {}".format(property_value))
print("Property tax: {}".format(property_tax))
print("Assessed value: {}".format(assessed_value))
# Call the main function
main()
That runs without errors, at least.