【发布时间】:2020-06-14 06:16:17
【问题描述】:
这是我的代码:
cart = ['S/n'," "*10, 'Items', " " * 15, "Quantity", " " * 8, "Unit Price", " " * 6, "Price"]
total_pricee = 0
pricee = 0
count=1
def invalid_input(Quantitiy):
while Quantitiy > '5' or Quantitiy < '1':
Quantitiy = input("Please key in a valid quantity(Between 1 to 4):")
if Quantitiy < '5' and Quantitiy > '1':
New_Quan=Quantitiy
break
while not Quantitiy.isdigit():
Quantitiy = input('Invalid input.Please enter a valid input:')
while Quantitiy.isdecimal() == False:
break
def add_to_cart(name, Quantity, price):
global total_pricee, pricee,count
cart.append('\n')
cart.append('{:<10s}'.format(str(count)+'.'))
cart.append('{:^10s}'.format(name))
cart.append('{:^30s}'.format(Quantity))
cart.append('{:^10s}'.format('$' + '{:.2f}'.format(float(price))))
pricee = '{:.2f}'.format(float(Quantity) * price)
cart.append('{:^23s}'.format('$' + str(pricee)))
total_pricee += float(pricee)
count = count +1
while True:
print('[1] Water')
print('[2] rice')
print('[3] ice')
print('[0] View Cart')
opt = input("Select option:")
if opt > '3' or opt < '0':
print("Select valid option!")
if opt == '3':
qunt = input("How many would you like?")
invalid_input(qunt)
nam3 = "Ice"
add_to_cart(nam3, qunt, 2)
if opt == '1':
qunt2 = input("How many would you like?")
invalid_input(qunt2)
nam2 = "Water"
add_to_cart(nam2, qunt2, 3)
if opt == '2':
qunt1 = input("How many would you like?")
invalid_input(qunt1)
nam1 = "Rice"
add_to_cart(nam1, qunt1, 5)
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()
我面临的问题是当用户输入的数量超过5时(参考invalid_input函数),程序要求它提供小于6的数量。但是,当我应用add_to_cart时,它取用户输入的原始值(大于5)。
[1] Water
[2] rice
[3] ice
[0] View Cart
Select option:3
How many would you like?6
Please key in a valid quantity(Between 1 to 4):5
[1] Water
[2] rice
[3] ice
[0] View Cart
Select option:0
S/n Items Quantity Unit Price Price
1. Ice 6 $2.00 $12.00
您看到它如何要求用户输入有效数量(5)但是add_to_cart所取的数量是初始值(6)。我希望从有效数量中显示数量。请帮助!谢谢!
【问题讨论】:
标签: python python-3.x list logic