Think globally act locally

It's easy to explicitly tell a function that a name is global: You just use the keyword global with the name. In the example program below, which we call, defining the name eggcolor as global allows the function to change the value of that name, and the changed value remains in effect after Python exits the function. In contrast, the name meat, which isn't declared global, is changed only inside the function.

# eggcolor = "green" meat = "ham"

print eggcolor, "eggs and", meat def breakfast():

global eggcolor eggcolor = "red" meat = "bacon"

print eggcolor, "eggs and", meat breakfast()

print eggcolor, "eggs and", meat

If you run this code on the command line, you get the following result:

% python green eggs and ham red eggs and bacon red eggs and ham

REMEMBER It's usually a Bad Idea to use global names because they are more likely to cause name conflicts in complex programs.

Was this article helpful?

0 0

Post a comment