Function parameters and local variables
A function can take parameters, which are values you supply to the function so that the function can do something utilising those values. These parameters are just like variables except that the values of these variables are defined when we call the function and are already assigned values when the function runs.
Parameters are specified within the pair of parentheses in the function definition, separated by commas. When we call the function, we supply the values in the same way. Note the terminology used - the names given in the function definition are called parameters whereas the values you supply in the function call are called arguments.
#!/usr/bin/python # Filename: func_param.py def printMax(a, b): if a > b: print(a, 'is maximum') elif a == b: print(a, 'is equal to', b) else: print(b, 'is maximum') printMax(3, 4) # directly give literal values x = 5 y = 7 printMax(x, y) # give variables as arguments
$ python func_param.py 4 is maximum 7 is maximum
How It Works:
Here, we define a function called printMax that uses two parameters called a and b. We find out the greater number using a simple if..else statement and then print the bigger number.
The first time we call the function printMax, we directly supply the numbers as arguments. In the second case, we call the function with variables as arguments. printMax(x, y) causes the value of argument x to be assigned to parameter a and the value of argument y to be assigned to parameter b. The printMax function works the same way in both cases.
When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function - i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name.
#!/usr/bin/python # Filename: func_local.py x = 50 def func(x): print('x is', x) x = 2 print('Changed local x to', x) func(x) print('x is still', x)
$ python func_local.py x is 50 Changed local x to 2 x is still 50
How It Works:
The first time that we print the value of the name x with the first line in the function's body, Python uses the value of the parameter declared in the main block, above the function definition.
Next, we assign the value 2 to x. The name x is local to our function. So, when we change the value of x in the function, the x defined in the main block remains unaffected.
With the last print function call, we display the value of x as defined in the main block, thereby confirming that it is actually unaffected by the local assignment within the previously called function.