Line (39) IndexError: pop index out of range
Line (39) IndexError: pop index out of range
这是我的代码:
#cart is a list, easy to append
cart=['S/n'," "*10, 'Items', " " * 14, "Quantity", " " * 8, "Unit Price", " " * 8, "Price"]
total_pricee = 0
pricee = 0
count=1
from datetime import datetime
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print( "Date & Time:",dt_string)
print('Welcome to tis program.Please use the numbers to navigate!')
def invalid_input(Quantitiy):
while Quantitiy > '5' or Quantitiy < '1':
Quantitiy = input("Please key in a valid quantity(Between 1 to 5):")
if Quantitiy < '5' and Quantitiy > '1':
New_Quan=Quantitiy
#This part of function checks if item quantity is between 1 and 5
return Quantitiy
break
while not Quantitiy.isdigit():
Quantitiy = input('Invalid input.Please enter a valid input:')
while Quantitiy.isdecimal() == False:
break
#This part of function checks that item quantity is not a decimal
return Quantitiy
def add_to_cart(name, Quantity, price):
global total_pricee, pricee,count,cart
#This function adds items to cart
cart.append('\n')
cart.append('{:<10s}'.format(str(count) + '.'))
cart.append('{:^10s}'.format(name))
cart.append('{:^30s}'.format(str(Quantity)))
cart.append('$'+str(price)+'0')
pricee = '{:.2f}'.format(float(Quantity) * price)
pricee
cart.append('{:^34s}'.format('$' +str(pricee)))
total_pricee += float(pricee)
count = count +1
print(name,"has been added to cart!")
def remove_from_cart(Item_number):
global count
while True:
if Item_number>(count-1):
print('Please key in a valid S/n!')
(Item_number)=int(input('Please enter the S/n of the item you want to remove:'))
if Item_number==2:
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
if Item_number<=(count-1):
x=(6*(Item_number-2))+9
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
print('Item has been sucsussfully removed from cart!')
if count==1:
print('Please add an item to cart first!')
while True:
print('[1] Water')
print('[2] rice')
print('[3] ice')
print('[0] View Cart and Check-out')
print("[4] Remove object from cart")
opt = input("Select option:")
if opt > '4' or opt < '0':
print("Select valid option!")
if opt == '3':
qunt = input("Please key in a quanity for your item:")
qunt =invalid_input(qunt)
nam3 = "Ice"
add_to_cart(nam3, qunt, 2.00)
if opt == '1':
qunt2 = input("Please key in a quanity for your item:")
qunt2=invalid_input(qunt2)
nam2 = " Water"
add_to_cart(nam2, qunt2, 3.00)
if opt == '2':
qunt1 = input("Please key in a quanity for your item:")
qunt1=invalid_input(qunt1)
nam1 = "Rice"
add_to_cart(nam1, qunt1, 5.00)
if opt == "0":
print(*cart)
print("Total price until now:", "$" + '{:.2f}'.format(total_pricee))
print('Would you like to check out?')
print('[1] Yes')
print('[2] No')
checkout=input("Please select an option:")
if checkout=='1':
print('You have bought',count,'items')
print("Please pay""$" + '{:.2f}'.format(total_pricee))
print('Thank you for shopping with us!')
exit()
if opt=="4":
print(*cart)
remove=input("Please key in the S/n of the item you want to remove:")
remove_from_cart(int(remove))
print(*cart)
我不知道为什么会出现这个错误。我对 python 有点陌生,还没有遇到过这样的错误 before.Please 告诉我如何改进我的代码,这样这个错误就不会发生再次发生。感谢任何帮助的人!
例如:
S/n Items Quantity Unit Price Price
1. Rice 3 .00 .00
2. Rice 4 .00 .00
3. Water 4 .00 .00
并且用户想要删除第二项,执行该功能后的输出应该是
S/n Items Quantity Unit Price Price
1. Rice 3 .00 .00
2. Water 4 .00 .00
不能在评论里贴格式化代码,我会写在答案里,望理解。
列表做这个操作很不方便
In [1]: import pandas as pd
In [5]: d = pd.DataFrame([['Rice', 3, '.0', '.0'], ['Water', 4, '.0', '.0']], columns=['Items', 'Quantity', 'Unit Price', 'Price'])
In [6]: d
Out[6]:
Items Quantity Unit Price Price
0 Rice 3 .0 .0
1 Water 4 .0 .0
In [7]: d.drop(0)
Out[7]:
Items Quantity Unit Price Price
1 Water 4 .0 .0
In [16]: d.append([{"Items": "Rice", "Quantity": 3, "Unit Price": ".0", "Price": ".0"}], ignore_index=True)
Out[16]:
Items Quantity Unit Price Price
0 Rice 3 .0 .0
1 Water 4 .0 .0
2 Rice 3 .0 .0
这是我的代码,也许供您参考:)
from itertools import repeat
class Cart():
def __init__(self):
self.header = ['S/N', 'Items', 'Quantity', 'Unit Price', 'Price']
(self.SN_width, self.item_width, self.quantity_width,
self.unit_price_width, self.price_width
) = self.widths =[13, 19, 16, 18, 20]
self.item_list = {}
def get_serial_no(self):
i = 1
while i in self.item_list:
i += 1
return i
def add(self, item, quantity, unit_price):
serial_no = self.get_serial_no()
self.item_list[serial_no] = (item, quantity, unit_price)
def delete(self, serial_no):
del self.item_list[serial_no]
lst = sorted(self.item_list.keys())
new_list = {i+1:self.item_list[key] for i, key in enumerate(lst)}
self.item_list = new_list
def sum_all(self):
all_price = 0
for item, quantity, unit_price in self.item_list.values():
all_price += quantity*unit_price
return all_price
def adjust(self, items):
line = ['']*5
for i in range(5):
if i == 0:
line[0] = items[0].center(self.widths[0])
elif i == 1:
line[1] = items[1].ljust(self.widths[1])
else:
line[i] = items[i].rjust(self.widths[i])
return ' '.join(line)
def __repr__(self):
keys = sorted(self.item_list.keys())
title = self.adjust(self.header)
seperator = ' '.join(list(map(str.__mul__, repeat('-'), self.widths)))
result = [title, seperator]
for key in keys:
lst = self.item_list[key]
items = [str(key), lst[0], '%.3f'%lst[1], '$%.3f'%lst[2],
'$%.3f'%(lst[1]*lst[2])]
line = self.adjust(items)
result.append(line)
return '\n'.join((' ', '\n'.join(result), ' ',
'Total price: $%.3f'%self.sum_all(), ' '))
cart = Cart()
new_items = [
('apple', 10, 1), ('orange', 5, 0.5), ('banana', 20, 0.2),
('avocado', 5, 0.2), ('cherry', 1, 20), ('grape', 1, 15), ('lemon', 5, 1)]
for item in new_items:
cart.add(*item)
while True:
print(cart)
try:
action = input('Add(A), Delete(D), Exit(E) :').strip().lower()
except:
continue
if action == 'a':
try:
item = input('Name of item: ').strip()
quantity = float(input('Quantiy: ').strip())
unit_price = float(input('Unit Price: ').strip())
except:
print('Wrong data for item !')
continue
cart.add(item, quantity, unit_price)
elif action == 'd':
key = input('Serial No. to be deleted: ').strip()
try:
key = int(key)
if key in cart.item_list:
cart.delete(int(key))
continue
except:
pass
print('Wrong serial No. !')
elif action == 'e':
break
else:
print('Wrong action !')
print('Bye !')
``
这是我的代码:
#cart is a list, easy to append
cart=['S/n'," "*10, 'Items', " " * 14, "Quantity", " " * 8, "Unit Price", " " * 8, "Price"]
total_pricee = 0
pricee = 0
count=1
from datetime import datetime
now = datetime.now()
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print( "Date & Time:",dt_string)
print('Welcome to tis program.Please use the numbers to navigate!')
def invalid_input(Quantitiy):
while Quantitiy > '5' or Quantitiy < '1':
Quantitiy = input("Please key in a valid quantity(Between 1 to 5):")
if Quantitiy < '5' and Quantitiy > '1':
New_Quan=Quantitiy
#This part of function checks if item quantity is between 1 and 5
return Quantitiy
break
while not Quantitiy.isdigit():
Quantitiy = input('Invalid input.Please enter a valid input:')
while Quantitiy.isdecimal() == False:
break
#This part of function checks that item quantity is not a decimal
return Quantitiy
def add_to_cart(name, Quantity, price):
global total_pricee, pricee,count,cart
#This function adds items to cart
cart.append('\n')
cart.append('{:<10s}'.format(str(count) + '.'))
cart.append('{:^10s}'.format(name))
cart.append('{:^30s}'.format(str(Quantity)))
cart.append('$'+str(price)+'0')
pricee = '{:.2f}'.format(float(Quantity) * price)
pricee
cart.append('{:^34s}'.format('$' +str(pricee)))
total_pricee += float(pricee)
count = count +1
print(name,"has been added to cart!")
def remove_from_cart(Item_number):
global count
while True:
if Item_number>(count-1):
print('Please key in a valid S/n!')
(Item_number)=int(input('Please enter the S/n of the item you want to remove:'))
if Item_number==2:
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
cart.pop(9)
if Item_number<=(count-1):
x=(6*(Item_number-2))+9
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
cart.pop(x)
print('Item has been sucsussfully removed from cart!')
if count==1:
print('Please add an item to cart first!')
while True:
print('[1] Water')
print('[2] rice')
print('[3] ice')
print('[0] View Cart and Check-out')
print("[4] Remove object from cart")
opt = input("Select option:")
if opt > '4' or opt < '0':
print("Select valid option!")
if opt == '3':
qunt = input("Please key in a quanity for your item:")
qunt =invalid_input(qunt)
nam3 = "Ice"
add_to_cart(nam3, qunt, 2.00)
if opt == '1':
qunt2 = input("Please key in a quanity for your item:")
qunt2=invalid_input(qunt2)
nam2 = " Water"
add_to_cart(nam2, qunt2, 3.00)
if opt == '2':
qunt1 = input("Please key in a quanity for your item:")
qunt1=invalid_input(qunt1)
nam1 = "Rice"
add_to_cart(nam1, qunt1, 5.00)
if opt == "0":
print(*cart)
print("Total price until now:", "$" + '{:.2f}'.format(total_pricee))
print('Would you like to check out?')
print('[1] Yes')
print('[2] No')
checkout=input("Please select an option:")
if checkout=='1':
print('You have bought',count,'items')
print("Please pay""$" + '{:.2f}'.format(total_pricee))
print('Thank you for shopping with us!')
exit()
if opt=="4":
print(*cart)
remove=input("Please key in the S/n of the item you want to remove:")
remove_from_cart(int(remove))
print(*cart)
我不知道为什么会出现这个错误。我对 python 有点陌生,还没有遇到过这样的错误 before.Please 告诉我如何改进我的代码,这样这个错误就不会发生再次发生。感谢任何帮助的人! 例如:
S/n Items Quantity Unit Price Price
1. Rice 3 .00 .00
2. Rice 4 .00 .00
3. Water 4 .00 .00
并且用户想要删除第二项,执行该功能后的输出应该是
S/n Items Quantity Unit Price Price
1. Rice 3 .00 .00
2. Water 4 .00 .00
不能在评论里贴格式化代码,我会写在答案里,望理解。 列表做这个操作很不方便
In [1]: import pandas as pd
In [5]: d = pd.DataFrame([['Rice', 3, '.0', '.0'], ['Water', 4, '.0', '.0']], columns=['Items', 'Quantity', 'Unit Price', 'Price'])
In [6]: d
Out[6]:
Items Quantity Unit Price Price
0 Rice 3 .0 .0
1 Water 4 .0 .0
In [7]: d.drop(0)
Out[7]:
Items Quantity Unit Price Price
1 Water 4 .0 .0
In [16]: d.append([{"Items": "Rice", "Quantity": 3, "Unit Price": ".0", "Price": ".0"}], ignore_index=True)
Out[16]:
Items Quantity Unit Price Price
0 Rice 3 .0 .0
1 Water 4 .0 .0
2 Rice 3 .0 .0
这是我的代码,也许供您参考:)
from itertools import repeat
class Cart():
def __init__(self):
self.header = ['S/N', 'Items', 'Quantity', 'Unit Price', 'Price']
(self.SN_width, self.item_width, self.quantity_width,
self.unit_price_width, self.price_width
) = self.widths =[13, 19, 16, 18, 20]
self.item_list = {}
def get_serial_no(self):
i = 1
while i in self.item_list:
i += 1
return i
def add(self, item, quantity, unit_price):
serial_no = self.get_serial_no()
self.item_list[serial_no] = (item, quantity, unit_price)
def delete(self, serial_no):
del self.item_list[serial_no]
lst = sorted(self.item_list.keys())
new_list = {i+1:self.item_list[key] for i, key in enumerate(lst)}
self.item_list = new_list
def sum_all(self):
all_price = 0
for item, quantity, unit_price in self.item_list.values():
all_price += quantity*unit_price
return all_price
def adjust(self, items):
line = ['']*5
for i in range(5):
if i == 0:
line[0] = items[0].center(self.widths[0])
elif i == 1:
line[1] = items[1].ljust(self.widths[1])
else:
line[i] = items[i].rjust(self.widths[i])
return ' '.join(line)
def __repr__(self):
keys = sorted(self.item_list.keys())
title = self.adjust(self.header)
seperator = ' '.join(list(map(str.__mul__, repeat('-'), self.widths)))
result = [title, seperator]
for key in keys:
lst = self.item_list[key]
items = [str(key), lst[0], '%.3f'%lst[1], '$%.3f'%lst[2],
'$%.3f'%(lst[1]*lst[2])]
line = self.adjust(items)
result.append(line)
return '\n'.join((' ', '\n'.join(result), ' ',
'Total price: $%.3f'%self.sum_all(), ' '))
cart = Cart()
new_items = [
('apple', 10, 1), ('orange', 5, 0.5), ('banana', 20, 0.2),
('avocado', 5, 0.2), ('cherry', 1, 20), ('grape', 1, 15), ('lemon', 5, 1)]
for item in new_items:
cart.add(*item)
while True:
print(cart)
try:
action = input('Add(A), Delete(D), Exit(E) :').strip().lower()
except:
continue
if action == 'a':
try:
item = input('Name of item: ').strip()
quantity = float(input('Quantiy: ').strip())
unit_price = float(input('Unit Price: ').strip())
except:
print('Wrong data for item !')
continue
cart.add(item, quantity, unit_price)
elif action == 'd':
key = input('Serial No. to be deleted: ').strip()
try:
key = int(key)
if key in cart.item_list:
cart.delete(int(key))
continue
except:
pass
print('Wrong serial No. !')
elif action == 'e':
break
else:
print('Wrong action !')
print('Bye !')
``