


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Modular programming
A global variable is a variable defined in the 'main' program. Such variables are said to have 'global' scope—they can be accessed within any function. A local variable is a variable defined within a function. Such variables are said to have local 'scope'—they are known only to the function. Functions can access global variables and modify them. Modifying global variables in a function is considered poor programming practice. It is better to send a variable in as a parameter (or have it be returned in the 'return' statement).
Think of a function as a black-box with inputs and outputs. The function's input/output should be completely defined by its function signature and return statement. The function should not access (read) or modify global variables directly. Send everything in as a parameter. A function signature is the function name and parameter list def pow(x,n): # this line is the function signature total= count = 0 while count The only effect of a function is the return value and modifications of list/object parameters (scalars cannot be modified).
Inside a function definition, If a variable is read , Python checks to see if it has been defined locally. If it has not, Python will check to see if there is a global with that name. def func(): # read example print x # python will use global x if it exists if a variable is assigned to , a local slot is created for it. def func(): # write example x=7 # will not use global even if global 'x' exists.
def func(): # how to write to a global global x x= x=x+1 # modifies global x Consider the following program snippets. What is the result of each? def f(): x= x= f() print x
def f(): print x x = 5 f()
def f(): global x x= x= f() print x
def generateSecret(): i= while i<4: color = random.randint(0,5) secretCode.append(colors[color]) i=i+
colors=['r','b','g','p','y','b'] secretCode=[] generateSecret() print secretCode
def generateSecret(): secretCode=[] i= while i<4: color = random.randint(0,5) secretCode.append(colors[color]) i=i+ return secretCode
colors=['r','b','g','p','y','b'] secretCode = generateSecret() print secretCode