Brief introduction
A function is a reusable program segment. They allow you to give a name to a statement, and then you can use that name to run this block any number of times in any part of your program. This is called the call function. We've used a lot of built-in functions, such as Len and range.
function is defined by the DEF keyword. The DEF keyword is followed by the identifier name of a function followed by a pair of parentheses. The parentheses can include variable names that end with a colon. Next is a statement, which is the function body. The following example will show that this is actually quite simple:
Defining functions
Example 7.1 defines a function
#!/usr/bin/python
# Filename: function1.py
def sayHello():
print 'Hello World!' # block belonging to the function
sayHello() # call the function
(source file: code/function1.py)
Output
$ python function1.py
Hello World!
How it works
We define a function called SayHello using the syntax explained above. This function does not use any arguments, so no variables are declared in parentheses. For a function, a parameter is just an input to a function so that we can pass different values to the function and then get the corresponding result.
function parameters
The function gets the arguments you give to the function, so that the function can do something with these values. These parameters are like variables, except that their values are defined when we call the function, not in the function itself.
Parameters are specified inside the parentheses of the function definition, separated by commas. When we call a function, we provide the value in the same way. Notice the term we used--the parameter name in the function is the formal parameter and the value you provide to the function call is called the argument.
Using function parameters
Example 7.2 uses 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
(source file: code/func_param.py)
Output
$ python func_param.py
4 is maximum
7 is maximum
How it works
Here, we define a function called Printmax, which requires two formal parameters, called A and B. We use the IF. The Else statement finds the larger number of both, and prints the larger number.
In the first Printmax use, we directly give the number, that is, the argument, to provide the function. In the second use, we use variables to call the function. Printmax (x, y) assigns the value of the argument x to the formal parameter a, and the value of the argument y is assigned to the formal parameter B. In two calls, the Printmax function works exactly the same.