A Day at the Supermarket: Are dictionaries global?


#1


In the compute_bill function, we were not passed the dictionaries yet we can still use them. Are they global, or did I miss something here?



#2

yes, the dictionary's are global


#3

See Programming FAQ: What are the rules for local and global variables in Python?.

Quote from the above:

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

In the Python: A Day at the Supermarket exercises, the two dictionaries are created outside the compute_bill function, and all we do is reference them within the function, therefore they are global. We can even make changes to the content of a dictionary within a function without the dictionary's being local. Changing an individual value associated with a key or creating a new item in a dictionary with an assignment statement does not constitute assigning a value to the dictionary.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.