Function and Modular Programming Lesson004
Function and Modular Programming Lesson004
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.
A function is a block of organized, reusable code that is used to perform a single, related action.
As you already know, Python gives you many built-in functions like print, etc. but you can also
create your own functions. These functions are called user-defined functions.
Defining a Function:
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
• Function blocks begin with the keyword def followed by the function name and
parentheses ( ).
• Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
• The code block within every function starts with a colon : and is indented.
• The statement return [expression] exits a function, optionally passing back an expression
to the caller. A return statement with no arguments is the same as return None.
Syntax:
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same
order that they were defined.
Example:
The following function takes a string as input parameter and prints it on standard screen. def
printme( str ):
"This prints a passed string into this function" print str return
Calling a Function:
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function or directly from the Python prompt. Following is the example to call printme function −
"This prints a passed string into this function" print str return;
# Now you can call printme function printme("I'm first call to user defined function!")
printme("Again second call to the same function")
Example
def greet(name):
message = greet("Alice")
Key Points
def keyword defines a function.
Parameter
A parameter is a variable which we use in the function definition that is a “handle” that allows
the code in the function to access the arguments for a particular function invocation.
added = a + b
return added
x = addtwo(3, 5)
print x
Return Values
Often a function will take its arguments, do some computation and return a value to be used as
the value of the function call in the calling expression. The return keyword is used for this.
def greet():
return "Hello”
Hello Sally
The return statement ends the function execution and “sends back” the result of the function
Example
def min_max(numbers):
print(result) # (2, 9)
Function Overloading
As the name suggests, function overloading is the process where the same function can be used
multiple times by passing a different number of parameters as arguments. But Python does not
support function overloading. An error gets thrown if we implement the function overloading
code the way we do in other languages. The reason is as Python does not have a data type for
method parameters.
The previous function having the same name(but different parameters) gets overridden with the
new function having the same name. So now, if we try to call the first function, which had
different number parameters, by passing a different number of arguments defined in the new
function, we get an error. Let us try to understand the same.
Example
class sumClass:
print("First method:",a+b)
print("Second method:", a + b + c)
obj=sumClass()
output
In the above program, we can see that the second sum method overrides the first sum method.
When we call the function using three arguments, it gives the output, but when we use two
argument, it gives an error. Hence we can say that Python does not support function
overloading.
But does that mean there is no other way to implement this feature? The answer is no. There
are other ways by which we can implement function overloading in Python.
We can achieve it by setting one or more parameters as None in the function declaration. We
will also include the checking condition for None in the function body so that while calling if we
don't provide the argument for a parameter that we have set as None, an error won't occur.
In the Python Data Model, we have a few special functions and it provides us the means of
overloading the built-in functions. The names of the special functions begin with double
underscores(__).
In our example, we will change the default behavior of the len() function by overloading it with
the special function. So when a pre-defined(built-in) function is declared as a special function
inside a class, the interpreter executes the special function as the function definition for the
built-in function's call. Let us see an example using a special function in Python.
class items:
self.cart= list(cart)
#special function
def __len__(self):
Output
The init method is automatically called every time an object gets created from a class. We are
trying to change the default behavior of the len() function in Python, which only displays the
object's length. Whenever we pass an object of our class to len(), the custom definition we have
written for the __len__() function will fetch the desired results.
In our custom definition for __len__ we have added the code we want. This overloads the len()
function.
Recursion in Python
Example: Factorial
def factorial(n):
if n == 0: # Base case
return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
Key Rules for Recursion
2. Progress Toward Base Case: Each call should reduce the problem size.