0

I'm trying to create a simple fruit store with apples and grapes for sale. I've set the amounts of each fruit to be randomised.

If you ask for more grapes then the store has, I want the code to loop back and ask for another input. I'm stuck on that. Here is my code:

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()
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – mkrieger1 Jan 12 '23 at 20:18

1 Answers1

0

This appears to be tailor-made for a while loop. A simple suggestion for implementing the loop would be:

while True:
    if function():
        break

However, you'll need to consider what an acceptable purchase will mean. You can test for that condition within your function, then cause your order_check method to return True or False to either continue looping or exit the loop.

Thanks @nonlinear for the syntax correction! Thanks @Chris for the code simplification!

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    The syntax `while !acceptable_purchase:` in your code is incorrect: it should be `while not acceptable_purchase:` – Nonlinear Jan 12 '23 at 20:26
  • 1
    There is no need to maintain/update another variable. `while True: ...` and then `break` when appropriate. – Chris Jan 12 '23 at 20:33
  • 1
    Thank you all for your help! I really appreciate how friendly and helpful this community is! I only just started coding and don't have people around me who can help. Thanks again! – TheThinker Feb 04 '23 at 22:15