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)
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
I want to ask the user if they are members and if so, give them a 5% discount on the seats they have purchased, if they are not members, there is no discount. I also want to display that discounted price. Also, how would I go about adding up all the final prices and displaying those as well? I don't know where to start with this, any help is appreciated, thanks. There may be some formatting issues, but here is my code:
def main():
print("Your final price for Orchestra seats will be $",get_orchp())
print("Your final price for Center seats will be $",get_centerp())
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
discount = 0.5
disc = Finalorchp * discount
Findiscorchp = Finalorchp - disc
elif member == 'n':
print('There is no discount for non-members')
return Finalorchp
return findiscorchp
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
This is how I would resolve all of your questions:
def main():
orchp = get_orchp()
centerp = get_centerp()
print(f"Your final price for Orchestra seats will be ${orchp}")
print(f"Your final price for Center seats will be ${centerp}")
print(f'Your final price for all tickets is {orchp + centerp}')
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
Finalorchp *= .95
return Finalorchp
else:
print('There is no discount for non-members')
return Finalorchp
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
Please note these
I change the location of the calls to your functions and set a variable to receive them
I changed the prints for the final price to an f string to receive the variables from the functions
Changed Finalorchp to the pythonic version of variable = variable * .95 right under the if member statement
Changed the else statement in get_orchp to else in the event that the user doesn't only put y or n (you could add onto this to have fault tolerance of if it isn't y or n then do something else)
Added another final price print with an f string to add the two variables that receive the 2 variables from the functions.
This code does what you want.
you can see that in the code I have returned both price and discount amount from the getorchp() function as a tuple and using which I have printed the actual price and discount in the main function. If the user is not a member the discount will be zero and in the main function, I have added both orchestra seats and center seat price and printed the total final price. This code answers all questions you have asked
def main():
orc = get_orchp()
print("Your final price for Orchestra seats will be $",orc[0], " and discount is ", orc[1])
cen = get_centerp()
print("Your final price for Center seats will be $",cen)
print("total final price", orc[0]+cen)
def get_orchp():
ORCH_SEATS = 75
frontseats = float(input('Enter the number of Orchestra seats you want to purchase : '))
Finalorchp = ORCH_SEATS * frontseats
member = str(input('Are you a member of the local theater group? Enter y or n: '))
if member == 'y':
discount = 0.5
disc = Finalorchp * discount
Findiscorchp = Finalorchp - disc
return (Findiscorchp, disc)
elif member == 'n':
print('There is no discount for non-members')
return (Finalorchp, 0)
def get_centerp():
CENTER_SEATS = 50
middleseats = float(input('Enter the number of Center Stage seats you want to purchase : '))
Finalcenterp = CENTER_SEATS * middleseats
return Finalcenterp
main()
I am coding a program that simulates someone making a purchase in a grocery store. I am displaying all the products and the price and I am prompting the user to input all the products they went to buy separated by commas. I want the program to check if the input is in the dictionary of product and add it to the cart with the use of a loop. Before adding it to cart the program needs to check if the input is valid, meaning if the item is in the list of products to buy. When the user selects an item to buy, I want the program to ask the user for the quantity of that item, so how many of the item they want to buy. At the samThen the program will calculate the total of all the products, then calculate the tax value, 24% of the total, and then return a subtotal that includes tax. Here is what I have so far:
def calculatetotal(slist, produce):
# for each item on the shoping list look up the cost & calculate total price
item_price = 0
subtotal = 0
VAT = 0
final_total = 0
basket = {}
for item in slist:
item_price = produce.get(item)
basket[item] = item_price
subtotal = subtotal + item_price
basket["Subtotal"] = subtotal
#calculating VAT
VAT = subtotal * 0.24
basket["VAT"] = VAT
#calculating price with tax
final_total = subtotal + VAT
basket["Total"] = final_total
# print off results
return basket
def main():
# set up grocery list with prices
produce={"Rice":5.00, "Bread":2.00, "Sugar":1.5, "Apple":0.75, "Cereal":3.75, "Gum": 1.00, "Water": 1.75, "Soda": 2.00}
# process input from the user - get a shopping list
item = input("Please enter the items that you want to buy: ")
slist = []
while(item != 'stop'):
if not (item in slist):
slist.append(item)
item = input("Please enter the items that you want to buy: ")
result = calculatetotal(slist, produce)
print(result)
main()
I've gotten most of it, but the small changes that I mentioned above, I can't figure out what to do. I forgot to mention that asking for the quantity of the item and checking if the user input has to be done with a loop. Any input is very much appreciated. Please show the change of code. Thank you in advance.
In this case I would simply go for a while loop
while True:
item = input("Please enter the items that you want to buy: ")
if item == 'Stop':
break
elif item not in produce or item in slist:
# error message or whatever
else:
num = int(input("Enter Quantity"))
# other operations
I have a problem.
I want to display all my records in "view" command, but it only displays the last record.
How do I solve the problem?
Please help me , thank you!
my code:
initial_money = int(input('How much money do you have? '))
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global rec
rec = records[0]
global amt
amt = records[1]
global initial_money
initial_money += int(amt)
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
print('{name:<20s} {number:<6s}'.format(name = rec,number = amt))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
Output
How much money do you have? 100
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tomato -50
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
salary 100
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
salary 100
Now you have 150 dollars.
output I want:
------------------- ------
tomato -50
salary 100
Now you have 150 dollars.
I will use a dictionary to hold them instead:
initial_money = int(input('How much money do you have? '))
mr = {}
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global rec
rec = records[0]
global amt
amt = records[1]
global mr
global initial_money
mr[rec] = int(amt)
initial_money += mr[rec]
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
for r,a in mr.items():
print('{name:<20s} {number:<6s}'.format(name = r,number = str(a)))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
Test:
How much money do you have? 100
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
tomato -50
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
salary 100
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
tomato -50
salary 100
Now you have 150 dollars.
You need to make records into a list of the records you inserted. Currently you are overwriting it each time you call add.
make records an array outside your main loop
In your main loop push the results of the call to add into your array In your view function
you then need to loop over the array to view all the results.
Also for bonus, stop using global in your add function, It's considered bad form
So first I'm trying to make a class, which holds an item's name, price, and quantity available. Then I wanted to make a function that will deduct the quantity sold to a buyer after they enter the amount they are buying, and then calculate the total price.
Now to add on top of that, I am trying to have the user select from a list of items.
The problem is it seem I seem to be getting errors around the time the program starts running the 'buy' function.
class Retail:
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy (self):
print ("How many are you buying?")
quant = int(input("Amount: "))
unitsOnHand -= quant
subto = price * quant
total = subto * 1.08
print ("There are now ", unitsOnHand, " left")
print ("The total price is $", total)
box = Retail(4.95, 20, "Boxes")
paper =Retail(1.99, 50, "Big Stacks of Paper")
staples =Retail(1.00, 200, "Staples")
ilist = (box, paper, staples)
print ("Which are you buying? ", [box.description, paper.description, staples.description])
ioi = input("Please use the exact word name: ")
if ioi == 'box':
Retail.buy(ilist[0])
elif ioi == 'paper':
Retail.buy(ilist[1])
elif ioi == 'staples':
Retail.buy(ilist[2])
The error I get when I tried to run it is
Traceback (most recent call last):
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 22, in <module>
Retail.buy(ilist[0])
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 9, in buy
unitsOnHand -= quant
UnboundLocalError: local variable 'unitsOnHand' referenced before assignment
I'm guessing is that it doesn't see the values I already assigned to the item, and if that is the case, how do I get it to?
Others have pointed out your error, but the other thing that is wrong is your buy call needs to be done on an instance of the object, not the class itself. In other words, right now you are executing buy on the Retail class where you need to execute it on instance (objects) of the class.
I have another suggestion to help organize your code. Use a dictionary to map the keys to the various objects to make your loop a bit cleaner. Putting all that together (and some other checks), here is an updated version of your class:
class Retail(object):
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy(self):
if self.unitsOnHand == 0:
print('Sorry, we are all out of {} right now.'.format(self.description))
return
print("How many are you buying? We have {}".format(self.unitsOnHand))
quant = int(input("Amount: "))
while quant > self.unitsOnHand:
print('Sorry, we only have {} left'.format(self.unitsOnHand))
quant = int(input("Amount: "))
self.unitsOnHand -= quant
subto = self.price * quant
total = subto * 1.08
print("There are now {} left".format(self.unitsOnHand))
print("The total price is ${}".format(total))
return
stock = {}
stock['box'] = Retail(4.95, 20, "Boxes")
stock['paper'] = Retail(1.99, 50, "Big Stacks of Paper")
stock['staples'] = Retail(1.00, 200, "Staples")
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
while ioi not in stock:
print("Sorry, we do not have any {} right now.".format(ioi))
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
stock[ioi].buy()
i am just writing a simple currency converter program, and the one problem that i am facing is that i can't think how to have the user change the content of the variable. Below is an the basic bit:
def D2Y():
def No():
newconv=float(input("What is the rate that you want to use: "))
amount=float(input("How much do you want to convert: $"))
conversionn=round(amount*newconv,2)
print("¥",conversionn)
return (rerun())
def Yes():
conrate2=float(97.7677)
amount=float(input("How much do you want to convert: $"))
conversion=round(amount*conrate2,2)
print("¥",conversion)
return (rerun())
def rerun():
rerun=int(input("Do you want to go again?\n1 - Yes\n2 - No\nChoice: "))
if rerun==1:
return (main())
else:
print("Thank you for converting")
conrate1=int(input("The currency conversion rate for Yen to 1 US Dollar is ¥97.7677 to $1\n1 - Yes\n2 - No\nDo you want to use this rate?: "))
if conrate1==1:
return (Yes())
else:
return (No())
I dont know how you do it. I dont mind if you get rid of the def functions.
Here's an approach that does away with the functions and allows you to modify the exchange rate:
rate = CONVERSION_RATE = 97.7677
while True:
print "The currency conversion rate for Yen to 1 US Dollar is ¥%.4f to $1" % rate
print 'Select an option:\n1)Modify Conversion Rate\n2)Convert a value to dollars\n0)Exit\n'
choice = int(raw_input('Choice: '))
if choice == 0:
print("Thank you for converting")
break
if choice == 1:
try:
rate = float(raw_input("What is the rate that you want to use: "))
except ValueError:
rate = CONVERSION_RATE
amount = float(raw_input("How much do you want to convert: $"))
print "¥", round(amount * rate,2)
print '\n\n'
In use, it looks like this:
The currency conversion rate for Yen to 1 US Dollar is ¥97.7677 to $1
Select an option:
1)Modify Conversion Rate
2)Convert a value to dollars
0)Exit
Choice: 2
How much do you want to convert: $1.00
¥ 97.77
...
Choice: 1
What is the rate that you want to use: 96.9000
How much do you want to convert: $1.00
¥ 96.9