Home > Enterprise >  How to retrieve a variable from a function?
How to retrieve a variable from a function?

Time:08-05

Say we have a function named shopping_cart(), and inside it we have a list assigned to the variable cart_items. How would I be able to use this variable/list out side of this function?

CodePudding user response:

return cart_items. Like this:

def shopping_cart():
    cart_items = ["apple", "banana"]
    return cart_items

items = shopping_cart()
print(items)
#['apple', 'banana']

This website explains it fairly well, and you can find numerous others by looking it up. (Hint: This is definitely something you could have looked up yourself)

CodePudding user response:

You'll need to either return the variable or use a global variable. Other answers have returned the variable, so here's an example using a global variable:

def shopping_cart():
    global cart_items
    cart_items = ["apple", "banana"]

CodePudding user response:

if you don't need to return it you should to define it as global variable and use it anywhere you want, but you need to use "global cart_items" before use this variable in any function, like this code:

cart_items = ['hello']
def shopping_cart():
    global cart_items
    cart_items.append('world!')


print(cart_items)
#['hello']

shopping_cart()

print(cart_items)
#['hello', 'world!']

and you can return cart_items, like this code:

def shopping_cart():
    cart_items = ['hello']
    cart_items.append('world!')
    return cart_items


print(shopping_cart())
#['hello', 'world!']

CodePudding user response:

You would not be able to access that variable because of scope. What you could do is declare that variable as a global variable and then change the value inside the function.

Here is an example:


def shopping_cart():
    global cart_items
    cart_items = ["some value"]
shopping_cart()
print(cart_items)
  • Related