The program offers items, has the user pay for items, 'gives' the items. It seems to work more or less. I have 2 questions:
I don't know how to deduct the cash from cash it is deposited and when they select the item, it should detect the cash from the deposit and give back the rest of the changes
Is there a way to make the code simpler/better?
import time
import sys
class CashBox(object):
def __init__(self):
self.credit = 0
self.totalReceived = 0
#self.price = 35
def deposit(self, amount):
self.credit = amount + self.credit
self.totalReceived = amount + self.totalReceived
print("Depositing {0} cents. You have {1} cents credit.".format(
amount, self.credit))
# print(type(self.credit))
return self.credit
def returnCoins(self):
print("Returning ", self.credit/100, " dollars.")
self.totalReceived = 0
def haveYou(self, name, price, recipe):
return self.credit >= price
def deduct(self, amount):
pass
def totalCoins(self):
return self.totalReceived
class CoffeeMachine(object):
def __init__(self):
self.cashBox = CashBox()
self.credit = CashBox.__init__
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, cancel, quit.
Your command:
""")
words = command.lower().split()
if 'select' in words:
Selector.select(self, int(words[1]))
elif 'insert' in words:
coinsAllowed = [5, 10, 25, 50]
if int(words[1]) in coinsAllowed:
self.cashBox.deposit(int(words[1]))
else:
print(
"""We only take half-dollars, quarters, dimes, and nickels.""")
elif 'cancel' in words:
print("Cancelling transaction. Returning to main menu: ")
self.cashBox.returnCoins()
elif 'quit' in words:
break
else:
print("Invalid command.")
def totalCash(self):
return self.cashBox.totalReceived
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):
for item in self.recipe:
print("dispensing", item)
time.sleep(0.5)
print("Enjoy your", self.name)
time.sleep(0.5)
# print(self.price)
class Selector(object):
def __init__(self):
#self.Product = Product()
self.cashBox = CashBox()
self.credit = CashBox.deposit
# self.products.append(Product.
def select(self, choiceIndex):
recipes = {
1: ["Black coffee", 35, ["cup", "coffee", "water"]],
2: ["White coffee", 35, ["cup", "coffee", "creamer", "water"]],
3: ["Sweet coffee", 35, ["cup", "coffee", "sugar", "water"]],
4: ["White & Sweet coffee", 35, ["cup", "coffee", "sugar", "creamer", "water"]],
5: ["Bouillon", 25, ["cup bouillonPowder", "water"]]
}
if choiceIndex in range(1, len(recipes)+1):
self.choiceIndex = choiceIndex
self.recipe = recipes.get(choiceIndex)
product = Product(*self.recipe)
if self.cashBox.haveYou(*self.recipe) == True:
#print(self.recipe,"Great selection")
#price = CashBox.haveYou(*self.recipe)
product.make()
self.cashBox.haveYou = self.cashBox.haveYou - self.cashBox.deduct
print("Returning {0} cents.".format(self.cashBox.haveYou))
else:
print("Sorry. Not enough money deposited.")
else:
print("That selection does not exist")
def main():
m = CoffeeMachine()
while m.oneAction():
pass
total = m.totalCash()
print(f"Total cash received: ${total/100:.2f}")
if __name__ == "__main__":
main()
Related
To give you some background info, I basically have to create 2 classes called ItemToPurchase that contains an item's name, quantity, description, and price. The other class ShoppingCart adds the item's name into a list with some other functions that modify the list. The part where I am facing some issues is at the part of execute_menu(). Let's say I enter the option 'a', after I give all the details of the item, the entire program ends. I do not want that. I want the program to ask me for the next option and keep asking me the next option after I complete a specific letter's required details.
class ItemToPurchase:
def __init__(self):
self.name = 'none'
self.quantity = 0
self.price = 0
self.description = 'none'
def item_name(self, name):
self.name = name
def item_price(self, price):
self.price = price
def item_quantity(self, quantity):
self.quantity = quantity
def item_description(self, description):
self.description = description
def print_item_cost(self):
print(self.name + " " + str(self.quantity) + " # $" + str(self.price) + " = $" + str(int(self.quantity) * int(self.price)))
def print_item_description(self):
print(self.name + ": " + self.description)
class ShoppingCart:
def __init__(self, name='none', date='January 1, 2016'):
self.customer_name = name
self.current_date = date
self.cart_items = []
def add_item(self, New_cart):
self.cart_items.append(New_cart)
def remove_item(self, item_name):
count = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
if item.name == item_name:
del self.cart_items[i]
count += 1
if count == 0:
print()
print('Item not found in cart. Nothing removed')
def modify_item(self, ItemToPurchase, Item_Name):
num = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
if Item_Name in [x.name for x in items]:
num += 1
if ItemToPurchase.description != "none":
item.item_description(ItemToPurchase.description)
if ItemToPurchase.price != 0:
item.item_price(ItemToPurchase.price)
if ItemToPurchase.quantity != 0:
item.item_quantity(ItemToPurchase.quantity)
if num == 0:
print()
print('Item not found in cart. Nothing modified.')
print()
def get_num_items_in_cart(self):
total_number = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
total_number += item.quantity
return total_number
def get_cost_of_cart(self):
total_cost = 0
items = self.cart_items[:]
for i in range(len(items)):
item = items[i]
total_cost += int(item.quantity*item.price)
return total_cost
def print_total(self):
print(self.customer_name + "'s Shopping Cart - " + str(self.current_date))
count = len(self.cart_items) + 1
if len(self.cart_items) > 0:
print('Number of items:' + str(count))
print()
for i in self.cart_items:
i.print_item_cost()
total = self.get_cost_of_cart()
print()
print('Total:', str(total))
else:
print('SHOPPING CART IS EMPTY')
def print_descriptions(self):
if len(self.cart_items) > 0:
print(self.customer_name + "'s Shopping Cart - " + str(self.current_date))
print()
print('Item Descriptions')
for j in self.cart_items:
j.print_item_description()
else:
print('SHOPPING CART IS EMPTY')
def print_menu(cart):
print('MENU')
print('a - Add item to cart')
print('r - Remove item from cart')
print('c - Change item quantity')
print("i - Output items' descriptions")
print('o - Output shopping cart')
print('q - Quit')
**def execute_menu(option, Cart):
while option != 'q':
if option == 'o':
print('OUTPUT SHOPPING CART')
Cart.print_total()
break
elif option == 'i':
print("OUTPUT ITEMS' DESCRIPTIONS")
Cart.print_descriptions()
break
elif option == 'a':
print('ADD ITEM TO CART')
print('Enter the item name:')
itemName = input()
print('Enter the item description:')
itemDescrip = input()
print('Enter the item price:')
itemPrice = int(input())
print('Enter the item quantity:')
itemQuan = int(input())
New_cart = ItemToPurchase()
New_cart.name = itemName
New_cart.quantity = itemQuan
New_cart.price = itemPrice
New_cart.description = itemDescrip
Cart.add_item(New_cart)
break
elif option == 'r':
print('REMOVE ITEM FROM CART')
print('Enter name of item to remove:')
ItemName = input()
Cart.remove_item(ItemName)
break
elif option == 'c':
print('CHANGE ITEM QUANTITY:')
print('Enter the item name:')
Item_Name = input()
print('Enter the new quantity:')
Item_Quantity = int(input())
item_s = ItemToPurchase()
item_s.item_quantity(Item_Quantity)
Cart.modify_item(item_s, Item_Name)
break**
if __name__ == "__main__":
print("Enter customer's name:")
customer = input()
print("Enter today's date:")
date = input()
print()
print('Customer name:', customer)
print("Today's date:", date)
Cart = ShoppingCart(customer, date)
option = ''
print()
print_menu(Cart)
print()
print('Choose an option:')
option = input().lower().strip()
execute_menu(option, Cart)
The reason why I am adding the break is cause the program keeps printing the end print item infinit amount of times if I do not add the break.
Any help is appreciated. thank you and have a great day ahead!
class volunteerList:
def __init__ (self, groupName):
self.__vList = []
self.__groupName = groupName
def setGroupName (self, newGroupName):
self.__groupName = newGroupName
def getGroupName (self):
return self.__groupName
def getvList (self):
return self.__vList
def addVolunteer (self, volunteer):
self.getvList().append(volunteer)
def highestHour (self):
details = ""
highestHourList = []
highest = self.__vList[0].getHourContribution()
for volunteer in self.__vList:
hour = volunteer.getHourContribution()
if hour == highest:
highestHourList.append(hour)
elif hour > highest:
highestHourList = [hour]
highest = hour
#highestHourList.append(hour)
if volunteer.getType().lower() == "f":
details = details + "{} - {} years old - flood volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "p":
details = details + "{} - {} years old - pandemic volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "e":
details = details + "{} - {} years old - earthquake volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "t":
details = details + "{} - {} years old - tsunami volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
return details
def main ():
groupName = input("Enter your group name: ")
newGroup = volunteerList(groupName)
print ("\n")
choice = menu()
while choice != "0":
if choice == "1":
name = input("Name of volunteer? ")
age = int(input("Age? "))
volunteerType = input("Type of volunteer ('F/P/E/T'): ")
volunteerType = volunteerType.lower()
while volunteerType not in "fpet":
print ("Invalid type! Please enter again!")
volunteerType = input("Type of volunteer ('F/P/E/T'): ")
volunteerType = volunteerType.lower()
hourCont = int(input("Contribution hour? "))
while hourCont <= 0:
print ("Invalid value! Please enter again!")
hourCont = int(input("Contribution hour? "))
newGroup.addVolunteer(volunteer(name, age, volunteerType, hourCont))
print ("... Volunteer has been added successfully.")
print ("\n")
choice = menu()
elif choice == "6":
print ("Volunteer with highest contribution hour:")
print (newGroup.highestHour())
print ("\n)
I'm not sure the code on highestHour() correct or wrong. I was planning to find the highest hour of the volunteer(s). If there are more than 1 highest hour of volunteer (same hour), display everything. My output was only one highest hour of volunteer or display 2 same line of statement instead of the example before.
Wondering how to display all volunteer that are highest hour?
The display sample will be:
a - 36 years old - pandemic volunteer
b - 25 years old - flood volunteer
Here you go:
class volunteer:
def __init__ (self, name, age, type, hourContribution):
self.__name = name
self.__age = age
self.__type = type
self.__hourContribution = hourContribution
def getHourContribution (self):
return self.__hourContribution
class volunteerList:
def __init__ (self, groupName):
self.vList = []
self.__groupName = groupName
def highestHour (self):
highHourList = []
hourList = []
for volunteer in self.vList:
hourList.append(volunteer.getHourContribution())
highest = max(hourList)
for hour in hourList:
if hour == highest:
highHourList.append(hour)
print(highHourList)
new = volunteerList("one")
vol1 = volunteer("", 1, "", 5)
vol2 = volunteer("", 1, "", 10)
vol3 = volunteer("", 1, "", 10)
vol4 = volunteer("", 1, "", 10)
vol5 = volunteer("", 1, "", 1)
new.vList = [vol1, vol2, vol3, vol4, vol5]
new.highestHour()
Alternative highestHour function
def highestHour (self):
highHourList = []
largest = self.vList[0].getHourContribution()
for volunteer in self.vList:
hour = volunteer.getHourContribution()
if hour == largest:
highHourList.append(hour)
elif hour > largest:
highHourList = [hour]
largest = hour
print(highHourList)
Needs some cleaning up, but you get the idea.
I started Python and struggle on using __repr__ data outside of a class. Printing the data outputs a list with lists (exactly what I wanted to do), example:
print(test) leads to:
[['Food', '-10.15', '-15.89', '-50'], ['Clothing', '-25.55'], ['Auto', '-15']]
My problem is:
print(test[0]) leads to unexpected outputs, not:
['Food', '-10.15', '-15.89', '-50']
rather than some data like:
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
***********Clothing***********
Transfer from Food 50.00
-25.55
Total: 24.45
*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
Total: 923.96
None
.***********Business***********
deposit 900.00
-10.99
class Category:
def __init__(self, category):
self.category = category
self.balance = 0
self.ledger = []
def __repr__(self):
b = []
b.append(self.category)
for obj in self.ledger:
if str(obj['amount'])[0] == "-":
b.append(str(obj['amount']))
return str(b)
def __str__(self):
lengthTop = int((30 - len(str(self.category))) / 2)
output = "*" * lengthTop + self.category + "*" * lengthTop
for entry in self.ledger:
if len(entry['description']) > 23:
x = slice(0, 23)
output += "\n" + entry['description'][x] + ("{:7.2f}".format(entry['amount']))
else:
output += ("\n" + entry['description'] + (" " * (23 - int(len(entry['description'])))) + ("{:7.2f}".format(entry['amount'])))
output += "\n" + "Total:" + ("{:7.2f}".format(self.balance))
return output
def check_funds(self, amount):
if amount > self.balance:
return False
else:
return True
def deposit(self, amount, description=""):
self.balance += amount
self.ledger.append({"amount": amount, "description": description})
def withdraw(self, amount, description=""):
if self.check_funds(amount) == True:
self.balance -= amount
self.ledger.append({"amount": -amount, "description": description})
return True
else:
return False
def get_balance(self):
return self.balance
def transfer(self, amount, newcategory):
if self.check_funds(amount) == True:
self.withdraw(amount, "Transfer to " + newcategory.category)
newcategory.deposit(amount, "Transfer from " + self.category)
return True
else:
return False
def create_spend_chart(categories):
test = categories
print(test)
I'm creating an invoice program that allows the user to select an item from a menu of products to either purchase or return. Once the user inputs the item ID and quantity desired, the program will read the inventory.txt file and write an UpdatedInventory.txt file, which will replace the inventory.txt file.
The inventory.txt file is formatted like this:
ID
item
stock
price
When my program runs, it does not print correctly on the UpdatedInventory.txt file. There's a lot of code here so bear with me.
As an aside, I feel like it would simplify the code if every purchase the user made was added into a list rather than hard coded. Thanks for the help!
Here's my main code:
import InventoryFile
import os
def readFile ():
#open the file and read the lines
inventoryFile = open ('Inventory.txt', 'r')
raw_data = inventoryFile.readlines ()
#remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip ('\n')
clean_data.append (clean_item)
#read lists into objects
all_objects = []
for i in range (0, len(clean_data), 4):
ID = clean_data [i]
item = clean_data [i+1]
qty = float (clean_data [i+2])
price = float (clean_data [i+3])
#create inventory object
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
all_objects.append (inventory_object)
return all_objects
def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print (item)
print ()
print ('Enter another item ID or 0 to stop')
def modify ():
found = False
search = -1
while search == -1:
search = input ('Enter the ID of the product you would like to purchase: ')
try:
if search == '0':
print ('The inventory has been updated...')
break
except Exception:
search = -1
print ('ERROR: Please enter a valid number.')
else:
inventoryFile = open ('inventory.txt', 'r')
temp_file = open ('UpdatedInventory.txt', 'w')
ID = str (inventoryFile.readline ())
while ID != '':
item = str (inventoryFile.readline ())
qty = float (inventoryFile.readline ())
price = float (inventoryFile.readline())
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
ID = ID.rstrip ('\n')
if ID == search:
purchase = -1
while purchase == -1:
purchaseEntry = float (input ('How many would you like to purchase? Negative numbers are returns'))
purchase = inventory_object.purchase (purchaseEntry)
if purchase is False:
purchase = -1
print ('ERROR: Insufficient stock!')
new_qty = inventory_object.restock (purchase)
transaction_object = InventoryFile.TransactionItem (ID, item, new_qty, price)
transaction_object.set_id (ID)
transaction_object.set_name (item)
transaction_object.set_qty (new_qty)
transaction_object.set_price (price)
ID = transaction_object.get_id ()
item = transaction_object.get_name ()
qty = transaction_object.get_qty ()
price = transaction_object.get_price ()
temp_file.write (ID + '\n')
temp_file.write (item + '\n')
temp_file.write (str (qty) + '\n')
temp_file.write (str (price) + '\n')
found = True
else:
temp_file.write (ID + '\n' )
temp_file.write (item + '\n')
temp_file.write (str (new_qty) + '\n')
temp_file.write (str (price) + '\n')
ID = inventoryFile.readline ()
if found:
print ('The file has been updated.')
else:
print ('That item was not found in the file.')
inventoryFile.close ()
temp_file.close ()
os.remove ('inventory.txt')
os.rename ('UpdatedInventory.txt', 'inventory.txt')
print ('Inventory has been updated.')
break
return search
def main ():
all_items = readFile ()
printMenu (all_items)
modify ()
main ()
Here's my Inventory Class file:
class Inventory ():
def __init__ (self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id (self):
return self.__id
def get_name (self):
return self.__name
def get_stock (self):
return self.__stock
def get_price (self):
return self.__price
def restock (self, new_stock):
if new_stock < 0:
print ('ERROR')
return False
else:
self.__stock += new_stock
return True
def purchase (self, purch_qty):
if self.__stock >= purch_qty:
self.__stock -= purch_qty
return self.__stock
else:
print ('ERROR: Insufficient stock')
return False
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__stock, '7.2f') + format (self.__price, '7.2f')
class TransactionItem (Inventory):
def __init__ (self, new_id, new_name, new_qty, new_price):
self.__qty = new_qty
Inventory.__init__(self, new_id, new_name, new_qty, new_price)
def get_id (self):
return self.__id
def set_id (self, new_id):
self.__id = new_id
def get_name (self):
return self.__name
def set_name (self, new_name):
self.__name = new_name
def get_qty (self):
return self.__qty
def set_qty (self, new_qty):
self.__qty = new_qty
def get_price (self):
return self.__price
def set_price (self, new_price):
self.__price = new_price
def calc_cost (self):
total = purch_qty * self.__price
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \
format (total, '7.2f')
Here is my inventory.txt file:
244
Large Cake Pan
7
19.99
576
Assorted Sprinkles
3
12.89
212
Deluxe Icing Set
6
37.97
827
Yellow Cake Mix
3
1.99
194
Cupcake Display Board
2
27.99
285
Bakery Boxes
7
8.59
736
Mixer
5
136.94
And here is what the updated inventory txt looks like after I input product ID 244, and purchase quantity of 5.
244
Large Cake Pan
4.0
19.99
576
Assorted Sprinkles
4.0
12.89
212
Deluxe Icing Set
4.0
37.97
827
Yellow Cake Mix
4.0
1.99
194
Cupcake Display Board
4.0
27.99
285
Bakery Boxes
4.0
8.59
736
Mixer
4.0
136.94
I've disabled TransactionItem. This seems to be working (I've combined the script files):
import os
class Inventory ():
def __init__(self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id(self):
return self.__id
def get_name(self):
return self.__name
def get_stock(self):
return self.__stock
def get_price(self):
return self.__price
def restock(self, new_stock):
if new_stock < 0:
print('ERROR')
return False
else:
self.__stock += new_stock
return True
def purchase(self, purch_qty):
if self.__stock >= purch_qty:
self.__stock -= purch_qty
return self.__stock
else:
print('ERROR: Insufficient stock')
return False
def __str__(self):
return self.__id + '\t' + self.__name + '\t' + \
format(self.__stock, '7.2f') + format(self.__price, '7.2f')
class TransactionItem (Inventory):
def __init__(self, new_id, new_name, new_qty, new_price):
self.__qty = new_qty
Inventory.__init__(self, new_id, new_name, new_qty, new_price)
def get_id(self):
return self.__id
def set_id(self, new_id):
self.__id = new_id
def get_name(self):
return self.__name
def set_name(self, new_name):
self.__name = new_name
def get_qty(self):
return self.__qty
def set_qty(self, new_qty):
self.__qty = new_qty
def get_price(self):
return self.__price
def set_price(self, new_price):
self.__price = new_price
def calc_cost(self):
self.total = purch_qty * self.__price
def __str__(self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__qty, '7.2f') + format (self.__price, '7.2f') + \
format(self.total, '7.2f')
def readFile():
# open the file and read the lines
inventoryFile = open('Inventory.txt', 'r')
raw_data = inventoryFile.readlines()
# remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip('\n')
clean_data.append(clean_item)
# read lists into objects
all_objects = []
for i in range(0, len(clean_data), 4):
ID = clean_data[i]
item = clean_data[i + 1]
qty = float(clean_data[i + 2])
price = float(clean_data[i + 3])
# create inventory object
inventory_object = Inventory(ID, item, qty, price)
all_objects.append(inventory_object)
return all_objects
def printMenu(all_data):
print()
print('Select an item ID to purchase or return: ')
print()
print('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print(item)
print()
print('Enter another item ID or 0 to stop')
def modify():
found = False
search = -1
while search == -1:
search = input(
'Enter the ID of the product you would like to purchase: ')
try:
if search == '0':
print('The inventory has been updated...')
break
except Exception:
search = -1
print('ERROR: Please enter a valid number.')
else:
inventoryFile = open('inventory.txt', 'r')
temp_file = open('UpdatedInventory.txt', 'w')
ID = str(inventoryFile.readline())
while ID != '':
item = str(inventoryFile.readline())
qty = float(inventoryFile.readline())
price = float(inventoryFile.readline())
inventory_object = Inventory(ID, item, qty, price)
ID = ID.rstrip('\n')
item = item.rstrip('\n')
if ID == search:
purchase = -1
while purchase == -1:
purchaseEntry = float(
input('How many would you like to purchase? Negative numbers are returns'))
purchase = inventory_object.purchase(purchaseEntry)
if purchase is False:
purchase = -1
print('ERROR: Insufficient stock!')
#new_qty = inventory_object.restock(purchase)
#transaction_object = TransactionItem(
# ID, item, new_qty, price)
#transaction_object.set_id(ID)
#transaction_object.set_name(item)
#transaction_object.set_qty(new_qty)
#transaction_object.set_price(price)
#ID = transaction_object.get_id()
#item = transaction_object.get_name()
#qty = transaction_object.get_qty()
#price = transaction_object.get_price()
qty = inventory_object.get_stock()
price = inventory_object.get_price()
temp_file.write(ID + '\n')
temp_file.write(item + '\n')
temp_file.write(str(int(qty)) + '\n')
temp_file.write(str(price) + '\n')
found = True
else:
temp_file.write(ID + '\n')
temp_file.write(item + '\n')
temp_file.write(str(int(qty)) + '\n')
temp_file.write(str(price) + '\n')
ID = inventoryFile.readline()
if found:
print('The file has been updated.')
else:
print('That item was not found in the file.')
inventoryFile.close()
temp_file.close()
os.remove('inventory.txt')
os.rename('UpdatedInventory.txt', 'inventory.txt')
print('Inventory has been updated.')
break
return search
def main():
all_items = readFile()
printMenu(all_items)
modify()
main()
I hope it helps!
Have you tried stepping thru the program?
https://docs.python.org/2/library/pdb.html or https://docs.python.org/3/library/pdb.html
at some point you're losing information
(its hard to troubleshoot that big block of code sadly)
import sys
import os.path
class Juvenile(object):
def createJuv(self, pop, rate):
self.pop = pop
self.rate = rate
def displayJuvpop(self):
return self.pop
def displayjuvRate(self):
return self.rate
class Adult(object):
def createAd(self, pop, rate, brate):
self.pop = pop
self.rate = rate
self.brate = brate
def displayAdpop(self):
return self.pop
def displayAdRate(self):
return self.rate
def displayBirthrate(self):
return self.brate
class Senile(object):
def createSe(self, pop, rate):
self.pop = pop
self.rate = rate
def displaySepop(self):
return self.pop
def displaySerate(self):
return self.rate
a = Juvenile()
b = Adult()
c = Senile()
`enter code here`pop_model = raw_input("Enter the number of generations: ")
`enter code here`pop_model = int(pop_model)
newjuv = 0
newsen = 0
newadu = 0
def menu():
This = True
while This == True:
print("1) Enter Generation 0 values")
print("2) Display Generation 0 values")
print("3) Run the model")
print("4) Export data")
print("5) Quit")
decision = raw_input("")
if decision == "1":
Gen0values()
elif decision == "2":
display()
elif decision == "3":
run()
elif decision == "4":
export()
elif decision == "5":
sys.exit()
def run():
print("Juvenile" + " " + "Adult" + " " + "Senile")
for i in range(0, pop_model):
newjuv = b.displayAdpop()* b.displayBirthrate()
newsen = b.displayAdpop() * b.displayAdRate()
newadu = a.displayJuvpop() * a.displayjuvRate()
print(i + 1,newjuv, newadu,newsen)
a.displayJuvpop() = newjuv
b.displayAdpop() = newsen
c.displaySepop() = newadu
def Gen0values():
a.createJuv(float(raw_input("Enter the juvenile population: ")), float(raw_input("Enter the Juvenile survival rate: ")))
b.createAd(float(raw_input("Enter the Adult population: ")), float(raw_input("Enter the Adult survival rate: ")), float(raw_input("Enter the birth rate: ")))
c.createSe(float(raw_input("Enter the Senile population: ")), float(raw_input("Enter the Senile survival rate: ")))
menu()
The error is coming up here:
def run():
print("Juvenile" + " " + "Adult" + " " + "Senile")
for i in range(0, pop_model):
newjuv = b.displayAdpop()* b.displayBirthrate()
newsen = b.displayAdpop() * b.displayAdRate()
newadu = a.displayJuvpop() * a.displayjuvRate()
print(i + 1,newjuv, newadu,newsen)
a.displayJuvpop() = newjuv
b.displayAdpop() = newsen
c.displaySepop() = newadu
The error comes up with "Can't assign to function call, line 60". Due to stack overflow's code to text limit, I've removed parts of the program that are irrelevant, like exporting the data and displaying the values.
Ps: This isn't an indentation error, copying and pasting somewhat disrupted it.
Your display*pop() functions return a value, not a variable. You can't assign to that function result. Just assign directly to the attributes:
a.pop = newjuv
b.pop = newsen
c.pop = newadu