0% found this document useful (0 votes)
5 views27 pages

Slide_3

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

Slide_3

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

Functions and Modules

A function is a block of organized and re-usable program code that performs a single, specific, and
well-defined task

Like as of till now, we have been using:


input() to take input from the user
print() to display some information on the screen
int() to convert the user entered information into int data type

1
Functions
Python enables its programmers to break up a program into segments commonly known as functions, each
of which can be written more or less independently of the others. Every function in the program is
supposed to perform a well-defined task.

Calling a function Function Calling another function 2


Need for Functions
Each function can be written and tested separately.
• Understanding, coding and testing multiple separate functions is far easier.
Without the use of any function, then there will be countless lines in the code and maintaining it will be a big
mess.
• Programmers use functions without worrying about their code details. This speeds up program development,
by allowing the programmer to concentrate only on the code that he has to write.
Different programmers working on that project can divide the workload by writing different functions.
• Like Python libraries, programmers can also make their functions and use them from different point in the
main program or any other program that needs its functionalities.

Functions provide better modularity for the applications and has a high 3

degree of code re-usability


Function Declaration and Definition

• A function, f that uses another function g, is known as the calling function and g is known as the called function.
• The inputs that the function takes are known as arguments/parameters.
• When a called function returns some result back to the calling function, it is said to return that result.
• The calling function may or may not pass parameters to the called function. If the called function accepts
arguments, the calling function will pass parameters, else not.
• Function declaration is a declaration statement that identifies a function with its name, a list of arguments
that it accepts and the type of data it returns.
• Function definition consists of a function header that identifies the function, followed by the body of the
function containing the executable code for that function.

4
Besides using built-in functions, users can also write their own functions.
Such functions are called user defined functions
Function Definition
Function blocks starts with the keyword def.
• The keyword is followed by the function name and parentheses (( )).
• After the parentheses a colon (:) is placed.
• Parameters or arguments that the function accept are placed within parentheses.
• • The code block within the function is properly indented to form the block code.
• A function may have a return[expression] statement. ( the return statement is optional)
• You can assign the function name to a variable. Doing this will allow you to call same function using the name
of that variable.
Example:

5
Before calling a function, you must
Function Call define it just as you assign variables
before using them
The function call statement invokes the function. When a function is invoked the program control jumps to
the called function to execute the statements that are a part of that function. Once the called function is
executed, the program control passes back to the calling function.
Function Parameters
A function can take parameters which are nothing but some values that are passed to it so that the function
can manipulate them to produce the desired result. These parameters are normal variables with a small
difference that the values of these variables are defined (initialized) when we call the function and are then
passed to the function.
Function name and the number and type of arguments in the function call must be same as that given in the
function definition.
If the data type of the argument passed does not matches with that expected in function then an error is
6
generated.
Examples

7
Some important points to remember
The function name and the number of arguments in the function call must be same as that given in
the function definition.

If by mistake the parameters passed to a function are more than that it is specified to accept, then an
error will be returned. Function definition header
def func(i): accepts a variable with name i
def func(i):
def func(i, j): print (“ABC”, i)
print (“ABC”, i)
print (“ABC”, i,j) j=10
func(5,5)
func(5) func(j) Function is called using variable j
Output:
Output: Output:
Error
Error ABC 10

8
Local and Global Variables

A variable which is defined within a function is local to that function. A local variable can be accessed from
the point of its definition until the end of the function in which it is defined. It exists as long as the function is
executing. Function parameters behave like local variables in the function. Moreover, whenever we use the
assignment operator (=) inside a function, a new local variable is created.

Global variables are those variables which are defined in the main body of the program file. They are visible
throughout the program file. As a good programming habit, you must try to avoid the use of global variables
because they may get altered by mistake and then result in erroneous output.

9
Local and Global Variables
Example:

10
Global Variables Local Variables

 They are defined within a function and are local to


 They are defined in the main body of the program
the function.
file
 They can be accessed from the point of their
 They can be accessed throughout the program.
definition until the end of the block in which they
 Global variables are accessible to all functions in the are defined.
program
 They are not related in any way to other variables
with the same names used outside the function

11
Using the Global Statement
To define a variable defined inside a function as global, you must use the global statement. This declares the
local or the inner variable of the function to have module scope.

Example:

12
The Return Statement
The syntax of return statement is,
return [expression]
The expression is written in brackets because it is optional. If the expression is present, it is evaluated and the
resultant value is returned to the calling function. However, if no expression is specified then the function will
return None. Example:

The return statement is used for two things.


• Return a value to the caller
• To end and exit a function and go back to its caller

13
Some more ways of defining function
• Required arguments

• Keyword arguments

• Variable-length arguments

• Default Arguments

All these features makes python a wonderful language

14
Required Arguments

In the required arguments, the arguments are passed to a function in correct positional order. Also, the number
of arguments in the function call should exactly match with the number of arguments specified in the
function definition. The function display (), displays the string only when number and type of arguments in the
function call matches with that specifies in the function definition.

Examples:

15
Keyword Arguments

When we call a function with some values, the values are assigned to the arguments based on their position.
Python also allow functions to be called using keyword arguments in which the order (or position) of the
arguments can be changed. The values are not assigned to arguments according to their position but based
on their name (or keyword).
Keyword arguments are beneficial in two cases. In both these cases, python interpreter uses
• First, if you skip arguments. keywords provided in the function call to
match the values with parameters
• Second, if in the function call you change the order of parameters.
Example:

16
Variable-length Arguments
In some situations, it is not known in advance how many arguments will be passed to a function. In such cases,
Python allows programmers to make function calls with arbitrary (or any) number of arguments.
When we use arbitrary arguments or variable length arguments, then the function definition use an asterisk
(*) before the parameter name.The syntax for a function using variable arguments can be given as,

Example:

17
Default Arguments
Python allows users to specify function arguments that can have default values.This means that a function can be
called with fewer arguments than it is defined to have.That is, if the function accepts three parameters, but function
call provides only two arguments, then the third parameter will be assigned the default (already specified) value.
The default value to an argument is provided by using the assignment operator (=). Users can specify a
default value for one or more arguments.

Example:

18
Recursive Functions
A recursive function is defined as a function that calls itself to solve a smaller version of its task until a final
call is made which does not require a call to itself. Every recursive solution has two major cases, which are as
follows:
• base case, in which the problem is simple enough to be solved directly without making any further calls to
the same function.
• recursive case, in which first the problem at hand is divided into simpler sub parts.
Recursion utilized divide and conquer technique of problem solving.
Example:

19
The from…import Statement
A module may contain definition for many variables and functions. When you import a module, you can use
any variable or function defined in that module. But if you want to use only selected variables or functions,
then you can use the from...import statement. For example, in the aforementioned program you are using
only the path variable in the sys module, so you could have better written from sys import path.

Example: Note: to import all the identifiers defined


in the system module, we can use
from system import * statement

To import more than one item from a module, use a comma separated list. For example, to import the
value of pi and sqrt() from the math module you can write,
20
Making your own Modules
Every Python program is a module, that is, every file that you save as .py extension is a module.

Note that we have been using the dot operator to access


members of the module. Assuming that Mymodule has
many other variables or functions definition we could have
imported just str () and display()
21

from Mymodule import str, display


The dir() function
dir() is a built-in function that lists the identifiers defined in a module. These identifiers may include functions,
classes and variables. If you mention the module name in the dir () function, it will return the list of all the
names defined in that module but If no name is specified, the dir() will return the list of names defined in the
current module.
Example:

22
Modules and Namespaces
A namespace is a container that provides a named context for identifiers. Two identifiers with the same name
in the same scope will lead to a name clash. In simple terms, Python does not allow programmers to have two
different identifiers with the same name. However, in some situations we need to have same name identifiers.
To cater to such situations, namespaces is the keyword. Namespaces enable programs to avoid potential
name clashes by associating each identifier with the namespace from which it originates.

Example:

Result1=module1.repeat_x(10)
Result2=module2.repeat_x(10)23
Local, Global, and Built-in Namespaces
During a program’s execution, there are three main namespaces that are referenced- the built-in namespace,
the global namespace, and the local namespace. The built-in namespace, as the name suggests contains
names of all the built-in functions, constants, etc that are already defined in Python. The global namespace
contains identifiers of the currently executing module and the local namespace has identifiers defined in the
currently executing function (if any).
When the Python interpreter sees an identifier, it first searches the local namespace, then the global
namespace, and finally the built-in namespace. Therefore, if two identifiers with same name are defined in
more than one of these namespaces, it becomes masked.

24
Local, Global, and Built-in Namespaces
Example:

25
Module Private Variables
In Python, all identifiers defined in a module are public by default. This means that all identifiers are accessible
by any other module that imports it. But, if you want some variables or functions in a module to be privately
used within the module, but not to be accessed from outside it, then you need to declare those identifiers as
private.
In Python identifiers whose name starts with two underscores (__) are known as private identifiers. These
identifiers can be used only within the module. In no way, they can be accessed from outside the module.
Therefore, when the module is imported using the import * from modulename, all the identifiers of a module’s
namespace is imported except the private ones (ones beginning with double underscores). Thus, private identifiers
become inaccessible from within the importing module.

26
Globals(), Locals(), And Reload()

The globals() and locals() functions are used to return the names in the global and local namespaces (In
Python, each function, module, class, package, etc owns a “namespace” in which variable names are identified
and resolved). The result of these functions is of course, dependent on the location from where they are
called. For example,
If locals() is called from within a function, names that can be accessed locally from that function will be
returned.
If globals() is called from within a function, all the names that can be accessed globally from that function is
returned.
Reload()- When a module is imported into a program, the code in the module is executed only once. If you
want to re-execute the top-level code in a module, you must use the reload() function. This function again
imports a module that was previously imported. 27

You might also like