尝试使用python进行基本的在线商店代码

  • 本文关键字:在线 代码 python python
  • 更新时间 :
  • 英文 :


我是大学的预科生,所以我对编码很陌生。我正在努力解决这个问题,需要一些帮助,这是我目前编写的问题和代码:

"编写一个python程序来模拟在线商店。
该程序应首先显示产品列表及其价格。至少应提供 4 种产品。程序应要求用户选择产品,然后要求用户输入他们需要的产品数量。然后,程序应该允许用户继续选择更多的产品和数量,直到他们输入一些东西来表明他们想要结束程序(例如,给定的数字或"q"或"exit"(。然后,程序应告诉用户他们选择的产品的总量。">

shopping_basket = {}
print("Welcome to the online drink store!nThese are the drinks we offern1. Lemonade: £1.50n2. 
Coke: £2.00n3. Fanta £1.00n4. Water: £0.50")
Price = {"Lemonade": 1.50, "Coke": 2.00, "Fanta": 1.00, "Water": 0.50 }
option = int(input("Which drink would you like to purchase?: "))
while option!= 0:
if option == 1:
qnty = int(input("Enter the quantity: "))
total = qnty * 1.50
print("The price is: " + str(total))
elif option == 2:
qnty = int(input("Enter the quantity: "))
total = qnty * 2.00
print("The price is: " + str(total))
elif option == 3:
qnty = int(input("Enter the quantity: "))
total = qnty * 1.00
print("The price is: " + str(total))
elif option == 4:
qnty = int(input("Enter the quantity: "))
total = qnty * 0.50
print("The price is: " + str(total))
print("Would you like another item? enter Yes or No:")
else:
print("The total price of your basket is: " , total = Price * qnty)

这是我尝试过的代码,但是在说明价格之后,它只是不断询问数量。

我不想发布新的答案,而是发表评论,但可惜,声誉不够。

我只是想补充Daemon Painter的答案,并说最终的总账单也不起作用,因为它将字典乘以整数。

可行的方法是在循环外初始化总变量以及一个新的total_cost变量,并放置:

total_cost += total

在 while 循环内,但在 if 条件之外。 这样最后一行就可以是:

print("The total price of your basket is: ", total_cost)

编辑:代码,按预期工作:

price = {"Lemonade": 1.50, "Coke": 2.00, "Fanta": 1.00, "Water": 0.50}
shopping_basket = {}
print("Welcome to the online drink store!nThese are the drinks we offern1. Lemonade: £1.50n2. Coke: £2.00n3. Fanta £1.00n4. Water: £0.50")
buy_another_flag = 1
total_cost, total = 0, 0
while buy_another_flag != 0:
option = int(input("Which drink would you like to purchase?: "))
if option == 1:
qnty = int(input("Enter the quantity: "))
total = qnty * 1.50
print("The price is: " + str(total))
elif option == 2:
qnty = int(input("Enter the quantity: "))
total = qnty * 2.00
print("The price is: " + str(total))
elif option == 3:
qnty = int(input("Enter the quantity: "))
total = qnty * 1.00
print("The price is: " + str(total))
elif option == 4:
qnty = int(input("Enter the quantity: "))
total = qnty * 0.50
print("The price is: " + str(total))
total_cost += total
buy_another_flag = int(input("Would you like another item? enter Yes (1) or No (0):"))
print("The total price of your basket is: ", total_cost)

你在 while 循环中无限循环。

通过此处的用户输入分配选项后:

option = int(input("Which drink would you like to purchase?: "))

始终满足此条件:

while option!= 0:

在这里,您不仅应该打印,还应该重新分配选项:

print("Would you like another item? enter Yes or No:")

像这样:

option = int(input("Would you like another item? enter Yes or No:"))

我希望这为您指明了正确的方向:)

(我已经假设了您应该如何在原始脚本中格式化代码。他们可能是错的...

最新更新