NameError: Global Name not defined - python

my python code keeps getting nameerror, global variable not defined on ticketSold. I am not sure how to fix this, as I did define it as a global variable. Any help is appreciated.
aLimit=300
bLimit=500
cLimit=100
aPrice=20
bPrice=15
cPrice=10
def Main():
global ticketSold
getTickets(aLimit)
sectionIncome=calcIncome(ticketSold,aPrice)
SectionIncome+=totalIncome
print("The theater generated this much money from section A "+str(sectionIncome))
getTickets(bLimit)
sectionIncome=calcIncome(ticketSold,bPrice)
SectionIncome+=totalIncome
print("The theater generated this much money from section B "+str(sectionIncome))
getTickets(cLimit)
sectionIncome=calcIncome(ticketSold,cPrice)
sectionIncome+=totalIncome
print("The theater generated this much money from section C "+str(sectionIncome))
print("The Theater generated "+str(totalIncome)+" total in ticket sales.")
def getTickets(limit):
ticketSold=int(input("How many tickets were sold? "))
if (ticketsValid(ticketSold,limit)==True):
return ticketSold
else:
getTickets(limit)
def ticketsValid(ticketSold,limit):
while (ticketSold>limit or ticketSold<0):
print ("ERROR: There must be tickets less than "+str(limit)+" and more than 0")
return False
return True
def calcIncome(ticketSold,price):
return ticketSold*price

Saying global varname does not magically create varname for you. You have to declare ticketSold in the global namespace, for example after cPrice=10. global only makes sure that when you say ticketSold, you're using the global variable named ticketSold and not a local variable by that same name.

Here is a version which:
is Python 2 / 3 compatible
does not use any global variables
is easily extended to any number of sections
demonstrates some benefits of OOP (as opposed to a proliferation of named variables: aLimit, bLimit, etc - what will you do when you reach 27 sections?)
And so:
import sys
if sys.hexversion < 0x3000000:
# Python 2.x
inp = raw_input
else:
# Python 3.x
inp = input
def get_int(prompt):
while True:
try:
return int(inp(prompt))
except ValueError: # could not convert to int
pass
class Section:
def __init__(self, name, seats, price, sold):
self.name = name
self.seats = seats
self.price = price
self.sold = sold
def empty_seats(self):
return self.seats - self.sold
def gross_income(self):
return self.sold * self.price
def sell(self, seats):
if 0 <= seats <= self.empty_seats():
self.sold += seats
else:
raise ValueError("Cannot sell {} seats, only {} are available".format(seats, self.empty_seats))
def main():
# create the available sections
sections = [
Section("Loge", 300, 20., 0),
Section("Floor", 500, 15., 0),
Section("Wings", 100, 10., 0)
]
# get section seat sales
for section in sections:
prompt = "\nHow many seats were sold in the {} Section? ".format(section.name)
while True:
# prompt repeatedly until a valid number of seats is sold
try:
section.sell(get_int(prompt))
break
except ValueError as v:
print(v)
# report section earnings
print("The theatre earned ${:0.2f} from the {} Section".format(section.gross_income(), section.name))
# report total earnings
total_earnings = sum(section.gross_income() for section in sections)
print("\nTotal income was ${:0.2f} on ticket sales.".format(total_earnings))
if __name__=="__main__":
main()
which gives us
How many seats were sold in the Loge Section? 300
The theatre earned $6000.00 from the Loge Section
How many seats were sold in the Floor Section? 300
The theatre earned $4500.00 from the Floor Section
How many seats were sold in the Wings Section? 100
The theatre earned $1000.00 from the Wings Section
Total income was $11500.00 on ticket sales.

Related

Rounds integer even with float- python

Below is my code. the issue is in MAIN. The code works as a person trying to buy items into a cart and you can see the total price of those items. They have to enter in the price for each item that they want. If a person inputs a number to two decimal places, it rounds it to the nearest whole number.
import locale
class CashRegister:
def __init__(self):
mself.items = 0
self.price = int(float(0.00))
def addItems(self,price): #keeps track of total number of items in cart
self.price += price
self.items += 1
print(self.price)
def getTotal(self): #returns total price
return self.price
def getCount(self): #return the item count of the cart
return self.items
def clearCart(self): #clears cart for another user or checkout
self.items = 0
self.price = int(float(0.00))
def main():
user_name = input('What is your name?\n') #weclomes user
print("Hello",user_name)
locale.setlocale(locale.LC_ALL, 'en_US')
user_name = CashRegister() #user is using the cash register
while True:
line = input ("Would you like to add another food item to your cart? Choose y or n \n")
if line == "y":
** price = int(float(input("please input the price of the item\n")))
print(price)**
user_name.addItems(price) #user adds prices to cart
elif line == "n":
print("Your total checkout price:", locale.currency(user_name.getTotal()) )
# int(float(locale.currency(user_name.getTotal())))
print("Your total item count", user_name.getCount())
user_name.clearCart() #clears cart for another user/checkout
break
else:
print("Error")
if __name__ == '__main__':
main()
As soon as the person inputs the number, I printed it to see if that's where the problems lies. I'll enter 3.20 but it automatically converts it to 3. I have no idea how to force it to keep those decimals. I even tried printing it with the int/float and it still doesn't work.
The int() function always returns an integer. An integer never has any decimal points. So use only
float(input("please input the price of the item\n"))
instead of
int(float(input("please input the price of the item\n")))

How to ask if a user is a member and if so, display their discounted price and how to add all values up? [closed]

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()

global name not defined error

I keep on getting an error with my discount variable. name-error: global name 'discount' not defined. please take a look at my code and help me out. I don't want to modify the parameters of the functions at all.
def finddiscount(quantity):
if quantity >= 1 and quantity <= 9:
discount = 0
elif quantity >= 10 and quantity <= 19:
discount = .2
elif quantity >= 20 and quantity <= 49:
discount = .30
elif quantity >= 50 and quantity <= 99:
discount = .40
elif quantity >= 100:
discount = .50
return discount
def calctotal(quantity, price):
finddiscount(quantity)
disc = (price*quantity)*discount
total = (price*quantity)
due = (price*quantity)-(price*quantity)*dicount
print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")
def main():
quantity = int(input("How many packages where purchased?"))
price = float(input("How much is each item?"))
calctotal(quantity, price)
main()
You have to declare discount as a global if you want to access it in a multi block scope.
discount = 0
def finddiscount(quantity):
...
global discount # Needed to modify global copy of discount
discount = 1
disc = (price*quantity)*discount
You never defined discount in calctotal (and neither in global scope). Assign the result from finddiscount(quantity) to it. At the moment you are calculating the discount, but drop the result immediately by not assigning it to any variable:
def calctotal(quantity, price):
discount = finddiscount(quantity)
disc = (price*quantity)*discount
total = (price*quantity)
due = (price*quantity)-(price*quantity)*dicount
print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")
If we look at this block of code
def calctotal(quantity, price):
finddiscount(quantity)
disc = (price*quantity)*discount
total = (price*quantity)
due = (price*quantity)-(price*quantity)*dicount
print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")
neither discount nor dicount (I'm assuming typo) have been declared in calctotal(). Below should solve yoru issue
def calctotal(quantity, price):
discount = finddiscount(quantity)
disc = (price*quantity)*discount
total = (price*quantity)
due = (price*quantity)-(price*quantity)*discount
print ("\t","Order total $",format(total, "10.2"),"\n\t","Discount $",format(disc,"10.2"),"\n\t","Amount Due $",format (due, "10.2"),sep="")
EDIT:
While making discount a global variable is certainly a way to do this, in general I'd recommend not making a variable global unless you have a good reason. For example - if the discount applied was going to be affected by external functions, and you wanted it changed in finddiscount() as well then a global variable would work nicely. However in this scenario you are creating all possible values of discount within finddiscount() and it just makes more sense to use assignment.
The problem with global variables is that you can accidentally reassign them to things you didn't intend to do, and it can clutter up the namespace if done for no reason.

Python pick item from list of classes

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()

Why do I get an attribute error with my class?

EDIT BELOW!
Here is my retail_item class:
#RetailItem Class
class RetailItem:
def __init__(self, desc, inventory, price):
self.__desc=desc
self.__inventory=inventory
self.__price=price
#mutators
def set_desc (self, desc):
self.__desc=desc
def set_inventory (self, inventory):
self.__inventory=inventory
def set_price (self, price):
self.__price = price
#accessors
def get_desc(self):
return self.__desc
def get_inventory(self):
return self.__inventory
def get_price(self):
return self.__price
def __str__(self):
return 'Item Description:' + self.__desc, \
'\tNumber of Units:' + self.__inventory, \
'\tPrice: $' + self.__price
And my cash_register class:
#CashRegister Class
class CashRegister:
def __init__(self, purchase, total, show, clear):
self.__purchase=purchase
self.__total=total
self.__show=show
self.__clear=clear
#mutators
def purchase_item(self, purchase):
self.__purchase=purchase
def get_total(self, total):
self.__total=total
def show_item(self, show):
self.__show=show
def clear(self, clear):
self.__clear=clear
#accessors
def acc_purchase(self):
return self.__purchase
def acc_total(self):
return self.__total
def acc_show(self):
return self.__show
def acc_clear(self):
return self.__clear
And finally my program:
import retail_item
import cash_register
SHOW = 1
PURCHASE = 2
CART = 3
TOTAL = 4
EMPTY = 5
QUIT = 6
def main():
mylist = make_list()
#mycr = cash_register.CashRegister(mylist)
choice = 0
# Process menu selections until user quits program.
while choice != QUIT:
# Get the user's menu choice.
choice = get_menu_choice()
# Proces the choice.
if choice == SHOW:
show_items(mylist)
elif choice == PURCHASE:
purchase_item(mylist)
elif choice == TOTAL:
get_total(mylist)
elif choice == EMPTY:
clear(mylist)
def make_list():
item_list = {}
desc = 'Jacket'
inventory = 12
price = 59.95
entry = retail_item.RetailItem(desc, inventory, price)
item_list[desc]=entry
desc = 'Jeans'
inventory = 40
price = 34.95
entry = retail_item.RetailItem(desc, inventory, price)
item_list[desc]=entry
desc = 'Shirt'
inventory = 20
price = 24.95
entry = retail_item.RetailItem(desc, inventory, price)
item_list[desc]=entry
return item_list
# The get_menu_choice function displays the menu and gets
# a validated choice from the user.
def get_menu_choice():
print()
print('CASH REGISTER MENU')
print('-------------------------')
print('1. Show Retial Items')
print('2. Purchase Item(s)')
print('3. Show Current Shopping Cart')
print('4. Show Total of Items Purchased')
print('5. Empty Your Shopping Cart')
print('6. Quit the program')
print()
# Get the user's choice.
choice = int(input('Enter your choice: '))
# Validate the choice.
while choice < SHOW or choice > QUIT:
choice = int(input('Enter a valid choice: '))
# Return the user's choice.
return choice
def show_items(mylist):
print('\t\tDescription\t\tUnits in Inventory\t\tPrice')
print('--------------------------------------------------------------------------------')
x=1
for item in mylist:
print('Item #', x, '\t\t', item.get_desc(), '\t\t\t\t', item.get_inventory(), '\t\t\t$', format(item.get_price(), ',.2f'),sep='')
print()
x+=1
def purchase_item(mylist):
desc = input('Enter the item you wish to purchase: ')
if desc in mylist:
amount=int(input('How many would you like to buy: '))
if mylist[units]>0:
mylist[units]-=amount
elif (units-amount<0):
mylist[units]=0
else:
mylist[units] = 0
entry=cash_register.CashRegister(desc, units,)
mylist[desc]=entry
print()
def get_total(mylist):
print()
def clear(mylist):
print(mylist)
mylist.clear()
print(mylist)
main()
So my question is, how to I update only one object of a class?
And how do I call on the cash_register class?
Here are the instructions for the assignment, if that helps:
This exercise assumes that you have created the RetailItem class for Programming
Exercise 5. Create a CashRegister class that can be used with the RetailItem class. The
CashRegister class should be able to internally keep a list of RetailItem objects. The
class should have the following methods:
• A method named purchase_item that accepts a RetailItem object as an argument.
Each time the purchase_item method is called, the RetailItem object that is passed as
an argument should be added to the list.
• A method named get_total that returns the total price of all the RetailItem objects
stored in the CashRegister object’s internal list.
• A method named show_items that displays data about the RetailItem objects stored
in the CashRegister object’s internal list.
• A method named clear that should clear the CashRegister object’s internal list.
Demonstrate the CashRegister class in a program that allows the user to select several
items for purchase. When the user is ready to check out, the program should display a list
of all the items he or she has selected for purchase, as well as the total price.
EDIT: Here's my somewhat final code. I know it's not pretty, and I apologize for the lack of comments. I would still like some feedback even though I'll be submitting it shortly (for my own betterment and for job opportunities!) Here it is:
import retail_item
import cash_register
SHOW = 1
PURCHASE = 2
TOTAL = 3
EMPTY = 4
QUIT = 5
def main():
#set all variables to zero
lister = []
inv=[]
cost=[]
desc=''
inventory=0
price=0
total=0
purchase=0
#setting variable for each class
cash=cash_register.CashRegister(purchase, total, lister, inv, cost)
retail=retail_item.RetailItem(desc, inventory, price)
#classes
desc = 'Jacket'
inventory = 12
price = 59.95
#setting classes
retail.set_desc(desc)
retail.set_inventory(inventory)
retail.set_price(price)
#Adding to cart
cash.purchase_item(retail.get_desc(), lister)
cash.purchase_item(retail.get_inventory(), inv)
cash.purchase_item(retail.get_price(), cost)
desc = 'Jeans'
inventory = 40
price = 34.95
retail.set_desc(desc)
retail.set_inventory(inventory)
retail.set_price(price)
cash.purchase_item(retail.get_desc(), lister)
cash.purchase_item(retail.get_inventory(), inv)
cash.purchase_item(retail.get_price(), cost)
desc = 'Shirt'
inventory = 20
price = 24.95
retail.set_desc(desc)
retail.set_inventory(inventory)
retail.set_price(price)
cash.purchase_item(retail.get_desc(), lister)
cash.purchase_item(retail.get_inventory(), inv)
cash.purchase_item(retail.get_price(), cost)
choice = 0
# Process menu selections until user quits program.
while choice != QUIT:
# Get the user's menu choice.
choice = get_menu_choice()
# Proces the choice.
if choice == SHOW:
show_items(cash, retail, lister, inv, cost)
elif choice == PURCHASE:
purchase_item(cash, retail, lister, inv, cost)
elif choice == TOTAL:
get_total(cash, retail, lister)
elif choice == EMPTY:
price=0
cash.set_total(price)
clear(cash, lister)
# The get_menu_choice function displays the menu and gets
# a validated choice from the user.
def get_menu_choice():
print()
print('CASH REGISTER MENU')
print('-------------------------')
print('1. Show Retail Items')
print('2. Purchase Item(s)')
print('3. Show Total of Items Purchased')
print('4. Empty Your Shopping Cart')
print('5. Quit the program')
print()
# Get the user's choice.
choice = int(input('Enter your choice: '))
# Validate the choice.
while choice < SHOW or choice > QUIT:
choice = int(input('Please enter a valid choice: '))
# Return the user's choice.
return choice
def show_items(cash, retail, lister, inv, cost):
print('\t\tDescription\t\tUnits in Inventory\t\tPrice')
print('--------------------------------------------------------------------------------')
cash.show_item(lister, inv, cost)
def purchase_item(cash, retail, lister, inv, cost):
JACKET=1
JEANS=2
SHIRT=3
QUIT=4
choice=0
print()
print('WHICH WOULD YOU LIKE TO BUY')
print('-------------------------')
print('1. Jacket')
print('2. Jeans')
print('3. Shirt')
print('4. Quit')
print()
print('Choose as many as you like. Press 4 then ENTER to quit.')
while choice != QUIT:
# Get the user's menu choice.
choice = int(input('Which would you like to buy: '))
if choice < JACKET or choice > QUIT:
choice = int(input('Please enter a valid choice: '))
while choice != QUIT:
# Proces the choice.
if choice == JACKET:
desc = 'Jacket'
inventory = 12
price = 59.95
retail.set_desc(desc)
retail.set_inventory(inventory)
retail.set_price(price)
cash.purchase_item(retail.get_desc(), lister)
cash.purchase_item(retail.get_inventory(), inv)
cash.purchase_item(retail.get_price(), cost)
cash.set_total(price)
break
elif choice == JEANS:
desc = 'Jeans'
inventory = 40
price = 34.95
retail.set_desc(desc)
retail.set_inventory(inventory)
retail.set_price(price)
cash.purchase_item(retail.get_desc(), lister)
cash.purchase_item(retail.get_inventory(), inv)
cash.purchase_item(retail.get_price(), cost)
cash.set_total(price)
break
elif choice == SHIRT:
desc = 'Shirt'
inventory = 20
price = 24.95
retail.set_desc(desc)
retail.set_inventory(inventory)
retail.set_price(price)
cash.purchase_item(retail.get_desc(), lister)
cash.purchase_item(retail.get_inventory(), inv)
cash.purchase_item(retail.get_price(), cost)
cash.set_total(price)
break
print()
def get_total(cash, retail, lister):
print()
cash.show_items(cash.get_list(lister))
print('Your total is: $', format(cash.cost_total(),',.2f'))
def clear(cash, lister):
print('Shopping cart emptied.')
lister=lister.clear()
price=0
cash.set_total(price)
return lister
main()
RetailItem Class:
class RetailItem:
def __init__(self, desc, inventory, price):
self.__desc=desc
self.__inventory=inventory
self.__price=price
#mutators
def set_desc (self, desc):
self.__desc=desc
def set_inventory (self, inventory):
self.__inventory=inventory
def set_price (self, price):
self.__price = price
#accessors
def get_desc(self):
return self.__desc
def get_inventory(self):
return self.__inventory
def get_price(self):
return self.__price
def __str__(self):
return 'Item Description:' + self.__desc, \
'\tNumber of Units:' + self.__inventory, \
'\tPrice: $' + self.__price
And again, lastly my CashRegister Class:
#CashRegister Class
class CashRegister:
def __init__(self, purchase, total, lister, inv, cost):
self.__purchase=purchase
self.__total=total
self.__lister=[]
self.__inv=[]
self.__cost=[]
#mutators
def purchase_item(self, purchase, lister):
self.__purchase=purchase
lister.append(purchase)
return lister
def set_total(self, price):
self.__total+=price
def show_item(self, lister, inventory, price):
i=0
while i<len(lister):
s=('Item # %i\t%s\t\t\t\t%i\t\t\t%4.2f') % ((i+1),lister[i],inventory[i],price[i])
s = s.strip(' \t\n\r')
print(s)
i+=1
def show_items(self, lister):
i=0
print('You have purchased the following items')
while i<len(lister):
print(lister[i])
i+=1
def clear(self, lister):
i=0
while i<len(lister):
del lister[i]
i+=1
return lister
def get_list(self, lister):
return lister
#accessors
def acc_purchase(self):
return self.__purchase
def cost_total(self):
return self.__total
def acc_show(self):
return self.__show
def acc_clear(self):
return self.__clear
Thanks again guys! I used this site often, and though I didn't use much of what y'all gave me this time, you're still awesome!
This code has a couple of major problems. Without a stack trace I can't say exactly why you're getting an AttributeError, but I can tell that CashRegister objects can't be instantiated as written. Its __init__ refers to nonexistent variables - item and items.
Your CashRegister class is taking arguments to __init__ that aren't necessary - and in some cases should be methods. I don't see any reason your CashRegister class should take any __init__ arguments - it should initialize the list of RetailItem objects and probably a running total and do nothing else. purchase_item should update those internal attributes, get_total and show_items should read them (or get_total should calculate the total based on the list if you don't keep a running total) and clear should reset them both.
Stylistically, mutators and accessors and hidden internal data are not a Pythonic idiom. In general Python classes get and set member data directly, and get refactored to use properties if the behavior ever needs to change. I see that this is for a class/exercise, so you might be using them because they're required, but if not you're better off without them.
edit
This is what my main() would look like, making the minimal edits to show the logic:
def main():
items = make_list()
mycr = cash_register.CashRegister()
# at this point, mycr.show_items() should return [] and mycr.get_total() should return 0
choice = 0
while choice != QUIT:
choice = get_menu_choice()
if choice == SHOW:
mycr.show_items()
elif choice == PURCHASE:
item, quantity = get_purchase(items)
if item and quantity:
item.set_inventory(max(0, item.get_inventory() - quantity))
mycr.purchase_item(item, quantity)
elif choice == TOTAL:
print(mycr.get_total())
elif choice == EMPTY:
mycr.clear()
def get_purchase(items):
desc = input('Enter the item you wish to purchase: ')
if desc in items:
amount=int(input('How many would you like to buy: '))
return items[desc], amount
else:
return None, 0
This doesn't cover every possibility - for instance, as with your original code it allows entering higher quantities than are currently available with no side effect besides setting the quantity to 0. But the exercise description doesn't mention inventory tracking, so maybe that's not a requirement.

Categories