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)
Related
#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")
So I have been working on a quizzing application for some time now (about 4 days). I managed to make all the logical part of the code (the quiz taking, the quiz question handling, score outputting, etc.) I know that this code is neither the best nor the most efficient as it can be but I'm just a beginner. Anyways, the get() function for the entry function for tkinter does not return anything. I am aware that there is a way to fix it however I'm not sure how to implement the solution with an external loop. Please help me. Here is my code:
import random
from time import sleep
import tkinter as tk
from tkinter import *
import threading
class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback(self):
self.root.quit()
def run(self):
self.root = tk.Tk()
self.root.protocol("WM_DELETE_WINDOW", self.callback)
#label = tk.Label(self.root, text="Hello World")
#label.pack()
#Button(self.root, text = "Choose", command=btnPressed).pack()
tk.Label(self.root, text="Answer: ").grid(row=0,column=0)
#answerField_get = StringVar()
answerField = tk.Entry(self.root)
answerField.grid(row=0, column=1)
#Button(self.root, text='Show').grid(row=3, column=1, sticky=tk.W, pady=4)
print(str(answerField.get()))
Button(self.root, text='Show', command = lambda arg1=answerField.get():btnPressed("<"+str(arg1)+">")).grid(row=3, column=1, sticky=tk.W, pady=4)
self.root.mainloop()
def sendTMP(self, sendStr):
btnPressed(sendStr)
SCORE_SET = []
qasTmp = {}
qas = {}
qasSequenced = {}
incorrectResponses = []
incorrectResponses_replies = []
quiztaker_name = ""
attachAnsCode = "%% Fun fact: rgb computer parts lovers are somewhat weird hehe %%********^^&&^^&&^^&&"
qasQsSequenced = False
qasQsL = 0
qasQsL_divisionFactor = 2
qasINDEX = 0
err_noCode = "<!>NO_CODE<!>"
codes_answerCorrect = "A_C"
codes_answerIncorrect = "A_I"
answerCode = err_noCode
score = 0
randQs = False
# File
# the metadata will corrupt the reading from the file, a separate file, created in the targeted system, must be used to properly read the data.
# comment out the file name that is not being used.
filename_windows = "qas-windows"
filename_rpi = "qas-rpi"
filename = filename_windows
fileformat = "txt"
file_name_format = filename + "." + fileformat
spaceIndicator = "|"
char_commentLine_qasFile = "*"
char_newline = "`"
print("Information about modes: ")
print(" *Easy: No point deductions for an incorrect response")
print(" *Hard: One point deducted for every incorrect response")
modes_err = "0"
modes_ez = "1"
modes_hard = "2"
gameOn = False
selectedMode = modes_err
askReplay = True
data_prev = []
with open("SCORES.txt", 'r') as scores_prev:
data_prev = scores_prev.readlines()
scores_prev.close()
for i in range(0, len(data_prev)):
SCORE_SET.append(data_prev[i])
def btnPressInform():
print("A button has been pressed!")
def importAndClean():
# import questions from qas-windows.txt
with open(file_name_format, 'r') as document:
for line in document:
if line.strip():
key, value = line.split(None, 1)
if key[0] != char_commentLine_qasFile: # Custom comments for the txt file
qasTmp[key] = value.split()
# Clean up dictionary input from the txt file
for i in range(0, len(qasTmp)): # FIVE FOR LOOPS!!!! (FOUR IN THIS ONE)
for ii in qasTmp:
output = ""
output_ans = ""
for iii in range(0, len(ii)):
if ii[iii] != spaceIndicator:
output += ii[iii]
else:
output += " "
for iiii in range(0, len(qasTmp[ii])):
TEMP = str(qasTmp[ii])
for iiiii in range(2, len(TEMP) - 2): # IGNORE [' and ']
# print(TEMP[iiiii])
if TEMP[iiiii] != spaceIndicator:
output_ans += TEMP[iiiii]
else:
output_ans += " "
# print(output + " : " + output_ans) #Output question: answer
qas[output] = output_ans
importAndClean()
def getL():
qasQsL = len(qas) / qasQsL_divisionFactor # only ask 1/qasQsL_divisionFactor the questions
qasQsL = int(qasQsL) # round to an integer as odd numbers will end in .5 after division
if qasQsL < 1:
qasQsL = 1 # Have atleast ONE question
return qasQsL
def debug1(keys, vals, index, i):
print(str(index) + "/" + str((len(keys) - 1)))
print(keys)
print(vals)
print()
print(keys[index] + " : " + vals[index] + "\n")
print("Sorting original index " + str(i) + " at random index " + str(index))
def debug2(keys, vals, index):
print(keys)
print(vals)
print("\n")
def debugFinal():
print("Temp (OG reading): ")
print(qasTmp)
print("\nQAS (Non-sequenced, cleaned): ")
print(qas)
print("\nQAS Sequenced (Randomly sequenced, cleaned): ")
print(qasSequenced)
def randomize(qasQsL_tmp):
qas_keys = list(qas.keys())
qas_vals = list(qas.values())
if randQs == False:
qasQsL_tmp = len(qas_keys) # all questions
print("You will be asked all " + str(qasQsL_tmp) + " questions")
else:
qasQsL_tmp = getL() # random question
print("You will be asked " + str(qasQsL_tmp) + " questions out of " + str(len(qas)) + " possible questions!")
print("\n\nRandomly sequencing questions...")
for i in range(0, qasQsL_tmp):
INDEX = random.randint(0, qasQsL_tmp - 1)
# debug1(qas_keys, qas_vals, INDEX, i)
qasSequenced[qas_keys[INDEX]] = qas_vals[INDEX]
qas_keys.pop(INDEX)
qas_vals.pop(INDEX)
qasQsL_tmp -= 1
# debug2(qas_keys, qas_vals, INDEX)
sleep(0.05)
# debugFinal()
print("Done sequencing! Starting quiz now! \n\n")
return "0"
def quizController(index):
qas_keys = list(qasSequenced.keys())
qas_vals = list(qasSequenced.values())
# print(qas_keys)
# print(qas_vals)
lines = []
lines_index = 0
tmp = ""
# Splitter
for i in range(0, len(qas_keys[index])):
if lines_index < len(qas_keys[index]) - 1:
if qas_keys[index][i] != char_newline:
tmp += qas_keys[index][i]
else:
lines.append(tmp)
tmp = ""
lines.append(tmp)
# Multiple choice
mChoiceQ = False
mChoice_startBrackets = 0
mChoice_endBrackets = 0
mChoice_options = []
mChoice_numOptions = 0
mChoice_seperatorsAt = []
for i in range(0, len(qas_keys[index])):
if qas_keys[index][i] == "[":
mChoice_startBrackets = i
mChoiceQ = True
elif qas_keys[index][i] == "]":
mChoice_endBrackets = i
elif qas_keys[index][i] == "/":
mChoice_seperatorsAt.append(i)
if mChoiceQ == True:
TEMP = ""
for i in range(mChoice_startBrackets, mChoice_endBrackets + 1):
if qas_keys[index][i] != "[":
if qas_keys[index][i] != "/" and qas_keys[index][i] != "]":
TEMP += qas_keys[index][i]
else:
mChoice_options.append(TEMP)
TEMP = ""
mChoice_numOptions = len(mChoice_seperatorsAt) + 1
# Default options (yes, no) full names
for i in range(0, len(mChoice_options)):
if mChoice_options[i].lower() == "y":
mChoice_options.append("yes")
elif mChoice_options[i].lower() == "n":
mChoice_options.append("no")
# if mChoiceQ == True:
# print("It is a multiple choice question! There are " + str(mChoice_numOptions) + " options. They are: ")
# print(mChoice_options)
print("\nQuestion " + str(index + 1) + "/" + str(qasQsL) + ":")
for i in range(0, len(lines)):
print(lines[i])
# answer = ""
answer = input(">")
# answer = input(qas_keys[index]+ ": ")
if mChoiceQ == False:
if len(answer) > 0:
if answer.lower() == str(qas_vals[index]).lower():
return codes_answerCorrect
else:
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
# print("DEBUG: Incorrect response! Expected '" + str(qas_vals[index]).lower() + "', received " + answer.lower())
return codes_answerIncorrect
else:
print("Please insert an answer!")
else:
allowedResponse = False
for i in range(0, len(mChoice_options)):
if answer.lower() == mChoice_options[i].lower():
allowedResponse = True
if allowedResponse == True:
ans = qas_vals[index].lower()
yn = False
ans_yesno = ""
if ans.lower() == "y" or ans.lower() == "n":
yn = True
else:
yn = False
if yn == True:
if ans == "y":
ans_yesno = "yes"
elif ans == "n":
ans_yesno = "no"
if len(answer) > 0:
if yn == True:
if answer.lower() == ans.lower() or answer.lower() == ans_yesno.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
if answer.lower() == ans.lower():
return codes_answerCorrect
else:
return codes_answerIncorrect
incorrectResponses.append(qas_keys[index])
incorrectResponses_replies.append(answer)
else:
print("Please insert an answer!")
else:
print("Invalid response! You may only enter the following: " + str(mChoice_options))
def saveScore():
# Clear file!
score_file_CLEAR = open("SCORES.txt", "wt")
score_file_CLEAR.close()
# Save contents
score_file = open("SCORES.txt", "wt")
for i in range(0, len(SCORE_SET)):
score_file.write(SCORE_SET[i])
print("Done saving!")
def btnPressed(tmp):
print(tmp)
app = App()
while True:
qasQsL = len(qasSequenced)
if gameOn == True and selectedMode != modes_err:
if qasQsSequenced == True:
if qasINDEX < qasQsL:
answerCode = quizController(qasINDEX)
else:
output = randomize(qasQsL)
if output == "0":
qasQsSequenced = True
if qasINDEX < qasQsL:
if answerCode == codes_answerCorrect:
score += 1
qasINDEX += 1
# print("DEBUG: Correct! Score set to: " + str(score))
elif answerCode == codes_answerIncorrect:
if selectedMode == modes_hard:
score -= 1
qasINDEX += 1
# print("Score set to: " + str(score))
else:
print("")
if qasQsL != 0:
score_per = score / qasQsL
if score_per < 0:
score_per = 0
if score < 0:
score = 0
print("You score was lower than 0, therefore it was set to 0")
# print("Your score: " + str(score) + "/" + str(len(qasSequenced)) + " (" + str(int(score_per*100)) + "%)")
# if score != qasQsL:
# print("You responded to the following questions incorrectly:")
# print(incorrectResponses)
if score / qasQsL == 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + "(" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + "\n")
if score / qasQsL != 1:
SCORE_SET.append(quiztaker_name + " scored " + str(score) + " out of " + str(qasQsL) + " (" + str(
int(score / qasQsL) * 100) + "%). PART OF Qs: " + str(
int(randQs)) + " at division factor 1/" + str(qasQsL_divisionFactor) + ", MODE: " + str(
int(selectedMode)) + " They got the following questions wrong: \n")
for i in range(0, len(incorrectResponses)):
SCORE_SET.append(" " + str(i + 1) + ") " + incorrectResponses[i] + " --RESPONSE-- " +
incorrectResponses_replies[i] + "\n")
SCORE_SET.append("\n")
saveScore()
qasQsSequenced = False
gameOn = False
print("\nGame over!")
askReplay = True
else:
continue
elif askReplay == False:
TEMP = input("What mode would you like? (E = Easy, H = Hard): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "e":
selectedMode = modes_ez
gameOn = True
print("Set mode to: NO POINT DEDUCTIONS")
elif str(TEMP).lower() == "h":
selectedMode = modes_hard
gameOn = True
print("Set mode to: POINT DEDUCTIONS ALLOWED")
else:
print("Error: Undefined response. Please try again!")
elif askReplay == True:
TEMP = input("Would you like to (re)do the quiz? (Y/N): ")
if len(str(TEMP)) > 0:
if str(TEMP).lower() == "y":
askReplay = False
qasQsSequenced = False
qasQsL = 0
qas.clear()
qasSequenced.clear()
qasTmp.clear()
qasINDEX = 0
incorrectResponses.clear()
answerCode = err_noCode
score = 0
selectedMode = modes_err
importAndClean()
randQs = False
USER_TEMP = input("Please enter your name >")
if len(USER_TEMP) > 0:
quiztaker_name = str(USER_TEMP)
print("Welcome " + quiztaker_name + "!")
USER_TEMP = input("Would you like all questions (a) or a part of the questions(p)? (A/P) > ")
if len(USER_TEMP) > 0:
if USER_TEMP.lower() == "a":
print("Set to all questions!")
randQs = False
elif USER_TEMP.lower() == "p":
print("Set to 1/" + str(qasQsL_divisionFactor) + " questions (pre-set variable)")
randQs = True
else:
print("Undefined response! Setting to default value (ALL)")
randQs = False
gameOn = False
askReplay = False
elif str(TEMP).lower() == "n":
selectedMode = modes_hard
gameOn = False
print("Exiting now!")
saveScore()
sleep(2)
exit(0)
else:
print("Error: Undefined response. Please try again!")
Entry() doesn't work like input(). It doesn't wait for your data but it only informs tkitner that you want to display Entry widget (and mainloop() will display it) and Python goes to next lines of code and it runs print(str(answerField.get())) before it even displays window - so you try to get from empty Entry.
You should get it in function assigned to Button which you will press after you put some text in Entry.
The same problem is with
lambda arg1=self.answerField.get():print(arg1)
it assigns to args value from Entry only once when lambda is defined at start - so it get empty string. You should use it inside function
command=lambda:print(self.answerField.get())
or create normal function and assign to button.
Minimal working code
import tkinter as tk
import threading
class App(threading.Thread):
def run(self):
self.root = tk.Tk()
#self.root.protocol("WM_DELETE_WINDOW", self.on_close)
self.answerField = tk.Entry(self.root)
self.answerField.grid(row=0, column=1)
#b = tk.Button(self.root, text='Show', command=lambda:print(self.answerField.get()))
b = tk.Button(self.root, text='Show', command=self.on_click)
b.grid(row=1, column=1)
self.root.mainloop()
def on_click(self):
print(self.answerField.get())
#def on_close(self):
# self.root.destroy()
App().start()
#App().run()
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
I'm still learning python. I am trying to write a program that develops a car inventory. I am creating an automobile class that will be used by a dealership as a vehicle inventory program. The following attributes should be present in your automobile class:
private string make
private string model
private string color
private int year
private int mileage
How can I make this execute and give prompts for input. It's not doing it.
class Automobile():
__make = ""
__model = ""
__color = ""
__year = 0
__mileage = 0
def __init__(self, make = None, model = None, color = None, year = None, mileage = None):
self.make = make
self.model = model
self.color = color
self.year = year
self.mileage = mileage
def add_vehicle(self):
auto = Automobile()
vehicle_file = open('vehicle.txt', 'a')
make = input("Enter make: ")
model = input("Enter model: ")
color = input("Enter color: ")
year = input("Enter year: ")
mileage = input("Enter mileage: ")
vehicles = Automobile(make, model, color, year, mileage)
vehicle_list = [vehicles.make, vehicles.model, vehicles.color, vehicles.year, vehicles.mileage]
for item in vehicle_list:
vehicle_file.write("%s\t" % item)
vehicle_file.write("\n")
vehicle_file.close()
print("Your record has been succesfully added to the inventory")
def delete_vehicle(self):
del_rec = input("Enter record to delete: ")
with open("vehicle.txt","r+") as f:
new_f = f.readlines()
f.seek(0)
for line in new_f:
if del_rec not in line:
f.write(line)
f.truncate()
print("Succesfully deleted record from inventory")
def set_make(self, make):
self.make = make
def get_make(self):
return self.make
def set_model(self, model):
self.model = model
def get_model(self):
return self.model
def set_color(self, color):
self.color = color
def get_color(self):
return self.color
def set_year(self, year):
self.year = year
def get_year(self):
return self.year
def set_mileage(self, mileage):
self.mileage = mileage
def get_mileage(self):
return self.mileage