0% found this document useful (0 votes)
3 views7 pages

Function and Modular Programming Lesson004

The document explains the concept of functions in Python, highlighting their role in modular programming by breaking code into reusable blocks. It covers defining functions, calling them, using parameters, return values, and the concept of recursion, along with examples. Additionally, it discusses function overloading and how Python handles it differently compared to other languages.

Uploaded by

BRIAN MUTURI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

Function and Modular Programming Lesson004

The document explains the concept of functions in Python, highlighting their role in modular programming by breaking code into reusable blocks. It covers defining functions, calling them, using parameters, return values, and the concept of recursion, along with examples. Additionally, it discusses function overloading and how Python handles it differently compared to other languages.

Uploaded by

BRIAN MUTURI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Function and modular programming

In Python, a function is a group of related statements that performs a specific task.

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.

A function is a block of code which only runs when it is called.

You can pass data, known as parameters, into a function.

A function can return data as a result.

Furthermore, it avoids repetition and makes the code reusable.

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 first statement of a function can be an optional statement - the documentation


string of the function or docstring.

• 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:

def functionname( parameters ):

"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 −

# Function definition is here def printme( str ):

"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")

I'm first call to user defined function!

Again second call to the same function

Example

def greet(name):

"""Returns a greeting message"""

return f"Hello, {name}!"

# Calling the function

message = greet("Alice")

print(message) # Output: "Hello, Alice!"

Key Points
def keyword defines a function.

Parentheses () hold parameters (if any).

Colon : starts the function block.

Docstring describes the function (optional but recommended).

return exits the function and sends back a value (default=None).

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.

Multiple Parameters / Arguments

We can define more than one parameter in the function definition

We simply add more arguments when we call the function

We match the number and order of arguments and parameter

def addtwo(a, b):

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”

print greet(), "Glenn”

print greet(), "Sally"


Hello Glenn

Hello Sally

A “fruitful ” function is one that produces a result (or return value )

The return statement ends the function execution and “sends back” the result of the function

Example

def min_max(numbers):

return min(numbers), max(numbers) # Returns a tuple

result = min_max([4, 2, 9, 7])

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:

def sum(self, a, b):

print("First method:",a+b)

def sum(self, a, b, c):

print("Second method:", a + b + c)
obj=sumClass()

obj.sum(19, 8, 77) #correct output

obj.sum(18, 20) #throws error

output

Second method: 104

Traceback (most recent call last):

File "<string>", line 9, in <module>

TypeError: sum() missing 1 required positional argument: 'c'

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.

Overloading Built-in Functions

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:

def __init__(self, cart):

self.cart= list(cart)
#special function

def __len__(self):

print("The total items are:")

return len(self.cart)#built-in function

purchase = items(['apple', 'banana', 'mango','grapes'])

print(len(purchase))#prints the body of the special function

Output

The total items are:

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

It is a function that calls itself until a base case stops it.

Example: Factorial

def factorial(n):

if n == 0: # Base case

return 1

else: # Recursive case

return n * factorial(n - 1)

print(factorial(5)) # 120
Key Rules for Recursion

1. Base Case: Must exist to prevent infinite recursion.

2. Progress Toward Base Case: Each call should reduce the problem size.

3. Stack Limit: Python has a recursion depth limit (~1000)

You might also like