I'm making a shopping cart list, where the products are added and identified by their codes.
The system has to add, remove, show and checkout.
Show and checkout commands are working fine.
Add is working fine too, but it has a particularity: it´s mandatory to add with "Add 15", "Add 70" (whatever other number). I can't input str and int separately (did before and was perfect, but not what they want).
After I add, the remove command does not identify number inserted previously, because it is being added as a str.
cart = []
while True:
command = str(input("Command: ")).split()
if "add" in command:
cart.append(int(command[1]))
elif "remove" in command:
if command[1] in cart:
cart.remove(int(command[1]))
else:
print(f'code {command[1]} not found')
elif "show" in command:
cart.sort()
print(cart, end="\n")
elif "checkout" in command:
break
cart.sort()
print(cart, end="")
CodePudding user response:
You forgot to change the type of "command[1]" in the if. The following code works:
cart = []
while True:
command = str(input("Command: ")).split()
if "add" in command:
cart.append(int(command[1]))
elif "remove" in command:
if int(command[1]) in cart: # There you forgot to check command[1] with the casting of type
cart.remove(int(command[1]))
else:
print(f'code {command[1]} not found')
elif "show" in command:
cart.sort()
print(cart, end="\n")
elif "checkout" in command:
break
cart.sort()
print(cart, end="")
You made this mistake because you repeated yourself too much, using multiple times the int() method. There is a cleaner version of the code
cart = []
while True:
raw = str(input("Command: ")).split()
command = raw[0]
amount = None
if (len(raw) > 1):
amount = int(raw[1])
if command == "add":
cart.append(amount)
elif command == "remove":
if amount in cart:
cart.remove(amount)
else:
print(f'code {amount} not found')
elif command == "show":
cart.sort()
print(cart, end="\n")
elif command == "checkout":
break
cart.sort()
print(cart, end="")
CodePudding user response:
cart = []
while True:
command = str(input("Command: ")).lower().split()
print(command)
# I assume that add and remove will be 2-word commands
if len(command) == 2:
try:
number = int(command[1])
if "add" == command[0]:
cart.append(number)
elif "remove" == command[0]:
if number in cart:
cart.remove(number)
else:
print(f"code {number} not found")
except ValueError:
print(f"code {command[1]} is not a number")
# I assume show and checkout will be 1-word commands
elif len(command) == 1:
if "show" == command[0]:
cart.sort()
print(cart, end="\n")
elif "checkout" == command[0]:
break
else:
print("invalid command")
else:
print("invalid command")
cart.sort()
print(cart, end="")