I'm coding a shopping cart class to implement a shopping cart that i often find on
websites where i can purchase some goods.Im thinking about stuff that i can store in a cart and also operations that i can perform on the cart. To
simplify matters, i consider the website to be an electronics e-store that
has goods like flat-panel TVs, boomboxes, iPods, camcorders, and so on. Here is my final code
class ShoppingCart(object):
def __init__(self, s_name = ""):
self.s_items = []
self.s_total = 0
self.s_shopper = s_name
self.s_address = ""
def add_item(self, s_T):
self.s_items.append(s_T)
self.s_total = sum([s_t[2]for s_t in self.s_items])
def print_cart(self):
print("\n Shipping:",self.s_address)
print("\n Cart:")
print("Name, \t\t ID, quantity, price")
for s_t in self.s_items:
print(s_t[0],"\t",s_t[3],"\t",s_t[1],"\t",s_t[2])
print("\n Total:", self.s_total)
def set_address(self,a):
self.s_address = a
def get_address(self):
return self.s_address
def demo(self):
R = ShoppingCart('Karlson')
R.add_item(('boom', 1, 23, 123))
R.add_item(('baam', 2, 130, 242))
R.set_address('123 main, smweher, MN')
R.print_cart()
When i run the code, nothing happens and i got "Processed finished with exit code 0" Usually, when my code isnt working, i got syntax or indentation errors and being a noob in coding that got downvotes in here for 0 reason, i dont know if that error only happens in my machine or is it related to the code?
You need to write some code at module scope to actually use your class. Looking at your code, you probably want something like this:
if __name__ == '__main__':
cart = ShoppingCart()
cart.demo()
Related
So I am working on a project which basically is to program a Monopoly. I want to be able for a player to pay X amount to the bank and have the bank properly receive and add that amount to its own. I am working the player on a Tkinter interface in a different class to the bank. I have done the following:
In Class Card1, import the Bank class from bank.py
Program a function pay_bank() where I get the amount entered in the Entry field and discount it from the player's available money and send it to bank.
-Create a function receive_payment() in the Bank class where it receives the player's money and adds it to its own.
For some reason, it is not working so I need your help. Code below:
Class Card1:
def __init__(self):
self.amount = 1500
self.properties = {}
#nested functions to handle interface and it's events
def manage_player1_card(self):
def pay_bank():
to_bank = int(payBox.get())
if self.amount > to_bank:
payBox.delete(0, END)
self.amount -= to_bank
Bank().receive_payment(to_bank)
class Bank:
def __init__(self):
self.bank_total = 14580
def receive_payment(self, pay):
self.bank_total += pay
*Indentation might look wrong due to copy-pasting but it is just fine in my code. What do you see I am doing wrong?
Basically, the self.bank_total amount is not adding up every time I enter the amount. For example: if I enter 500, it should go up to 15180, but it stays the same at 14580. I have debugged but it doesn't change. How can I fix this? Thanks!
Try something like this:
def pay_bank(bank: Bank):
...
bank.receive_payment(to bank)
That way you are passing the bank as a parameter.
I'm working on a project for CS1410, where I need to simulate a Coffee Machine. I have quite a bit so far, but I'm a bit stuck, specifically with these questions:
In the class CashBox, under the function deposit, I'm trying to add the values together from any coins inserted in the oneAction function from the CoffeeMachine class. However I get the error "'CoffeeMachine' object has no attribute 'credit'" and I'm struggling with understanding why. I can tell it's an inheritance problem, but I'm unsure exactly how to fix it.
How should I format it so that when I get the input in oneAction(), I can take that input and mess with it in the cashBox? What am I doing wrong with self.something, and how can I recognize when to use self, and when to just use a normal variable
I wasn't sure how to upload the code so that the problem is reproducible without giving at least this file, it's all pretty tied together. Some advice on how I could have presented this better would be helpful as well.
Past the original question, any further advice would be seriously appreciated.
Seriously.
Thank you all, hopefully the code is pretty readable.
class CashBox(object):
def __init__(self):
self.credit = 0
self.totalReceived = 0.0
def deposit(self,amount):
self.credit = amount + self.credit
self.totalReceived = amount + self.totalReceived
print(self.totalReceived,self.credit)
def returnCoins(self):
print("Returning ", self.totalReceived, " cents.")
self.totalReceived = 0.0
def haveYou(self,amount):
return self.credit >= amount
def deduct(self,amount):
pass
def totalCoins(self):
return self.totalReceived
class CoffeeMachine(object):
def __init__(self):
self.cashBox = CashBox()
self.selector = self.cashBox
def oneAction(self):
while True:
command = input("""
______________________________________________________
PRODUCT LIST: all 35 cents, except bouillon (25 cents)
1=black, 2=white, 3=sweet, 4=sweet & white, 5=bouillon
Sample Commands: insert 25, select 1. Your command:
""")
words = command.lower().split()
if 'select' in words:
Selector.select(self,int(words[1]))
print("Great selection!")
elif 'insert' in words:
coinsAllowed = [5,10,25,50]
if int(words[1]) in coinsAllowed:
CashBox.deposit(self,int(words[1]))
else:
print("""
That is not one of the allowed coins,
please insert a penny, nickel, dime, quarter,
or half-dollar. Thank you.
""")
elif 'cancel' in words:
print("Cancelling transaction. Returning to main menu: ")
CashBox.returnCoins(self)
elif 'quit' in words:
print("Have a nice day!")
else:
print("That is not an option")
def totalCash(self):
pass
class Product(object):
def __init__(self,name,price,recipe):
self.name = name
self.price = price
self.recipe = recipe
def getPrice(self):
return self.price
def make(self):
print(self.recipe)
class Selector(object):
def __init__(self):
self.cashBox = CashBox
self.products = []
#self.products.append(Product.
def select(self, choiceIndex):
pass
def main():
m = CoffeeMachine()
while m.oneAction():
pass
#total = m.totalCash()
#print(f"Total Cash: ${total/100:.2f}")
if __name__ == "__main__":
main()
Exception has occurred: AttributeError
'CoffeeMachine' object has no attribute 'credit'
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 7, in deposit
self.credit = amount + self.credit
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 46, in oneAction
CashBox.deposit(self,int(words[1]))
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 89, in main
while m.oneAction():
File "C:\Users\Tanner Harmer\Desktop\Coffee2\CashBox.py", line 95, in <module>
main()
You're calling the CashBox by using the class name, like if the method were static, but you created an instance of this class (in the constructor self.cashBox = CashBox()) so use it
CashBox.deposit(self,int(words[1])) // OLD, NO
self.cashBox.deposit(self,int(words[1])) // YES
use the cashBox of the CoffeeMachine
I am new to Python and trying to make a function for an assignment that will transfer money from a checking to a savings account,. We were given this initial code:
class portfolio:
def __init__(self):
self.checking = {}
self.saving = {}
self.credit = {}
self.stock = {}
And then the start of this code to make the function to transfer the money:
def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
I've tried numerous code, but none will pass the test cases. Can someone explain to me why this won't work?
def invest_in_savings_account(self, account_id_savings, amount, account_id_checking):
try:
self.checking[account_id_checking] -= amount
self.saving[account_id_savings] += amount
except:
return None
If the account id doesn't exist or if there are no funds in the checking account, the function is to do nothing.
Any suggestions would be greatly appreciated! I've worked on this all day and haven't been able to solve it.
This is the test case it must pass:
myportfolio.invest_in_savings_account('discover_saving_3785', 1000, 'discover_7732')
if (myportfolio.saving == {'chase_saving_4444': 0, 'discover_saving_3785':1000}) and (myportfolio.checking == {'chase_6688': 100, 'discover_7732':5500}):
print('Pass')
else:
print('Fail')
There are a few things going on here, most simple first, always start a class with a capital letter, it isn't necessary but it's good practice:
def class Portfolio:
After reading your comments it appears you need this to work without money in the accounts. You can write the code but you won't be able to test it, so really you need to make functions to create accounts and to add / remove money. If you haven't created any accounts your dictionaries will always come back empty. If you don't put money into them then the function will never do anything, I'm confused as to how you would go about moving something that doesn't exist.
Try something like this:
def create_checking_account(self,account_id):
self.checking[account_id] = None
def add_funds_checking(self,account_id,amount):
self.checking[account_id] += amount
def invest_in_savings(self, account_id_savings, amount, account_id_checking):
if self.checking[account_id_checking] >= amount:
self.checking[account_id_checking] -= amount
self.savings[account_id_savings] += amount
else:
print('error')
I have a small project and I have been unable to get the following statement to work. Any help would be great. User inputs can either self.sale_head which is a $ value,if a $ value is not add a self.estimated_weight_hd is used to get the total weight, the code below should return a estimated_weight_total which can be used for the total sale price. All works when I add the estimated_weight_total manually. I am lost as why.
def calc_estimated_weight_total(self):
if self.sale_head <= 0:
amount = (self.number * self.estimated_weight_hd)
return amount
def save(self):
self.estimated_total_weight = self.calc_estimated_weight_total()
super(SaleNote, self).save()
Your code doesn't do what you want cause if self.sale_head > 0 nothing will return. From your description, I think your code should be somthing like:
def calc_estimated_weight_total(self):
if self.sale_head <= 0:
amount = (self.number * self.estimated_weight_hd)
return amount
else:
return something_only_you_know
def save(self):
self.estimated_total_weight = self.calc_estimated_weight_total()
super(SaleNote, self).save()
I have a homework assignment that's really baking my noodle. It involves an elevator simulation that takes user inputs for the number of floors and the number of people using the elevator. the people's starting floor and destination floors are random numbers within the floors.
I realize that my code is very sparse and that there's quite a few gaps, but I really don't know where to go from here.
I need help within the building class, such as how to make the run() and output() sections work. any other tips would be greatly appreciated and helpful. Note that i am not looking for someone to do the code for me, but to kind of hold my hand and tell me which way to go. Classes seem to be completely mystifying to me.
import random
floors=raw_input('Please enter the number of floors for the simulation:')
while floors.isalpha() or floors.isspace() or int(floors) <=0:
floors=raw_input('Please re enter a digit for number of floors:')
customers=raw_input('Please enter the number of customers in the building:')
while customers.isalpha() or customers.isspace() or int(customers) <0:
customers=raw_input('Please re enter a digit for number of customers:')
count = 1
class building:
def num_of_floors():
num_of_floors = floors
def customer_list():
customer_list = customers
def run(self):
def output(self):
print elevator.cur_floor
class elevator:
def num_of_floors():
building.num_of_floors
def register_list():
register_list = []
def cur_floor(building):
cur_floor = 1
def direction(self):
if elevator.cur_floor == 1:
direction = up
if elevator.cur_floor == floors:
direction = down
def move(self):
if elevator.direction == up:
cur_floor +=1
if elevator.direction == down:
cur_floor -=1
def register_customer(self, customer):
register_list.append(customer.ID)
def cancel_customer (self, customer):
register_list.remove(customer.ID)
class customer:
def cur_floor(customer):
cur_floor = random.randint(0,int(floors))
def dst_floor(customer):
dst_floor = random.randint(0,int(floors))
while dst_floor == cur_floor:
dst_floor = random.randint(0,int(floors))
def ID():
cust_id = count
count+=1
def cust_dict(cust_id,dst_floor):
cust_dict = {cust_id:dst_floor}
def in_elevator():
in_elevator = 0
if customer.ID in register_list:
in_elevator = 1
def finished():
if customer.ID not in register_list:
pass
You need to understand the self
parameter to all methods.
You need to understand __init__,
the constructor.
You need to understand self.varible
for your member variables.
You need to understand how to setup a
main function.
You need to understand how to
return a value from a function or
method.
You need to understand how to assign to global variables from within a function or method.
Maybe your building class should start like this.
class building:
def __init__(self, floors, customers):
self.num_of_floors = floors
self.customer_list = customers
self.elevator = elevator()
You should definately spend some time on Python Tutorial or Dive into Python.
The first parameter of every method is a reference to the object and is usually called self. You need it to reference instancemembers of an object.
Second, referencing global variables from inside a class is considered a bad idea. You can better pass them to a class via the constructor or parameters.