I want to export all the entries to an excel file - python

#bll
import pickle
import pandas as pd
class Customer:
cuslist=[]
def __repr__(self):
return(str(self))
def __init__(self):
self.id=0
self.age=0
self.name=0
self.dateofBirth = 0
self.address = 0
self.phoneNumber = 0
self.amount = 0
self.zipCode = 0
self.experience = 0
self.form = 0
def addcustomer(self):
Customer.cuslist.append(self)
def searchcustomer(self):
for e in Customer.cuslist:
if(e.id==self.id):
self.age=e.age
self.name=e.name
self.dateofBirth = e.dateofBirth
self.address = e.address
self.phoneNumber = e.phoneNumber
self.amount = e.amount
self.zipCode = e.zipCode
self.experience = e.experience
self.form = e.form
break
def deletecustomer(self):
for e in Customer.cuslist:
if (e.id == self.id):
Customer.cuslist.remove(e)
break
def updatecustomer(self):
for e in Customer.cuslist:
if(e.id==self.id):
e.age=self.age
e.name=self.name
e.dateofBirth = self.dateofBirth
e.address = self.address
e.phoneNumber = self.phoneNumber
e.amount = self.amount
e.zipCode = self.zipCode
e.experience = self.experience
e.form = self.form
break
#staticmethod
# def convertoExcel(self):
# df = pd.DataFrame(Customer.cuslist.self)
# writer = pd.ExcelWriter('pandas.xlsx', engine='xlsxwriter')
# df.to_excel(writer, sheet_name='Sheet1')
# writer.save()
#staticmethod
def savetoPickle():
f=open("D://cetpa//mypickle.txt","wb")
pickle.dump(Customer.cuslist,f)
f.close()
#staticmethod
def loadfromPickle():
f = open("D://cetpa//mypickle.txt", "rb")
Customer.cuslist=pickle.load(f)
f.close()
#pl
if (__name__ == "__main__"):
while(1):
print("Enter 1 to Add Customer")
print("Enter 2 to Search Customer")
print("Enter 3 to Delete Customer")
print("Enter 4 to Modify Customer")
print("Enter 5 to Display All Customer")
print("Enter 6 to Exit")
ch = input("Enter A Number: ")
if(ch=='1'):
cus=Customer()
cus.id=input("enter id: ")
cus.age = input("enter age: ")
cus.name = input("enter name: ")
cus.dateofBirth = input("enter date of birth: ")
cus.addcustomer()
print("Added Successfully!!")
elif(ch=="2"):
cus=Customer()
cus.id=input("Enter Customer ID: ")
cus.searchcustomer()
print("Customer ID: ",cus.id, "Customer Age: ", cus.age, "Customer Name: ",cus.name)
elif(ch=="3"):
cus=Customer()
cus.id=input("Enter Customer ID: ")
cus.deletecustomer()
print("Entry Deleted!!")
elif(ch=='4'):
cus=Customer()
cus.id=input("Enter Customer ID: ")
cus.age=input("Enter Updated Customer Age: ")
cus.name=input("Enter Updated Customer Name: ")
cus.updatecustomer()
print("Customer Updated Successfully!!")
elif(ch=='5'):
cus=Customer()
for e in Customer.cuslist:
print("Customer ID: ",e.id)
print("Customer Age",e.age)
print("Customer Name: ",e.name)
print("Customer Date of Birth: ",e.dateofBirth)
elif (ch == '6'):
Customer.savetoPickle()
elif (ch == '7'):
Customer.loadfromPickle()
elif (ch == '8'):
print(Customer.cuslist)

Look into openpyxl.
It's a python module that lets you do stuff like this:
from openpyxl import Workbook
book = Workbook()
sheet = book.active
sheet['A1'] = "name"
sheet['A2'] = customer1.name
sheet['A3'] = customer2.name
sheet['B1'] = "age"
sheet['B2'] = customer1.age
sheet['B3'] = customer2.age
book.save("my_excel_file.xlsx")

Related

how to extract only text but not the object using pandas and output a report

I am required to generate a report to like in the question shown, but when I write the display function, I found that I cannot extract pure text from the excel file, and also, when I try to print the information using the f string, the code cell went into infinite loop, how can I fixe this?
here is the questionenter image description here
and here is the code I wrote
`#import the necessary module
import pandas as pd
#read the two excel files
consultant = pd.read_excel('SalesConsultants.xlsx')
manager = pd.read_excel('SalesManagers.xlsx')
#ask the user if they want to check consultant, manager or quit
def get_input():
print("1. Search data of sales consulatant; \
2. Search data of sales manager; \
3. Quit.")
user_input = input("Please enter your choice(1, 2, 0) --> ")
return user_input
#ask the user to input the consultant id if 1 is chosen
def get_consultant_id():
consultant_id = input("Please enter consultant ID: ")
return consultant_id
#ask the user to input the manager id if 2 is chosen
def get_manager_id():
manager_id = input("Please enter manager ID: ")
return manager_id
#validate the consultant_id
def validate_consultant_id(consultant_id):
for item in consultant['AgentID']:
#to check if the consultant id exists
if consultant_id in item:
return True
else:
print(f"No agent ID {consultant_id} exist.")
return False
#validate the manager_id
def validate_manager_id(manager_id):
for item in manager['SID']:
#to check if the consultant id exists
if manager_id in item:
return True
else:
print(f"No manager ID {manager_id} exist.")
return False
#function to get the name, sales and calculate the annual sales of the agent
def get_consultant_name_sales(consultant_id):
name = consultant[consultant.AgentID == consultant_id]['AgentName']
sales_q1 = consultant[consultant.AgentID == consultant_id]['Q1'].sum()
sales_q2 = consultant[consultant.AgentID == consultant_id]['Q2'].sum()
sales_q3 = consultant[consultant.AgentID == consultant_id]['Q3'].sum()
sales_q4 = consultant[consultant.AgentID == consultant_id]['Q4'].sum()
total = sales_q1 + sales_q2 + sales_q3 + sales_q4
return name, sales_q1, sales_q2, sales_q3, sales_q4, total
#function to get the name, sales and calculate the annual sales of the manager
def get_manager_name_sales(manager_id):
name = manager[manager.SID == manager_id]['Supervisor']
sales_q1 = consultant[consultant.SID == manager_id]['Q1'].sum()
sales_q2 = consultant[consultant.SID == manager_id]['Q2'].sum()
sales_q3 = consultant[consultant.SID == manager_id]['Q3'].sum()
sales_q4 = consultant[consultant.SID == manager_id]['Q4'].sum()
total = sales_q1 + sales_q2 + sales_q3 + sales_q4
return name, sales_q1, sales_q2, sales_q3, sales_q4, total
#function to desplay the report of the consultant
def display_consultant(consultant_id, name, sales_q1, sales_q2, sales_q3, sales_q4, total):
print(name)
print(sales_q1)
print(sales_q2)
print(sales_q3)
print(sales_q4)
print(total)
#function to desplay the report of the manager
def display_manager(manager_id, name, sales_q1, sales_q2, sales_q3, sales_q4, total):
print(name, manager_id)
print(sales_q1)
print(sales_q2)
print(sales_q3)
print(sales_q4)
print(total)
# the main body to run all functions
while True:
user_input = get_input()
if user_input == '1':
consultant_id = get_consultant_id()
validation = validate_consultant_id(consultant_id)
if validation == True:
name, sales_q1, sales_q2, sales_q3, sales_q4, total = get_consultant_name_sales(consultant_id)
display_consultant(consultant_id, name, sales_q1, sales_q2, sales_q3, sales_q4, total)
else:
continue
elif user_input == '2':
manager_id = get_manager_id()
validation = validate_manager_id(manager_id)
if validation == True:
name, sales_q1, sales_q2, sales_q3, sales_q4, total = get_manager_name_sales(manager_id)
display_manager(manager_id, name, sales_q1, sales_q2, sales_q3, sales_q4, total)
else:
continue
elif user_input == '0':
break
else:
print("Please follow the instruction")
continue
`

My function menu.displayHomeMenu(m) is stuck in an infinite loop. Why?

In the code below, I want the menu to display and prompt the user for a selection. Based on the selection, I want to move on to the following if statements which allow the user to define the attributes of their vehicle. The code worked before I put the menu in a function, but this format is required for my assignment. No errors. It simply prompts for a selection over and over again. Any suggestions?
class Menu:
""" Create a Menu """
def __init__(self):
self.selection = selection
def displayHomeMenu(self):
if 2 == vehicleCount:
print("----Press 1 for car ")
print("----Press 2 for pickup ")
selection = input("----Press 3 to quit ")
return selection
else:
print("----Press 1 for car ")
selection = input("----Press 2 for pickup ")
return selection
class Vehicle:
""" Model a vehicle"""
def __init__(self, make = " ", model = "n/a", color = "n/a ", fuelType = "n/a ", *options):
""" Initialize vehicle attributes """
self.make = make
self.model = model
self.color = color
self.fuelType = fuelType
self.options = {"power windows", "powerlocks", "remote start", "backup camera", "bluetooth", "cruise control", "heated seats", "heated steering wheel"}
def getMake(self):
self.make = input("Please enter your make ")
return self.make
def getModel(self):
self.model = input("Please enter your model ")
return self.model
def getColor(self):
self.color = input("Please enter the color ")
return self.color
def getFuelType(self):
self.fuelType = input("Please enter your fuel type ")
return self.fuelType
def getOptions(self):
print("Please select from the following options: ")
input(self.options)
return self.options
class Car(Vehicle):
"""Represents a car"""
def __init__(self, make = "n/a ", model = "n/a", color = "n/a ", fuelType = "n/a "):
super().__init__(make, model, color, fuelType)
""" Initialize car attributes"""
self.engineSize = " "
self.numDoors = " "
def getEngineSize(self):
self.engineSize = input("Please enter your engine size ")
return self.engineSize
def getNumDoors(self):
self.numDoors = input("How many doors do you have ")
return self.numDoors
class pickup(Vehicle):
"""Represents a pickup"""
def __init__(self, make = " ", model = " ", color = " ", fuelType = " "):
super().__init__(make, model, color, fuelType)
""" Initialize pickup attributes """
self.cabStyle = " "
self.bedLength = " "
def getCabStyle(self):
self.cabStyle = input("Please enter your cab style ")
def getBedLength(self):
self.bedLength = input("Please enter the length of your bed ")
i = 0
list = []
vehicleCount = 0
carCount = 0
pickupCount = 0
selection = 0
while True:
vehicleCount = pickupCount + carCount
m = Menu()
Menu.displayHomeMenu(m)
if selection == "1":
# Processing for item found
c = Car(Vehicle)
Vehicle.getMake(c)
Vehicle.getModel(c)
Vehicle.getColor(c)
Vehicle.getFuelType(c)
Car.getEngineSize(c)
Car.getNumDoors(c)
newcar = vars(c)
list.append(newcar)
if carCount < 1:
carCount = carCount + 1
else:
pass
elif selection == "2":
# Processing for item not found
p = pickup(Vehicle)
Vehicle.getMake(p)
Vehicle.getModel(p)
Vehicle.getColor(p)
Vehicle.getFuelType(p)
pickup.getCabStyle(p)
pickup.getBedLength(p)
newpickup = vars(p)
list.append(newpickup)
if pickupCount < 1:
pickupCount = pickupCount + 1
else:
for i in list:
print(i)
You are not using the return value from displayHomeMenu():
while True:
vehicleCount = pickupCount + carCount
m = Menu()
selection = m.displayHomeMenu() # Assign the return value to selection
if selection == "1":
# Processing for item found
c = Car(Vehicle)
Vehicle.getMake(c)
Vehicle.getModel(c)
Vehicle.getColor(c)
Vehicle.getFuelType(c)
Car.getEngineSize(c)
Car.getNumDoors(c)
newcar = vars(c)
list.append(newcar)
if carCount < 1:
carCount = carCount + 1
else:
pass
elif selection == "2":
# Processing for item not found
p = pickup(Vehicle)
Vehicle.getMake(p)
Vehicle.getModel(p)
Vehicle.getColor(p)
Vehicle.getFuelType(p)
pickup.getCabStyle(p)
pickup.getBedLength(p)
newpickup = vars(p)
list.append(newpickup)
if pickupCount < 1:
pickupCount = pickupCount + 1
else:
for i in list:
print(i)

Trying to compare two strings in python

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)

Create a list of a class as an attribute of a second class in Python

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

Accessing method from objects in a dictionary

is it possible to access to an external class method from a loop into a dictionary?
Here 2 examples, one access by a loop into a list and the other one by a dictionary. The first one does the job I'd like to reach with the dictionary (the second one):
ins.py
class Ins:
def __init__(self, cognome, nome, indirizzo, entrate, spese):
self.__cognome = cognome
self.__nome = nome
self.__indirizzo = indirizzo
self.__entrate = entrate
self.__spese = spese
def get_cognome(self):
return self.__cognome
def get_nome(self):
return self.__nome
def get_indirizzo(self):
return self.__indirizzo
def get_totale(self):
return str(float(self.__entrate) - float(self.__spese))
def __str__(self):
return "Cognome: " + self.__cognome + "\nNome: " + self.__nome + \
"\nIndirizzo: " + self.__indirizzo +\
"\nEntrate: " + self.__entrate + "\nSpese: " + self.__spese
ins_main_list.py
import ins
dict = []
def main():
again = 'y'
while again.lower() == 'y':
cognome = input('Inserire Cognome: ')
nome = input('Inserire Nome: ')
indirizzo = input('Inserire Indirizzo: ')
entrate = input('Inserire Entrate: ')
spese = input('Inserire Spese: ')
again = input("Continuare con l'inserimento? (Y/N) ")
print()
entry = ins.Ins(cognome, nome, indirizzo, entrate, spese)
dict.append(entry)
for item in dict:
print(item)
print(item.get_totale())
print()
main()
ins_main_dict.py
import ins
dict = {}
def main():
again = 'y'
while again.lower() == 'y':
cognome = input('Inserire Cognome: ')
nome = input('Inserire Nome: ')
indirizzo = input('Inserire Indirizzo: ')
entrate = input('Inserire Entrate: ')
spese = input('Inserire Spese: ')
again = input("Continuare con l'inserimento? (Y/N) ")
print()
entry = ins.Ins(cognome, nome, indirizzo, entrate, spese)
dict[cognome] = entry
for item in dict:
print(dict[item])
print(item.get_totale())
print()
main()
As you can see in the last example item.get_totale() give me an attribute error. How is possible to access into it?
I believe you should be doing dict[item].get_totale(), not item.get_totale(). item is iterating over the keys of dict (which are strings), not your custom class

Categories

Resources