I'm very new to python and I'm stuck in some basic problems.
I can't seem to be able to put most of my calculations in a module. If I do, the results are not transferable and they will always show up as 0.0.
Once I'm able to put my calculations in a module, I can put the module inside a loop and ask the user if he wants to repeat the action.
This is my main issue too :: I want to "store" the output (displayResults) of each of the items (item number, price, etc) and print all of them once the loop is cancelled.
Thanks! I'm having a pretty difficult time trying to figure this out.
Here is my code:
#Mateo Marquez
#Oct. 8th, 2012
#P.O.S information system assigment
#
#Define Global Variables
TAX = 0.6
YELLOW_TAG = 0.10
BLUE_TAG = 0.20
RED_TAG = 0.25
GREEN_TAG = 0
#Main Module
def main():
tax_fee = 0.0
total_price = 0.0
introUser()
# I want this to be the mainCalc() function and return results.
productNumber=raw_input("Please enter the Product Number: ")
cost=float(raw_input("Please enter the cost of the selected product: "))
print " "
print "As you might have noticed, our discounts are color coded"
print "Yellow is 10%, Blue is 20% & Red is 25%"
print " "
tagDiscount=raw_input("Please enter the color tag: (yellow, blue, red or none)")
if tagDiscount == 'yellow':
print " "
print "You get a 10% discount"
total_price = (YELLOW_TAG*cost)
if tagDiscount == 'blue':
print " "
print "You get a 20% discount"
total_price = (BLUE_TAG*cost)
if tagDiscount == 'red':
print " "
print "You get a 25% discount"
total_price = (RED_TAG*cost)
if tagDiscount == 'none':
print " "
print "No discount for you!"
total_price = 0
print " "
print "~Remember~ this weekend is Tax Free in most of the country"
print "Green Tags designate if the product is tax free"
tagDiscount=raw_input("Does your product has a Green Tag? (yes or no)")
if tagDiscount == 'yes':
print " "
print "Good! your product is tax free"
tax_fee = 0
if tagDiscount == 'no':
print " "
print "I'm sorry, product", productNumber, "requires regular tax"
tax_fee = (TAX*total_price)
#I want this to be the end of the mainCalc() function
displayResults(total_price, tax_fee, cost, productNumber)
#Introduction function
def introUser():
print "Welcome to Wannabee's"
print "I'll gladly help you with your price question"
print "Let's start"
print " "
#Display results function
def displayResults(total_price, tax_fee, cost, productNumber):
print " "
print "Your Product Number: ", productNumber
print "Listed price of your product: $", cost
print "Your discount: $", total_price
print "Your Tax amount: $", tax_fee
print "Your grand total: $", (cost - total_price - tax_fee)
print " "
print "Your savings: ", ((cost-total_price)/cost*100),"%!"
main()
In order to save values used by related routines, put the variables and the routines that use them in a class. The following code defines a "POS" class and two method routines that share its variables. The "self." notation in the methods indicates a class variable that is saved in the instance "p" that is created when the class is instantiated with p = POS().
The example illustrates how the variables are stored; you'll need to adjust the inputs and print statements as needed (they're in Python 3 here). If you want to store the items as they are input and print them at the end, create an empty list in __init__, add a tuple to the list in mainCalc(), and print out each of the list items in displayResults().
class POS:
def __init__(self):
self.taxrate = 0.06
self.disc = {"": 0.0, "yellow": 0.10, "blue": 0.20, "red": 0.25}
self.total = 0
self.savings = 0
self.tax = 0
def mainCalc(self, item, qty, cost, tag, taxable):
print(qty, "* Item", item, "# ${:.2f}".format(cost),
"= ${:.2f}".format(qty*cost))
discount = cost * self.disc[tag]
if (tag):
print(" You get a", int(100*self.disc[tag]),
"% discount ${:.2f}".format(discount), "for", tag, "tag")
self.total += qty * (cost - discount)
self.savings += discount
if (taxable == "yes"):
tax = qty * cost * self.taxrate
self.tax += tax
print(" tax ${:.2f}".format(tax))
else:
print(" tax free")
def displayResults(self):
print("----------------")
print("Your total: ${:.2f}".format(self.total))
print("Your savings: ${:.2f}".format(self.savings))
print("Your total tax: ${:.2f}".format(self.tax))
print("Grand total: ${:.2f}".format(self.total + self.tax))
return
p = POS()
# Item Qty Price Tag Taxable
items = [(1492, 1, 1.95, "yellow", "yes"),
(1524, 2, 4.50, "blue", "no"),
(2843, 1, 6.95, "blue", "yes"),
(1824, 3, 2.29, "", "yes")]
for i in items:
p.mainCalc(*i)
p.displayResults()
Running the example produces:
1 * Item 1492 # $1.95 = $1.95
You get a 10 % discount $0.20 for yellow tag
tax $0.12
2 * Item 1524 # $4.50 = $9.00
You get a 20 % discount $0.90 for blue tag
tax free
1 * Item 2843 # $6.95 = $6.95
You get a 20 % discount $1.39 for blue tag
tax $0.42
3 * Item 1824 # $2.29 = $6.87
tax $0.41
----------------
Your total: $21.39
Your savings: $2.49
Your total tax: $0.95
Grand total: $22.33
You should consider the following constraints:
A function can only be called after it has been defined by a def statement (your call to displayResults.
Functions cannot access variables that are defined locally in the body of another function definition.
To improve your code, either think about how the program should flow from an overall point of view, or use a class as suggested in Dave's answer.
Related
Being relatively new to coding, some of the small issues I have not yet learn to tweak out. In this code my goal is to print the account's name, plus their balance based off of a withdraw, deposit, or simply checking. The name and values will print, however, they are not in a line, as well as "none" prints at the end, and i cannot seem to rid it. I need suggestions on how to fix. I believe the problem stems somewhere within the methods and calling them but am not sure.
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def Withdraw(self):
if Amount1 > self.balance:
self.withdraw = "You have exceeded your balance."
print (self.withdraw)
elif Amount1 < self.balance:
self.withdraw = (self.balance - Amount1)
print (self.withdraw)
def Deposit(self):
self.deposit = (self.balance + Amount2)
print (self.deposit)
def CheckBalance(self):
self.check = self.balance
print (self.check)
account1 = Account("Barbara", 500.00)
account2 = Account("Joe", 150.00)
account3 = Account("Frank", 20.00)
Action = input("What would you like to do; check balance(c), deposit(d), or withdraw(w)? ")
if Action == "w":
Amount1 = int(input("What amount would you like to withraw?"))
print (account1.name + str(account1.Withdraw()))
print (account2.name + str(account2.Withdraw()))
print (account3.name + str(account3.Withdraw()))
if Action == "d":
Amount2 = int(input("What amount would you like to deposit? "))
print (account1.name + str(account1.Deposit()))
print (account2.name + str(account2.Deposit()))
print (account3.name + str(account3.Deposit()))
if Action == "c":
print (account1.name + str(account1.CheckBalance()))
print (account2.name + str(account2.CheckBalance()))
print (account3.name + str(account3.CheckBalance()))
This is the code i have running so far
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)
I'm new to python and need help because I have no clue how to space in a print()
lemme show you what I'm working on
#Receipt.py
#Create a program that will prompt the user for an item description, the price of the item, and the quantity purchased.
#The program will output the final cost including all taxes. Your output should look as follows...
#
#Sample Output
#Enter the description: Volleyball
#Enter the price: 39.99
#Enter the quantity: 4
#RECEIPT
#-------------------------------------------------
#Description QTY price Subtotal
#Volleyball 4 $39.99 $159.96
#HST: $20.79
#-------------------------------------------------
#Total: $180.75
#user inputs
def main():
print("Welcome!")
Description = input("What is the name of the item?")
Price = float(input("What is the price?"))
Quantity = float(input("What is the quantity of the item?"))
#variables
Tax = 1.13
#boring math
Total = Price * Quantity * Tax
#what the user has inputted
print( "You have inputted the following")
print("The item is", Description)
print("The price is", Price)
print("The Quantity is", Quantity)
#Asking the user if it is correct
Answer = int(input("Is this want you want? If \"no\" type 1 if \"yes\" type 2")
if Answer = "1":
main()
#ignore the top part lol thaz extra
else:
print("Receipt")
print("--------------------------------------------------------------------------")
print (Description Price Subtotal)
tldr
As you can see I'm trying to make it like this
Sample Output
Enter the description: Volleyball
Enter the price: 39.99
Enter the quantity: 4
RECEIPT
-------------------------------------------------
Description QTY price Subtotal
Volleyball 4 $39.99 $159.96
HST: $20.79
-------------------------------------------------
Total: $180.75
but every time I try it gives me a error
Please use simple things cause I'm just a beginner and don't be to harsh on me lol
If you have any tips list them down below!
Thanks :)
The error seems to be from this line, print (Description Price Subtotal),
you have to separate out arguments to the print function with a ,, so
print (Description, Price, Subtotal) should work. Also please try to include the interpreter outputs when posting errors as they are helpful for debugging. Welcome to StackOverflow!
Your have syntax issues on your print statements. Please check the syntax for printing variables. Also variables need to be separated using commas.
Check out string formatting for Python.
Description = "Volleyball"
Quantity = 4
Price = 39.99
Subtotal = 159.96
name = "bug_spray"
# For newer versions of Python (>=3.6)
# Use f-strings
print(f"{Description} {Quantity} {Price:.2f} {Subtotal:.2f}")
print(f"Hi {name}")
# For older versions of Python
# Use modulo operator
print("%s %d %.2f %.2f" % (Description, Quantity, Price, Subtotal))
print("Hi %s" % name)
# Or use .format() (for Python >= 2.6)
print("{0} {1} {2} {3}".format(Description, Quantity, Price, Subtotal))
print("Hi {0}".format(name))
Also careful of how you indent stuff with if-else statements.
EDIT: I also a syntax error where you wrote if Answer = "1". It should instead look like:
if (Answer == 1):
...
else:
...
This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Alternatives for returning multiple values from a Python function [closed]
(14 answers)
Closed 3 years ago.
It seems like I can't pass a value from a function to another even though I have put a return statement in the 1st function.
This is my code:
price=0
TotalPrice=0
def SumPrice(price,TotalPrice):
if cup_cone=="cup":
price=(price+(mass/10)*0.59)*TotalSet
else:
if cone_size=="small":
price=(price+2)*TotalSet
else:
if cone_size=="medium":
price=(price+3)*TotalSet
else:
price=(price+4)*TotalSet
if Member_Ans=="yes":
TotalPrice=TotalPrice+price*0.90
print(price,TotalPrice)
return (price)
return (TotalPrice)
def PrintDetails(price,TotalPrice,Balance):
SumPrice(price,TotalPrice)
if Member_Ans=="yes":
print("Member ID: ", loginID, " (" , Username, ")")
for element in range (len(UserFlavor)):
print (UserFlavor[element], "--- ", UserFlavorPercentage[element], "%")
print ("Total set = ", TotalSet)
print ("Total price = RM %.2f" % (price))
if Member_Ans=="yes":
print ("Price after 10% discount = RM %.2f" % (TotalPrice))
while True:
Payment=int(input("Please enter your payment: "))
if Payment<TotalPrice:
print("Not enough payment.")
if Payment >= TotalPrice:
break
Balance=Balance+(Payment-TotalPrice)
print(Balance)
PrintDetails(price,TotalPrice,Balance)
When I try to print the price and TotalPrice, it prints 0, why?
You are trying to use return twice, which is not allowed (your function will end as soon as it reaches the 1st return statement, making the other one useless).
You can, however, return both values in one statement:
return (price, TotalPrice)
And then assign the value to a tuple or anything else you would like:
my_tuple = SumPrice(a, b)
or
var1, var2 = SumPrice(a, b)
Your second return statement of first function is not reachable! btw try to not use global variables in your code, instead access return values of your first function.
def SumPrice():
price = 0
TotalPrice = 0
if cup_cone=="cup":
price=(price+(mass/10)*0.59)*TotalSet
else:
if cone_size=="small":
price=(price+2)*TotalSet
else:
if cone_size=="medium":
price=(price+3)*TotalSet
else:
price=(price+4)*TotalSet
if Member_Ans=="yes":
TotalPrice=TotalPrice+price*0.90
return price, TotalPrice
def PrintDetails():
price, TotalPrice = SumPrice()
if Member_Ans=="yes":
print("Member ID: ", loginID, " (" , Username, ")")
for element in range (len(UserFlavor)):
print (UserFlavor[element], "--- ", UserFlavorPercentage[element], "%")
print ("Total set = ", TotalSet)
print ("Total price = RM %.2f" % (price))
if Member_Ans=="yes":
print ("Price after 10%% discount = RM %.2f" % (TotalPrice))
while True:
Payment=int(input("Please enter your payment: "))
if Payment<TotalPrice:
print("Not enough payment.")
if Payment >= TotalPrice:
break
Balance=Balance+(Payment-TotalPrice)
print(Balance)
PrintDetails()
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()