我试图创建一个简单的水果店,销售苹果和葡萄。我设置了每种水果的数量是随机的。
如果你要的葡萄比商店里的多,我希望代码循环回来,要求另一个输入。我被卡住了。下面是我的代码:
import random
amount_of_apples = random.randint(1, 100)
price_of_apples = random.randint(1, 10)
amount_of_grapes = random.randint(1, 50)
price_of_grapes = random.randint(5, 15)
stock = ["apples","grapes"]
basket = []
greeting = """Hello and welcome to Pennants."""
availability = "We have the following fruits available to purchase " + stock[0] + " and " + stock[1]
print(greeting)
print(availability)
print("""We have %s Apples available to purchase. Each Apple cost £%s.""" % (amount_of_apples, price_of_apples))
print("""We have %s bunches of grapes available to purchase. Each bunch of grapes cost £%s.""" % (amount_of_grapes, price_of_grapes))
order = input("What would you like to purchase?")
if order == " Grapes":
basket.append("Grapes")
def order_check():
G2 = input("How many bunches of grapes would you like to buy?")
print("Your basket:" + G2 + basket[0])
Correct = "Yes"
Incorrect = "No"
M = int(G2) * price_of_grapes
if int(G2) > amount_of_grapes:
print("""Unfortunately we don't have enough grapes to fufil your request.
We have %s grapes available to buy.""" % (amount_of_grapes))
order_check()
1条答案
按热度按时间bf1o4zei1#
这似乎是为while循环量身定制的。实现该循环的一个简单建议是:
但是,你需要考虑一个可接受的购买意味着什么,你可以在你的函数中测试这个条件,然后让你的order_check方法返回
True
或False
,要么继续循环,要么退出循环。感谢@nonlinear的语法修正!感谢@Chris的代码简化!