Home > front end >  Calling multiple variables from a function to multiple other functions
Calling multiple variables from a function to multiple other functions

Time:09-19

There are multiple variables that I'm trying call in multiple parts of the code.

  1. Firstly I need to call stock in num_loop from product_loop
  2. Next would be productprice from product_loop and num from num_loop in the final line of the code
def product_loop(): 
   product = input ("Enter product name: ")
   if product == 'apple':
       productprice = 3.5
       stock = 134
   elif product == 'banana':
       productprice = 6.82
       stock = 52    
   else:
       print ("Sorry, no such product. Try again.")
       #loops back to the start of product input
       product_loop()
       
def num_loop():
   num = int(input ("Enter number of products ordered: "))
   if num>stock:        #trying to call stock from product_loop
       print ("Sorry, not enough stock. Try again.")
       num_loop()

totalprice=productprice*num       #trying to call productprice from product_loop and num from num_loop
print(totalprice)

Would I need to use the return statement or a class to accomplish this?
*Edit(How would I use a return statement in this situation?)

CodePudding user response:

Yes, usually you would write a function that returns a product with its information. If you dont want to use that in this basic example, you can also do something like that. Store all product information in a dictionary and use .get() to access the parameters.

PRODUCTS = {
    "apple": {"price": 3.5, "stock": 134},
    "banana": {"price": 6.82, "stock": 52}
}


if __name__ == "__main__":
    while True:
        product = PRODUCTS.get(input("Enter product name: "))
        if not product:
            print("Sorry, no such product. Try again.")
            continue

        num = int(input("Enter number of products ordered: "))
        stock = product.get("stock", 0)
        if num > stock:
            print("Sorry, not enough stock. Try again.")
            continue

        price_per_unit = product.get("price", 0)
        print("Ordervalue: ", price_per_unit * num)
  • Related