Here is what ive done:
food =["cheeseburger", "smallchips", "drink"]
prices =[2.50, 1.50, 1]
x=0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
I want to display an invoice at the end once the user has completed there order showing there total price.
This is some of my code for just the drinks, same type of code used for cheeseburger etc. :
while True:
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink = int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
break
You can use something like this:
from statistics import quantiles
from xml.etree.ElementPath import prepare_predicate
food =["cheeseburger", "smallchips", "drink"]
prices =[2.50, 1.50, 1]
x=0
price = 5
quantitydrink = 0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
print("10% GST applies to total amount (including both food and delivery)")
print("Delivery is free for food orders that are $30 or more")
print("Delivery cost is an additional $5 for food orders below $30\n")
while True:
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1 * quantitydrink
print(f"Your total cost is {price}!")
break
So the base price is 5 for the delivery and if you pick cola it adds the price of the cola multiplied by the amount you purchase to the price variable.
The += operator is best for this.
Changes:
price = 5 #added this on line 8 because the delivery cost is 5 so that is the base price
quantitydrink = 0 #added this on line 9 so you can add the amount to it later in the code
quantitydrink += int(input("How many would you like?\n")) # changed this in line 26 to add the amount you are ordering to the initial value.
price += 1 * quantitydrink # added this in line 36 to calculate the price based on how many colas you are ordering and the base price
print(f"Your total cost is {price}!") #added this at line 37 to print the final price of the order
hope this helps!
FINAL CODE WITH ALL FIXES:
from statistics import quantiles
from xml.etree.ElementPath import prepare_predicate
finished = False
food =["cheeseburger", "smallchips", "drink", "delivery"]
prices =[2.50, 1.50, 1, 5]
x=0
price = 5
quantitydrink = 0
quantityburger = 0
quantitychips = 0
quantitydelivery = 0
myorderfood=[]
myordercost=[]
print("Burgers\n")
print("Menu:")
print("Cheeseburger. Cost - $2.50 each")
print("Small chips. Cost - $1.50 each")
print("Drink - Cola only. Cost - $1.00 each\n")
print("10% GST applies to total amount (including both food and delivery)")
print("Delivery is free for food orders that are $30 or more")
print("Delivery cost is an additional $5 for food orders below $30\n")
name = input("What is your name?\n")
print("\nHello " + name + "\n")
while finished == False:
try:
burgerselect = input("Please select which burger:\n")
if burgerselect == "cheeseburger":
quantityburger += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if burgerselect != "cheeseburger":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 2.5 * quantityburger
try:
chipselect = input("Please select what size chips:\n")
if chipselect == "small":
quantitychips += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if chipselect != "small":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1.50 * quantitychips
try:
drinkselect = input("Please select which drink:\n")
if drinkselect == "cola":
quantitydrink += int(input("How many would you like?\n"))
except ValueError:
print("Not valid")
continue
if drinkselect != "cola":
print("Not on our menu!\n")
else:
print("good choice\n")
price += 1 * quantitydrink
deliveryselect=input('Would you like delivery? \n Yes: Delivery\n No: No delivery \n \n')
if deliveryselect=='Yes'or deliveryselect=='yes':
print('Thank You\n')
if price <= 30:
price += 5
elif price > 30:
price += 0
finished == True
break
elif deliveryselect =='No' or deliveryselect=='no':
print('Thank you\n')
finished == True
break
print(f"Your total cost is {price}!")
This is my current code for a tax calculator based on age. I think that it would be easier to update in the future if I used data structures when calculating the brackets. Could someone help me make sense of this?
while True: #Loop the whole program
from datetime import datetime, date #Get the Age of from user input
print("Please enter your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
def calculate_age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
age = calculate_age(date_of_birth)
print("You are " ,int(age), " years old.")
#Get the Salary from user input
def get_salary():
while True:
try:
salary = int(input("Please enter your salary: "))
except ValueError:
print("You need to enter a number ")
else:
break
return salary
#Calculate the Amount that needs to be paid, using if,elif,else
def contribution(age):
if age <= 35:
tax = (salary * 0.20)
elif 36 <= age <= 50:
tax = (salary * 0.20)
elif 51 <= age <= 55:
tax = (salary * 0.185)
elif 56 <= age <= 60:
tax = (salary * 0.13)
elif 61 <= age <= 65:
tax = (salary * 0.075)
else:
tax = (salary * 0.05)
return tax
#Print the amount
if __name__ == "__main__": # It's as if the interpreter inserts this at the top of your module when run as the main program.
salary = get_salary() #get salary from get_salary()
tax = contribution(age) #calculate the tax
print("you have to pay", tax, " every month ")
while True:
answer = str(input("Do you need to do another calculation? (y/n): "))
if answer in ("y", "n"):
break
print ("invalid input.")
if answer == "y":
continue
else:
print("Thank you for using this Calculator, Goodbye")
break
So the code that I'm assuming that I need to change is:
#Calculate the Amount that needs to be paid, using if,elif,else
def contribution(age):
if age <= 35:
tax = (salary * 0.20)
elif 36 <= age <= 50:
tax = (salary * 0.20)
elif 51 <= age <= 55:
tax = (salary * 0.185)
elif 56 <= age <= 60:
tax = (salary * 0.13)
elif 61 <= age <= 65:
tax = (salary * 0.075)
else:
tax = (salary * 0.05)
return tax
Also, I'm trying to learn so could you explain by putting #comments into the code :) Thank you!
1. Rewrite the code structure
First of all, I think most programmers do like to put function blocks all together and leave the main logic as clean/short as possible to improve readability. Therefore the 'code structure' like this could be hard to maintain or update in the future.
while True: #Loop the whole program
from datetime import datetime, date #Get the Age of from user input
def calculate_age(born): ...
def get_salary(): ...
def contribution(age): ...
if __name__ == "__main__":
# main logic
...
So this kind of structure is really weird, plus you have lots of variables (date_of_birth, age) declared between functions. Would be hard to do the update/maintenance.
If I were you, I'd firstly revise the code like this way
from datetime import datetime, date #Get the Age of from user input
def calculate_age(born): ...
def get_salary(): ...
def contribution(age): ...
if __name__ == "__main__": # It's as if the interpreter inserts this at the top of your module when run as the main program.
program_continue = 'y'
while program_continue.upper() in ['Y', 'YES']:
print("Please enter your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
age = calculate_age(date_of_birth)
print("You are " ,int(age), " years old.")
salary = get_salary() #get salary from get_salary()
tax = contribution(age) #calculate the tax
print("you have to pay", tax, " every month ")
program_continue = str(input("Do you need to do another calculation? (y/n): "))
print("Thank you for using this Calculator, Goodbye")
2. Introduce data structure? or class?
Honestly I don't quite understand what do you mean by "using data structure", so I guess make a "class" is the one you wish. Then you have to consider some points:
what should be the attributes for this class? dob, salary, anything else?
what will you expand in the future? name? gender? contact_info? handicapped or not?
Whatever, we just create a class with dob and salary for now.
class Person(object):
def __init__(self, dob, salary):
"""
input dob and salary only, age and tax will be calculated then
"""
self.dob = dob
self.salary = salary
self.age = self.calculate_age()
self.tax = self.contribution()
def calculate_age(self):
today = date.today()
return today.year - self.dob.year - ((today.month, today.day) < (self.dob.month, self.dob.day))
def contribution(self):
if self.age <= 35:
tax = (self.salary * 0.20)
elif 36 <= self.age <= 50:
tax = (self.salary * 0.20)
elif 51 <= self.age <= 55:
tax = (self.salary * 0.185)
elif 56 <= self.age <= 60:
tax = (self.salary * 0.13)
elif 61 <= self.age <= 65:
tax = (self.salary * 0.075)
else:
tax = (self.salary * 0.05)
return tax
So once you create a variable in the class Person, you can access the age, salary, tax via .age, .salary, .tax.
Please notice that I did not put the function get_salary() into the class since it's a function for "asking user's salary" and has nothing to do with the attribute.
The main logic can be rewritten to:
if __name__ == "__main__": # It's as if the interpreter inserts this at the top of your module when run as the main program.
program_continue = 'y'
while program_continue.upper() in ['Y', 'YES']:
print("Please enter your date of birth (dd mm yyyy)")
date_of_birth = datetime.strptime(input("--->"), "%d %m %Y")
salary = get_salary() #get salary from get_salary()
##### THESE ARE THE CHANGES START
person_obj = Person(date_of_birth, salary)
print("You are ", int(person_obj.age), " years old.")
print("you have to pay", int(person_obj.tax), " every month ")
##### THESE ARE THE CHANGES END
program_continue = str(input("Do you need to do another calculation? (y/n): "))
print("Thank you for using this Calculator, Goodbye")
3. Future expansion
Let's say if I want to add name as an attribute now. All I have to do is to modify the Person class. Should be easier for you to update in the future.
Your function is fairly easy to maintain, especially if you rewrite it a little simpler:
def contribution(age):
if age <= 35:
rate = 0.20
elif age <= 50:
rate = 0.20
elif age <= 55:
rate = 0.185
elif age <= 60:
rate = 0.13
elif age <= 65:
rate = 0.075
else:
rate = 0.05
return salary * rate
But you are right to be worried about embedding data in your code like this. So you may do better with something like this:
# near top or read from file:
tax_rates = [ # upper age limit for each rate
(35, 0.20),
(50, 0.20),
(55, 0.185),
(60, 0.13),
(65, 0.075),
(1000, 0.05)
]
# then elsewhere in the code:
def contribution(salary, age):
for limit, rate in tax_rates:
if age <= limit:
return salary * rate
else:
# finally a good use for for ... else!
raise ValueError(f"Age {age} is out of range.")
I would also recommend moving your import statements and function definitions above the main loop and passing values into the functions (e.g., salary) rather than using global variables. That will make it easier to see what is going on.
https://www.101computing.net/entry-fees-calculator-using-a-flowchart/
I was trying to do the coding challenge my school sent me (link attached above) and I got quite stuck so I was hoping if someone could help. I was stuck when trying to add the discount calculating part because I had to see if the price was more than 50 and if it was, apply a 5% discount to it
def ThemePark():
age = int(input('Enter age: '))
if age <= 15:
print("Your entry price is £11")
if age >= 15:
print("Your entry price is £13.50")
if age >= 18:
print("Your entry price is £15 ")
discount = get_discount(price1 + price2 + price3)
print_discount_message(discount)
price > 50
price1 = 11
price2 = 13.50
price3 = 15
price > 50
discountprice = calculate_discount_price(price, discount)
print(f' Your price: {discd} (original price: {price})')
def Discount(price):
if price > 50:
discount = 0.95
else:
discount = 0.0
return discount
def print_discount_message(discount):
if discount == 0.0:
print(' Not qualified for family discount.')
else:
print(' Qualified for discount: {}%'.format(int(discount * 100)))
def calculate_discount_price(original_price, discount):
return round(original_price - original_price * discount, 2)
if __name__ == '__main__':
while True:
ThemePark()
more = input('Buy more? (Yes/No): ')
if more != 'Yes':
break
def print_discount_message(discount):
if discount == 0.0:
print(' Not qualified for family discount.')
else:
print(' Qualified for discount: {}%'.format(int(discount * 100)))
To output the print(' Qualified for discount: {}%'.format(int(discount * 100)))
you should have:
print(' Qualified for discount: {}%'.format(int((1 - discount) * 100)))
can someone help me troubleshoot my code the reply from going through the code at the end just loops instead of begining the program again completely would be brilliant is someone could help me thanks and i know its very basic and maybe not the best way to do it but as long as it works its fine.
start = input("Do you want to make an order? ")
while start == "Y" or start == "y" :
title = input("Enter book title: ")
sPrice = float(input("Enter price of book: "))
voucher = input("Do you have a voucher? ")
while sPrice >0 :
amount = float(input("Enter amount of books: "))
while amount >= 1 and amount <= 80 :
if amount >= 5 and amount <= 10 :
disc = 5
elif amount >= 11 and amount <= 50 :
disc = 7.5
elif amount >= 51 and amount <= 80 :
disc = 10
else :
disc = 0
base = sPrice * amount
discVal = (base * disc) / 100
dPrice = base - discVal
if voucher == "Y" or voucher == "y" and dPrice >= 25 :
voucherValue = 25
else :
voucherValue = 0
fPrice = dPrice - voucherValue
print (f"Discount rate: {disc}%")
print (f"Discount value: £{discVal:.2f}")
print (f"Total before discount: £{base:.2f}")
print (f"Total after discount: £{dPrice:.2f}")
if voucher == "Y" or voucher == "y" and dPrice >= 25 :
print (f"Value of voucher: £{voucherValue:.2f}")
print (f"Final cost of order: £{fPrice:.2f}")
else :
print ("ERROR - Invalid amount!")
amount = float(input("Enter amount of books: "))
else :
print ("ERROR - Price too low!")
sPrice = float(input("Enter price of book: "))
else :
start = input("Do you want to make an order? ")
You need to include if at two place just to validate the input value.
Change while sPrice >0 : to if sPrice >0 : and line while amount >= 1 and amount <= 80 : to if amount >= 1 and amount <= 80 :
I'm pretty new to coding so bear with me but how do I make this code work? I'm trying to take the information that is entered by the user and input it into my functions so I can print the total.
def hotel_cost(nights):
return nights * 140
def plane_cost(city):
if city == "Atlanta":
return 220
elif city == "Boston":
return 550
elif city == "Chicago":
return 900
def rental_car_cost(days):
if days >= 7:
return days * 100 - 50
elif days >= 1 and days <= 5:
return days * 100 - 20
a = raw_input("Please choose number of nights: ")
b = raw_input("Please choose which city you are flying to (Atlanta, Boston, Chicago) ")
c = raw_input("Please choose days of rental car use: ")
d = raw_input("Please choose how much spending money you plan on spending: ")
a = nights
b = city
c = days
total = a + b + c + d
print "Your total cost of trip is %d" % total
You need to first convert your numeric input values to numbers and then pass your input values to your functions.
Delete the lines
a = nights
b = city
c = days
Calculate your total with
total = hotel_cost(int(a)) + plane_cost(b) + rental_car_cost(int(c)) + float(d)
I assumed that for the number of nights and rental car days only integers make sense.
I am not sure if this applies in Python version 2. However, you could try this:
a = int(raw_input("Please choose number of nights: ") * 140 )
# Multiplies by 140, but this would defeat the purpose of your functions.
And apply the int function to convert all of your inputs into integers.
You can use input() in Python 2 as it evaluates the input to the correct type. For the functions, you just need to pass your values into them, like this:
def hotel_cost(nights):
return nights * 140
def plane_cost(city):
if city == "Atlanta":
return 220
elif city == "Boston":
return 550
elif city == "Chicago":
return 900
def rental_car_cost(days):
if days >= 7:
return days * 100 - 50
elif days >= 1 and days <= 5:
return days * 100 - 20
nights = input("Please choose number of nights: ")
city = raw_input("Please choose which city you are flying to (Atlanta, Boston, Chicago) ")
rental_duration = input("Please choose days of rental car use: ")
spending_money = input("Please choose how much spending money you plan on spending: ")
total = hotel_cost(nights) + plane_cost(city) + rental_car_cost(rental_duration) + spending_money
print "Your total cost of trip is %d" % total