A function can take parameters which are just 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 not assigned values within the function itself.
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.
Using Function Parameters
Example 7.2. Using Function Parameters
#!/usr/bin/python
# Filename: func_param.py
def printMax(a, b):
if a > b:
print a, 'is maximum'
else:
print b, 'is maximum'
printMax(3, 4) # directly give literal values
x = 5
y = 7
printMax(x, y) # give variables as arguments
Output
$ python func_param.py
4 is maximum
7 is maximum
How It Works
Here, we define a function called printMax where we take two parameters called a and b. We find
out the greater number using a simple if..else statement and then print the bigger number.
In the first usage of printMax, we directly supply the numbers i.e. arguments. In the second usage, we
call the function using variables. printMax(x, y) causes value of argument x to be assigned to
parameter a and the value of argument y assigned to parameter b. The printMax function works the
same in both the cases.
No comments:
Post a Comment