def warehouseInventoryCreationBios():
bios = []
warehouseName = ["\nWarehouse: WBS"]
bios.append(warehouseName)
warehouse_initial_quantity_aircondSec = 1000
aircondSec = ["Section: AS", "Parts: compressor", "Part ID: ABS01", "Initial Quantity in the warehouse:", warehouse_initial_quantity_aircondSec, '\n']
bios.append(aircondSec)
.
.
return bios
warehouseInventoryCreationBios()
def updateBiosWarehouseInventory():
bios = warehouseInventoryCreationBios()
warehouseUpdateSupplier = []
name = input('Enter Supplier name: ')
name = name.lower()
id_parts = input('The id of the part: ')
id_parts = id_parts.upper()
order_from_supplier = int(input('How many orders from supplier: '))
warehouseUpdateSupplier.append(name)
warehouseUpdateSupplier.append(id_parts)
warehouseUpdateSupplier.append(str(order_from_supplier))
if name == 'tab':
if id_parts == "ABS01" or id_parts == "TBS05" or id_parts == "BBS02":
if id_parts == "ABS01":
compressor_quantity_warehouse = warehouse_initial_quantity_aircondSec + order_from_supplier
return compressor_quantity_warehouse
.
.
return warehouseUpdateSupplier
updateBiosWarehouseInventory()
Input: Enter Supplier name: tab
The id of the part: abs01
How many orders from supplier: 100
Output: NameError: name 'warehouse_initial_quantity_aircondSec' is not defined
How can I add the value warehouse_initial_quantity_aircondSec in the first function with the warehouse_initial_quantity_aircondSec in the second function
Newbie here, sorry ><
You are trying to use a variable in the second function, which is defined in the first as a local variable, you should return that value to use it:
def warehouseInventoryCreationBios():
bios = []
warehouseName = ["\nWarehouse: WBS"]
bios.append(warehouseName)
warehouse_initial_quantity_aircondSec = 1000
aircondSec = ["Section: AS", "Parts: compressor", "Part ID: ABS01", "Initial Quantity in the warehouse:", warehouse_initial_quantity_aircondSec, '\n']
bios.append(aircondSec)
.
.
# return multiple values (as tuple)
return bios, warehouse_initial_quantity_aircondSec
warehouseInventoryCreationBios() # this line is unnecessary, only calculations with no results used after it
def updateBiosWarehouseInventory():
# receive multiple values
bios, warehouse_initial_quantity_aircondSec = warehouseInventoryCreationBios()
warehouseUpdateSupplier = []
name = input('Enter Supplier name: ')
name = name.lower()
id_parts = input('The id of the part: ')
id_parts = id_parts.upper()
order_from_supplier = int(input('How many orders from supplier: '))
warehouseUpdateSupplier.append(name)
warehouseUpdateSupplier.append(id_parts)
warehouseUpdateSupplier.append(str(order_from_supplier))
if name == 'tab':
if id_parts == "ABS01" or id_parts == "TBS05" or id_parts == "BBS02":
if id_parts == "ABS01":
compressor_quantity_warehouse = warehouse_initial_quantity_aircondSec + order_from_supplier
return compressor_quantity_warehouse
.
.
return warehouseUpdateSupplier
updateBiosWarehouseInventory()
Related
I have the following code, however when I run it, the variable stored under employee_name is stated as "Name '[name inputted]' is not defined.
I've tried to comment it out, and the issue just arises with another line. Employee_num needs to be a string, as putting it as an integer claims it to not be iterable.
Can anyone help?
import time
ListNames = []
ListIDs = []
ListComissions = []
total_properties = 0
highest = 0
employee_num = "a"
employee_name = "aa"
employee_id= "a"
employee_properties = "a"
employee_comission = "a"
employee_num = str(input("Enter the number of employees: "))
for y in employee_num:
employee_name = input("Enter the name of the employee: ")
ListNames.append(employee_name)
employee_id = str(input("Enter the ID of the employee: "))
ListIDS.append(employee_id)
employee_properties = int(input("Enter the number of properties sold by the employee: "))
ListProperties.append(employee_properties)
total_properties = total_properties + employee_properties
employee_comission = employee_properties * 500
ListComissions.append(employee_comission)
total_comission = total_comission + employee_comission
for i in ListProperties:
if ListProperties[i] > highest:
highest = ListProperties[i]
i = i + 1
star = ListProperties.index(highest)
print (ListNames[star])
print (ListIDs[star])
print (ListProperties[star])
print (ListComissions[star])
starcomission = ListComissions[star] + (ListComissions[star] * 0.15)
x = 1
for x in employee_num:
if x != star:
print (ListNames[x])
print (ListIDs[x])
print (ListProperties[x])
print (ListComissions[x])
x = x + 1
I am trying to improve this program. I am working with Linux. I want to add a menu function where the user can pick an option and based on the option call the respective function, but the program is not working, when I run it in the Terminal it doesn't do anything and doesn't show any errors. Please, I need help to solve the problem and make the program works. Thanks!
Here's what I have so far, still there are some functions that need to develop:
#! /usr/bin/python3
import sys
def menu(self):
print ("""
1. Add an Expense
2. Remove an Expense
3. Add revenue
4. Remove Revenue
5. Exit
""")
option = input ("What would you like to do [Number Only]?")
if option == "1":
self.add_expense()
elif option == "2":
self.remove_expense()
elif option == "3":
self.add_revenue()
elif option == "4":
self.remove_revenue()
else:
self.reset_program()
self.close_program()
return option
def add_expense(self):
def __init__(self):
self.month_balance = 0
self.expenses = 0
self.expense_list = []
self.expense_name = []
self.month_balance_name = []
self.month_balance_list = []
self.prompt_income()
def month_balance_ask(self):
add_month_balance = input('Add monthly balance? [y/n]: ')
return add_month_balance
def month_balance_sum(self):
self.month_balance = sum(self.month_balance_list)
def expense_ask(self):
add_expense = input('Add expense? [y/n]: ')
return add_expense
def expense_sum(self):
self.expenses = sum(self.expense_list)
def month_balance_check(self):
if not self.month_balance_list:
print('Please enter at least one monthly balance. ')
self.prompt_month_balance()
def expense_check(self):
if not self.expense_list:
print('Please enter at least one expense. ')
self.prompt_expense()
def prompt_month_balance(self):
x = False
while not x:
result = self.month_balance_ask()
if result == 'y':
month_balance_input = int(input('Enter monthly balance. [Numbers Only]: '))
self.month_balance_list.append(month_balance_input)
month_balance_name = input('Enter monthly balance name. [Name Only]: ')
self.month_balance_name.append(month_balance_name)
else:
self.month_balance_check()
x = True
self.month_balance_sum()
name = [name for name in self.month_balance_name]
month_balance = [month_balance for month_balance in self.month_balance_list]
month_balancedict = dict(zip(name, month_balance))
for k in incomedict:
print(k + ': ', '$' + str(month_balancedict[k]))
print('Total user monthly balance: ', '$' + str(self.month_balance))
self.prompt_expense()
def prompt_expense(self):
x = False
while not x:
result = self.expense_ask()
if result == 'y':
expense_input = int(input('Enter expense amount. [Numbers Only]: '))
self.expense_list.append(expense_input)
expense_name = input('Enter expense name. [Name Only]: ')
self.expense_name.append(expense_name)
else:
self.expense_check()
x = True
self.expense_sum()
name = [name for name in self.expense_name]
expense = [income for income in self.expense_list]
expensedict = dict(zip(name, expense))
for k in expensedict:
print(k + ': ', '$' + str(expensedict[k]))
print('Total user expenses: ', '$' + str(self.expenses))
self.added_expense()
def added_expense(self):
expenseadded = self.month_balance - self.expenses
if expenseadded < 0:
print('You are in the negative, you have a deficit of ' + '$' + str(expenseadded))
if expenseadded == 0:
print('You have broken even, you are spending exactly as much as you make.')
if expenseadded > 0:
print('You are in the positive, you have a surplus of ' + '$' + str(expenseadded))
another = input('Would you like to run another analysis? [y/n]: ')
if another == 'y':
self.menu()
else:
self.reset_program()
self.close_program()
def remove_expense(self):
print("code goes here")
def add_revenue(self):
print("code goes here")
def remove_revenue(self):
print("code goes here")
def reset_program(self):
self.month_balance = 0
self.expenses = 0
del self.expense_list[0:]
del self.expense_name[0:]
del self.month_balance_name[0:]
del self.month_balance_list[0:]
self.prompt_month_balance()
def close_program(self):
print('Exiting Program.')
sys.exit(0)
I even used print statements to check if y.name and favourite were the same when checking this and they were yet it still wasn't entering the if statement when using
if y.name == favourite
or
if favourite ==y.name
I'm super confused as to why that is since I thought this was just a standard equality check (The beginning of the code is mostly set up, just included it for context in the case that there was a problem there and not the if statement). Thank you in advance!
class Anime(object):
name: str = ""
year_aired = 0
genre1: str = ""
def __init__(self, name, genre1, year_aired):
self.name = name
self.genre1 = genre1
self.year_aired = year_aired
def _make_anime(name, genre1, year_aired):
anime = Anime()
return anime
animelist = input("Please enter a file with a list of anime\n")
animel = open(animelist, "r")
nolines = animel.readlines()
animearr = []
numanime = -1
for i in nolines:
if i.find("*") != -1:
animearr[numanime].genre1 = i
else:
k = Anime("","", 2018)
k.name = i
animearr.append(k)
numanime += 1
favourite = input("Please enter your favourite anime\n")
favgenre = ""
for y in animearr:
if y.name == favourite:
favgenre = y.genre1
print(favgenre)
I think you should add strip.("\n") before you compare two string.
class Anime(object):
name: str = ""
year_aired = 0
genre1: str = ""
def __init__(self, name, genre1, year_aired):
self.name = name
self.genre1 = genre1
self.year_aired = year_aired
def _make_anime(name, genre1, year_aired):
anime = Anime()
return anime
animelist = input("Please enter a file with a list of anime\n")
animel = open(animelist, "r")
nolines = animel.readlines()
animearr = []
numanime = -1
for i in nolines:
if i.find("*") != -1:
animearr[numanime].genre1 = i
else:
k = Anime("","", 2018)
k.name = i
animearr.append(k)
numanime += 1
favourite = input("Please enter your favourite anime\n")
favgenre = ""
for y in animearr:
if y.name == favourite.strip("\n"):
favgenre = y.genre1
print(favgenre)
I have an intro class in Python where part of the instructions are:
(2) Build the ShoppingCart class with the following data attributes and related methods. Note: Some can be method stubs (empty methods) initially, to be completed in later steps.
Parameterized constructor which takes the customer name and date as parameters
Attributes
customer_name (string) - Initialized in default constructor to "none"
current_date (string) - Initialized in default constructor to "January 1, 2016"
cart_items (list)
Methods
add_item()
Adds an item to cart_items list. Has parameter ItemToPurchase. Does not return anything.
The code is:
class ItemToPurchase:
def __init__(self):
self._name = "none"
self._price = 0
self._quantity = 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 __str__(self):
print("For item " + self._name + ": " + self._description + " there are " + str(self._quantity) + " available at $" + str(self._price) + ".")
def print_item_cost(self):
print(self._name + " " + str(self._quantity) + " # $" + str(self._price) + " = $" + str(self._quantity * self._price))
def print_item_description(self):
print(self._name + ": " + self._description)
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
cart_items = []
_customer_name = name
_current_date = date
def add_item(self, cartItem):
self.cart_items.append(cartItem)
def remove_item(self, item_name):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
if itm._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):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
if itm._name == ItemToPurchase._name:
count += 1
if ItemToPurchase._description != "none":
itm.item_description(ItemToPurchase._description)
if ItemToPurchase._price != 0:
itm.item_price(ItemToPurchase._price)
if ItemToPurchase._quantity != 0:
itm.item_quantity(ItemToPurchase._quantity)
if count == 0:
print(" ")
print("Item not found in cart. Nothing modified.")
def get_num_items_in_cart(self):
count = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
count += itm._quantity
return count
def get_cost_of_cart(self):
cost = 0
itms = self.cart_items[:]
for i in range(len(itms)):
itm = itms[i]
cost += (itm._quantity * itm._price)
return cost
def print_total(self):
print(self._customer_name + "'s Shopping Cart - " + self._current_date)
count = len(self.cart_items)
if count == 0:
print(" ")
print("SHOPPING CART IS EMPTY")
return 0
print("Number of Items: " + str(count))
print(" ")
for itm in self.cart_items:
itm.print_item_cost()
total = self.get_cost_of_cart()
print("Total: $" + str(total))
def print_descriptions(self):
print(self._customer_name + "'s Shopping Cart - " + self._current_date)
print(" ")
print("Item Descriptions")
for itm in self.cart_itmes:
print(itm.item_name() + ": " + itm.item_description())
def print_menu(cart):
print(" ")
print("MENU")
print("a - Add item to cart")
print("r - Remove item from cart")
print("c - Change item quntity")
print("i - Output items' descriptions")
print("o - Output shopping cart")
print("q - Quit")
print(" ")
def main():
#Define Constants and variables
custName = ""
dateToday = ""
custName = input("Enter customer's name: ")
dateToday = input("Enter today's date: ")
print("Customer name: " + custName)
print("Today's date: " + dateToday)
myCart = ShoppingCart(custName,dateToday)
option = ""
while option != "q":
print_menu(myCart)
option = input("Choose an option: ").lower().strip()
if option == "o":
myCart.print_descriptions()
elif option == "a":
print("ADD ITEM TO CART")
itemName = input("Enter the item name: ")
itemDescr = input("Enter the item description: ")
itemPrice = int(input("Enter the item price: "))
itemQuantity = int(input("Enter the item quantity: "))
print(" ")
cartItem = ItemToPurchase()
cartItem.item_name(itemName)
cartItem.item_description(itemDescr)
cartItem.item_price(itemPrice)
cartItem.item_quantity(itemQuantity)
myCart.add_item(cartItem)
elif option == "r":
print("REMOVE ITEM FROM CART")
itemName = input("Enter name of item to remove: ")
myCart.remove_item(itemName)
elif option == "c":
print("CHANGE ITEM QUNATITY")
itemName = input("Enter the item name: ")
itemQuantity = int(input("Enter the new quantity: "))
changeItem = ItemToPurchase(itemName)
changeItem.item_quantity(itemQuantity)
myCart.modify_item(changeItem)
main()
I am getting the following error:
Enter customer's name: Rog
Enter today's date: Oct 20
Customer name: Rog
Today's date: Oct 20
MENU
a - Add item to cart
r - Remove item from cart
c - Change item quntity
i - Output items' descriptions
o - Output shopping cart
q - Quit
Choose an option: a
ADD ITEM TO CART
Enter the item name: Sketchers
Enter the item description: Black
Enter the item price: 120
Enter the item quantity: 2
Traceback (most recent call last): File
"C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 176, in
main() File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 163, in main
myCart.add_item(cartItem) File "C:\PythonWorkspace\Chapter9Assignment\src\onlineShoppingCart2.py",
line 44, in add_item
self.cart_items.append(cartItem) AttributeError: 'ShoppingCart' object has no attribute 'cart_items'
Can anyone tell me what I am doing incorrectly?
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
cart_items = []
_customer_name = name
_current_date = date
These are all local variable. If you want them to be attributes of the instance, you have to explicitly refer to self:
class ShoppingCart:
def __init__(self, name="none", date="January 1, 2016"):
self.cart_items = []
self._customer_name = name
self._current_date = date
Alright so what I am trying to do is to get objects to save in list form when a user creates a NoteSet. It appends the objects to the list db properly when I input NoteSet('ex','example',True). I made a function called makeNewNoteSet() and it seems to be working correctly but it doesnt append to the db list. I can not figure out why.
import sys
import datetime
import pickle
notesets = []
db = []
def save():
global db
filename = "notesets.dat"
file = open(filename, "wb")
if file == None:
print("There was an error creating your file")
return
pickle.dump(db, file)
file.close()
print("Saved words to ",filename)
def load():
global db
filename = "notesets.dat"
file = open(filename, "rb")
db = pickle.load(file)
print("There are ",len(db)," Note Sets")
file.close()
class NoteSet:
nextseqNum = len(db)+2
def __init__(self,name,description,hidden):
global db
self.seqNum = NoteSet.nextseqNum
self.name = name
self.description = description
self.dateCreated = datetime.date.today()
self.hidden = hidden
self.notes = list()
NoteSet.nextseqNum += 1
print(self)
notesets.append(self)
notelist = [self.seqNum,self.name,self.description,self.dateCreated,self.hidden,self.notes]
print(notelist)
db.append(notelist)
NoteSet.nextseqNum += 1
def __str__(self):
printstr = str(self.seqNum),self.name,self.description,str(self.dateCreated)
printstr = str(printstr)
return printstr
class Note:
nextseqNum = 0
def __init__(self,text,dateCreated,description,category,priority,hidden):
self.text = text
self.dateCreated = str
self.dateRead = str
self.description = str
self.category = str
self.priority = int
self.hidden = bool
self.seqNum = Note.nextseqNum
Note.nextseqNum += 1
def main():
while True:
load()
printMainMenu()
selection = int(input("? "))
if selection == 1:
listNoteSets()
elif selection == 2:
listAllNoteSets()
elif selection == 3:
makeNewNoteSet()
elif selection == 4:
selectNoteSet() # this makes the working note set
elif selection == 5:
deleteNoteSet()
elif selection == 6:
sys.exit()
else:
print("Invalid choice")
def printMainMenu():
print("1. List note sets")
print("2. List all note sets (including hidden sets)")
print("3. Make a new note set")
print("4. Select a working note set")
print("5. Delete a note set")
print("6. Quit")
def listNoteSets():
num = 0
for row in db:
if db[num][4] == False:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def listAllNoteSets():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def makeNewNoteSet():
num = 0
name = input("What would you like to name your note set? --- ")
for row in db:
if name == db[num][1]:
print("That note set has already been created")
makeNewNoteSet()
description = input("Describe your note set briefly --- ")
hidden = input("Would you like this note set to be hidden? --- ")
if hidden == 'y' or 'yes':
hidden = True
else:
hidden = False
NoteSet(name, description, hidden)
print("noteset created you can now access it through the menu")
input("[Press enter to return to menu]")
main()
def selectNoteSet():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
response = input("Enter the number assosciated with the noteset you would like to access")
print("Note set #",response," was selected")
main()
After you add a new note in makeNewNoteSet(), you call main() which calls load() which overwrites the in-memory copy of the database you just changed. You probably want to call save() somewhere in there.