Functions and Modules
Functions and Modules
Python Programming
Using Problem Solving Approach
Reema Thareja
7
Example:
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.
Examples
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.
10
Example:
11
12
13
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
Examples:
14
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.
• First, if you skip arguments.
• Second, if in the function call you change the order of parameters.
Example:
15
Example:
16
Example:
17
Example:
18
Example:
19
Example:
20
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,
21
Examples:
22
Example:
23
Example:
24
25
26
27
28
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.
29