Program control: Looping, conditionals and functions ( Part 2)
Categories: Python
Then, if the user really intended to replace the old list, he or she would use L =
bump(L)
Often, the evaluation of a function will require a number of constants or parameters which you might not need to change very often, or which are common to a great many different functions. These could always be added to the parameter list. If there are many of them, that could become tedious. Soon you will learn how to create objects which provide a way to package data in a way that allows you to keep the argument list of functions under control. There is yet another technique, though, that can be useful if used with discretion, namely the global variable.
Global variables are set outside functions, and can be accessed by any function that needs them. In many languages, global variables need to be declared explicitly, but Python simply makes an intelligent guess about what you intend to be global. Basically, if a variable is used within a function, but is neither set in the function nor is in the argument list, Python assumes it to be global. Note that the same variable name can be local in one function (if it is set internally), but global in another.
As an example of the use of global variables, consider the function computing the acceleration of gravity towards the center of a planet at the origin:
def grav(r):
return -G*M/(r*r)
This has a problem, because the gravitational constant G and the mass of the planet M have not been defined anywhere. It’s bad practice to hard-wire their values in the function, because then it’s inconvenient to change them later. If you try evaluating the function after you’ve defined it, you’ll get an error message (try it). However, if you type:
G = 6.6742e-11 # In mks units
M = 6.4185e23 #Mass of Mars inkg
grav(1.e12)
everything will work fine. You do not need to define the globals until you want to evaluate the function, and you can change their values at any time.
This is convenient, but if you have too many globals being set in too many places, it can be hard to keep track of what is going on. It is also bad practice to use globals for things you will change a lot, which would more appropriately be arguments. The behavior of globals can become even more confusing if you have functions spread across several different files. Nonetheless, you will encounter many
cases where using a few globals does the job nicely.