def userQty():
name = input("Quantity: ")
return name
def userAdd():
add = input("What would you like to add do your cart? ")
return add
def userInfo():
data = {}
while True:
result = input(
"Make your shopping list. Please type (Show/Add/Delete/Clear/Quit). ")
if result.lower() == 'add':
data[userQty()] = userAdd()
elif result.lower() == 'show':
print(data)
elif result.lower() == 'delete':
print("Still working on that, use 'clear' for now please.")
# Could not figure out how to remove one item
elif result.lower() == 'clear':
dLi = input("Clear your list?: [y/n] ").lower()
if dLi in ["y", "yes"]:
data = {}
print("Your list has been cleared.")
print(data)
elif dLi in ["n", "no"]:
print("Action Abandoned.")
elif result.lower() == 'quit':
break
else:
print(
'Oops! Something went wrong. Please type "(Show/Add/Delete/Clear/Quit)"')
print(data)
return data
userInfo()
I am fairly new to programming as a whole so I'm sorry if the code is sloppy or if I am not being specific enough?
I tried adding:
def __init__(self):
return #something
I am lost as far as where to go from here.
CodePudding user response:
You could add:
class Somthing():
def __init__(self):
code
and add the variables to self, like this:
self.name = name
also put (self):
in the function parentheses.
CodePudding user response:
One approach might be to make your different menu items methods on your object:
class ShoppingCart:
def __init__(self):
self.data = {}
def add(self):
i = input("What would you like to add to your cart? ")
self.data[i] = input("Quantity: ")
def clear(self):
if input("Clear your list? [y/n] ").lower().startswith("y"):
self.data = {}
print("Your list has been cleared.")
else:
print("Action abandoned.")
def delete(self):
print("Still working on that, use 'clear' for now please.")
def menu_loop(self):
while True:
i = input(
"Make your shopping list. "
"Please type (Show/Add/Delete/Clear/Quit). "
).lower()
if i == "quit":
break
try:
getattr(self, i)()
except AttributeError:
print(
'Oops! Something went wrong. '
'Please type "(Show/Add/Delete/Clear/Quit)"'
)
cart = ShoppingCart()
cart.menu_loop()
print(cart.data)