0% found this document useful (0 votes)
7 views35 pages

UNIT3

Uploaded by

.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views35 pages

UNIT3

Uploaded by

.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

1

Unit – III
Errors and Exceptions: Syntax Errors, Exceptions, Handling Exceptions,
Raising Exceptions, User-defined Exceptions, Defining Clean-up Actions,
Redefined Clean-up Actions.
Functions: What are Functions, Defining and Creating functions, Function
Arguments: Formal and Variable length, Calling functions, Recursive Functions
and Variable Scope. Modules: Modules, Standard Modules, Importing Modules,
Namespaces and Packages.

Detecting and Correcting Syntax Errors


Programmers inevitably make typographical errors when editing
programs, and the Python interpreter will nearly always detect them. Such errors
are called syntax errors.
The term syntax refers to the rules for forming sentences in a language.
When Python encounters a syntax error in a program, it halts execution with an
error message. The following sessions with the Python shell show several types
of syntax errors and the corresponding error messages:
>>> length = int(input("Enter the length: "))
Enter the length: 44
>>> print(lenth)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
NameError: name 'lenth' is not defined

The first statement assigns an input value to the variable length. The next
statement attempts to print the value of the variable lenth. Python responds that
this name is not defined. Although the programmer might have meant to write
the variable length, Python can read only what the programmer actually entered.
This is a good example of the rule that a computer can read only the instructions
it receives, not the instructions we intend to give it.
The next statement attempts to print the value of the correctly spelled
variable. However, Python still generates an error message.
>>> print(length)
SyntaxError: unexpected indent

In this error message, Python explains that this line of code is


unexpectedly indented. In fact, there is an extra space before the word print.
Indentation is significant in Python code. Each line of code entered at a shell
prompt or in a script must begin in the leftmost column, with no leading spaces.
The only exception to this rule occurs in control statements and definitions,
where nested statements must be indented one or more spaces.
You might think that it would be painful to keep track of indentation in a
program. However, in compensation, the Python language is much simpler than
other programming languages. Consequently, there are fewer types of syntax
errors to encounter and correct, and a lot less syntax for you to learn! In our
2

final example, the programmer attempts to add two numbers, but forgets to
include the second one:
>>> 3 +
SyntaxError: invalid syntax

Exceptions
Any programming language has two types of errors.
1. Syntax error : Errors due to invalid syntax.
Ex: print ‘hai’ # gives syntax error missing parenthesis in call to print
- Syntax errors are fixed by programmer, once fixed program can be
executed normally

2. Runtime error: (exceptions)


- Errors during Runtime of the program.
Ex: print(10/0) # ZeroDivisionError: division by zero
print(10/x) # NameError: name 'x' is not defined.
Exception handling is applicable for the handling the run time errors only
not for the syntax errors.

What is an Exception?
Exception is a run time error.
An unwanted, unexpected event that disturbs normal flow of the program
is called Exception.
Example: our program requirement is read the data from a remote file
located in Landon. At runtime if Landon file is not available program is
terminated abnormally
exception is that FileNotFoundError.

What is an Exception Handling?


 Graceful termination of the program.
 Defining an alternative way to continue rest of the program execution
normally.
 If anything went wrong we should not miss or lose anything.
 Concept of exception handling is to provide alternative way to continue
flow of execution normally without losing anything.
try:
read data from a file located at Landon
except:
use local file and continue rest of the program normally

If the Landon file not available our program should not be terminated
abnormally. We have to provide some local file to continue rest of the program
normally. This is nothing but Exception Handling.
3

 Exception handling does not fix the run time error. It provides the
alternative way to continue the execution of rest of the program.

Benefits of exception handling


• Exception handling is used to continue the flow of execution without
terminating the program abnormally when run time error is encounter.
• Fix the run time errors
• Separates the error code and regular code using try and except blocks.

Default exception handling in python


• Every exception in a python is an object. Every exception has a
corresponding class.
• Example:
print(‘hai’)
print(10/0)
print(‘hello cse1’)

 When the exception raised in python, python virtual machine(PVM)


creates corresponding exception object and checks for the exception
handling code in the program. If no handling code in the python, python
interpreter terminates the program abnormally and gives the exception
report to the program. Then rest of the program will not be executed.
 Exception is a base class for all exceptions

Built in Exception in python


- AttributeError- attribute assignment or reference fails
- FloatingpointError- raised when floating point operation fails
- ImportError- module not found
- NameError- when a variable not found in local or global space.
- ZeroDivisionError- when a number divides with zero.

Exception hierarchy
4

Handling Exceptions:( try,except,finally)


- try ,except and finally keywords are used to handle exceptions.
- Syntax:
try:
riskycode
except Exceptionclass:
handling code
finally:
cleanup code
Where, risky code means- code that raises the exception
handling code – alternative way.
Note: using finally block is optional.

Example

Program terminated normally though exception raised.

Control flow in try and except


5

In which order statements are executed if exception rised?


try:
statement1;
statement2;
statement3;
except:
statement4;
statement5;

Case1:- no exception
1,2,3&5 are executed
Case2:- if exception rised at statement2
1,4,5 are executed.
once it comes out of try block control never goes back. Rest of
the try block never executed so write only risky code inside of the try
block.
Case 3:- if exception rised at statement4
exceptions can be rised in except and finally blocks also sometimes
- causes abnormal termination.
Case4:- if exception rised in try block and if corresponding except block is not
present
- causes abnormal termination.

Note: within the try block if anywhere an exception rised then the rest of try
block won’t be executed even though we handled that exception. Hence within
the try block we have to take only risky code and length of the try block should
be as less as possible.

How to print the exception information ?


6

try:
print(10/0)
except ZeroDivisionError as info:
print(“exception raised due to”, info)

Output:
exception raised due to division by zero

try with multiple except blocks


• If programmer does not know what type of exception will rise in the code
then go for the multiple except blocks.
• For every exception a separate except block is to be defined.
• When exception is thrown, each except block is inspected in order, and
the first one which matches with the type of exception that except block
will be executed.
• When multiple except blocks used in a program you must remember in
which order exception types should be specified for except block.
• Exception subclasses should come before its super class exceptions why
because except statement which has super class will handle all its sub
classes exceptions.
• It never give chance to handle for its sub class

Example:

Test case1:

Test case2:

Test case3:
7

 Exception subclasses should come before its super class exceptions why
because except statement which has super class will handle all its sub
classes exceptions .
 It never give chance to handle for its sub class

Single except block handles multiple exceptions


• A single except block can handle multiple exceptions using following
syntax.
• Syntax:
except(exception1,exception2,……) or
except(exception1,exception2,…..) as info
Note: parenthesis is must and will consider internally as tuple

Default except block


• To handle any type of error we can use default except block.
• Syntax:
8

except:
statement

Note: If try with multiple except blocks available then default except
block should be last, otherwise we will get SyntaxError.

How many ways we can use except block


1. except ValueError:
2. except ValueError as info:
3. except(ValueError,TypeError):
4. except(ValueError,TypeError) as info
5. except:

finally keyword
finally is a block always associated with try and except to maintain
clean up code.

What is specialty of finally?


finally block is always executed irrespective of whether exception is rised or
not rised and whether handled or not handled.
whatever resources are allocated in the try block can be deallocated by
finally block.
Syntax:
try:
risky code
except:
handling code
finally:
clean up code
9

Case study where finally block is more useful


Suppose open a file in read mode and read first line of a file and display it.
1. f=open(‘test.py’,’r’)
2. data=f.readline()
3. print(dat)# NameError
4. f.close()
in above code exception at line no 3. file unable to close. Then use finally
block.
Output:

Example:

Output:
hai
file closed

Nested try-except-finally blocks:


 We can define try-except-finally blocks inside the try, except and finally
blocks i.e nested try-except-finally blocks.
try:
10

st1
st2
try:
st3
except:
st4
finally:
st5
except:
st6
finally:
st7
st8
 when exception rised in inner try block, inner except block will handle
exception. If inner except block unable to handle, then outer except block
will handle.
Example:

else clause with try-except-finally


 Along with try-except-finally blocks we can also use else clause.
 else block will be executed when try block does not rise the exception.
Syntax:
try:
errorcode
except:
executed when exception rised
else:
executed when no exception
finally:
executed irrelevant of the exception
Example:
11

- if elseTryEx.py file available no exception raised in try block then else block
will be executed.
- if exception raised else block will not be executed.

Types of exceptions
• There are two types of exceptions in python
1. Predefined / built in exceptions: when the exception raised in python
program, python virtual machine creates exception object and stops the
program execution and gives the information to the programmer.
Ex: ZeroDivisionError, ValueError, TypeError etc.
2. User defined exceptions / customized exceptions: user or programmer
can raise his own exceptions explicitly to deal with common problems
such as
a) attempting to enter invalid PIN in ATM transactions.-InvalidPinError
b) attempt to enter negative salary for an employee- NegativeSalaryError
c) attempt to enter wrong username and password- WrongDetailsError
d) attempt to withdraw more amount than existing.-
InsufficientFundsError

Raising Exceptions
raise exceptions by user
‘ raise’ statement is used to raise the exceptions forcefully by the user
rather than python virtual machine.
Example
12

Re-raise the exception


• We can also reraise the excpetion

How to define and raise customized exceptions


 Exception is super class for all the exceptions in python.
 User defined exceptions are defined by create a class that extends
Exception class.
 Raise the exception using keyword ‘raise’.
 raise is used to forcefully raise the exception by the user.
 Syntax:
class classname(Exception):
def __init__(self,msg):
self.msg=msg
Example:

User-Defined Exceptions
By inheriting classes from the typical built-in exceptions, Python also lets
us design our customized exceptions.
Here is an illustration of a RuntimeError. In this case, a class that derives
from RuntimeError is produced. Once an exception is detected, we can use this
to display additional detailed information.
13

We raise a user-defined exception in the try block and then handle the
exception in the except block. An example of the class EmptyError is created
using the variable var.

Code
class EmptyError( RuntimeError ):
def __init__(self, argument):
self.arguments = argument
Once the preceding class has been created, the following is how to raise an
exception:
Code
var = " "
try:
raise EmptyError( "The variable is empty" )
except (EmptyError, var):
print( var.arguments )
Output:
2 try:
----> 3 raise EmptyError( "The variable is empty" )
4 except (EmptyError, var):

EmptyError: The variable is empty

Python Exceptions List

Sr.No. Name of the Description of the Exception


Exception

1 Exception All exceptions of Python have a base class.

2 StopIteration If the next() method returns null for an iterator,


this exception is raised.

3 SystemExit The sys.exit() procedure raises this value.

4 StandardError Excluding the StopIteration and SystemExit, this


is the base class for all Python built-in
exceptions.

5 ArithmeticError All mathematical computation errors belong to


this base class.

6 OverflowError This exception is raised when a computation


surpasses the numeric data type's maximum
limit.
14

7 FloatingPointError If a floating-point operation fails, this exception


is raised.

8 ZeroDivisionError For all numeric data types, its value is raised


whenever a number is attempted to be divided by
zero.

9 AssertionError If the Assert statement fails, this exception is


raised.

10 AttributeError This exception is raised if a variable reference or


assigning a value fails.

11 EOFError When the endpoint of the file is approached, and


the interpreter didn't get any input value by
raw_input() or input() functions, this exception is
raised.

12 ImportError This exception is raised if using the import


keyword to import a module fails.

13 KeyboardInterrupt If the user interrupts the execution of a program,


generally by hitting Ctrl+C, this exception is
raised.

14 LookupError LookupErrorBase is the base class for all search


errors.

15 IndexError This exception is raised when the index


attempted to be accessed is not found.

16 KeyError When the given key is not found in the


dictionary to be found in, this exception is raised.

17 NameError This exception is raised when a variable isn't


located in either local or global namespace.

18 UnboundLocalError This exception is raised when we try to access a


local variable inside a function, and the variable
has not been assigned any value.

19 EnvironmentError All exceptions that arise beyond the Python


environment have this base class.

20 IOError If an input or output action fails, like when using


the print command or the open() function to
access a file that does not exist, this exception is
raised.
15

22 SyntaxError This exception is raised whenever a syntax error


occurs in our program.

23 IndentationError This exception was raised when we made an


improper indentation.

24 SystemExit This exception is raised when the sys.exit()


method is used to terminate the Python
interpreter. The parser exits if the situation is not
addressed within the code.

25 TypeError This exception is raised whenever a data type-


incompatible action or function is tried to be
executed.

26 ValueError This exception is raised if the parameters for a


built-in method for a particular data type are of
the correct type but have been given the wrong
values.

27 RuntimeError This exception is raised when an error that


occurred during the program's execution cannot
be classified.

28 NotImplementedError If an abstract function that the user must define


in an inherited class is not defined, this exception
is raised.

Defining Clean Up Actions in Python


There are numerous situation occurs when we want our program to do
this specific task, irrespective of whether it runs perfectly or thrown some error.
Mostly to catch at any errors or exceptions, we use to try and except block.
The “try” statement provides very useful optional clause which is meant for
defining ‘clean-up actions’ that must be executed under any circumstances. For
example −
>>> try:
raise SyntaxError
finally:
print("Learning Python!")
Learning Python!
Traceback (most recent call last):
File "<pyshell#11>", line 2, in <module>
16

raise SyntaxError
File "<string>", line None
SyntaxError: <no detail available>
The final clause will execute no matter what, however, the else clause executes
only if an exception was not raised.

Example1 − Consider below example, where everything looks ok and writing


to a file with no exception (the program is working), will output the following −
file = open('finally.txt', 'w')
try:
file.write("Testing1 2 3.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")
On running above program, will get −
Writing to file.
Write successful.
File closed.

Example 2 − Let's try to raise an exception by making a file read-only and try
to write onto it, thus causing it to raise an exception.
file = open('finally.txt', 'r')
try:
file.write("Testing1 2 3.")
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
17

print("Write successful.")
finally:
file.close()
print("File closed.")
Above program will give an output, something like −
Could not write to file.
File closed.
In case we have an error, but we have not put any except clause to handle it. In
such a case, the clean-up action (finally block) will be executed first and then
the error is raised by the compiler. Let's understand the concept with the below
example −

Example

file = open('finally.txt', 'r')


try:
file.write(4)
print("Writing to file.")
except IOError:
print("Could not write to file.")
else:
print("Write successful.")
finally:
file.close()
print("File closed.")

Output

File closed.
Traceback (most recent call last):
File "C:/Python/Python361/finally_try_except1.py", line 4, in <module>
file.write(4)
TypeError: write() argument must be str, not int
So from above, we can see that, finally, clause executes always, irrespective of
whether an exception occurs or not.
18

Predefined Clean-up Actions


Some objects define standard clean-up actions to be undertaken when the object
is no longer needed, regardless of whether or not the operation using the object
succeeded or failed. Look at the following example, which tries to open a file
and print its contents to the screen.

for line in open("myfile.txt"):


print(line, end="")

The problem with this code is that it leaves the file open for an indeterminate
amount of time after this part of the code has finished executing. This is not an
issue in simple scripts, but can be a problem for larger applications.
The with statement allows objects like files to be used in a way that ensures they
are always cleaned up promptly and correctly.

with open("myfile.txt") as f:
for line in f:
print(line, end="")

After the statement is executed, the file f is always closed, even if a problem was
encountered while processing the lines. Objects which, like files, provide
predefined clean-up actions will indicate this in their documentation.

Assertions in Python
An assertion is a sanity-check that you can turn on or turn off when you
are done with your testing of the program.
 The easiest way to think of an assertion is to liken it to a raise-if
statement (or to be more accurate, a raise-if-not statement). An
expression is tested, and if the result comes up false, an exception is
raised.
 Assertions are carried out by the assert statement, the newest keyword to
Python, introduced in version 1.5.
 Programmers often place assertions at the start of a function to check for
valid input, and after a function call to check for valid output.

The assert Statement


When it encounters an assert statement, Python evaluates the
accompanying expression, which is hopefully true. If the expression is false,
Python raises anAssertionError exception.
The syntax for assert is −
assert Expression[, Arguments]
19

If the assertion fails, Python uses ArgumentExpression as the argument


for the AssertionError. AssertionError exceptions can be caught and handled
like any other exception, using the try-except statement. If they are not handled,
they will terminate the program and produce a traceback.

Example
Here is a function that converts a given temperature from degrees Kelvin
to degrees Fahrenheit. Since 0° K is as cold as it g ets, the function bails out if it
sees a negative temperature
#!/usr/bin/python3
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print (KelvinToFahrenheit(273))
print (int(KelvinToFahrenheit(505.78)))
print (KelvinToFahrenheit(-5))

When the above code is executed, it produces the following result


32.0
451
Traceback (most recent call last):
File "test.py", line 9, in
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!
20

Functions
What are Functions
A function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your application
and a high degree of code reusing.
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 and Creating functions


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 without parameters


def my_function():
print("Hello from a function")

Syntax with parameters


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" # docstring
print(str)
return
21

Calling Functions
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 −

Example
def my_function():
print("Hello from a function")

my_function()

Example:
# 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")

Output:
I'm first call to user defined function!
Again second call to the same function

Pass by reference vs value


All parameters (arguments) in the Python language are passed by
reference. It means if you change what a parameter refers to within a function,
the change also reflects back in the calling function. For example −
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
22

Here, we are maintaining reference of the passed object and appending


values in the same object.
Output:
Values inside the function: [10, 20, 30, [1, 2, 3, 4]]
Values outside the function: [10, 20, 30, [1, 2, 3, 4]]

There is one more example where argument is being passed by reference


and the reference is being overwritten inside the called function.
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

The parameter mylist is local to the function changeme. Changing mylist within
the function does not affect mylist. The function accomplishes nothing and
finally this would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]

Function Arguments
Information can be passed into functions as arguments. Arguments are
specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When
the function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

Output:
Emil
Tobias
Linus
23

Parameters or Arguments?
The terms parameter and argument can be used for the same thing:
information that are passed into a function.
From a function's perspective: A parameter is the variable listed inside the
parentheses in the function definition. An argument is the value that is sent to
the function when it is called.

Formal and Actual Arguments


When a function is defined, it may have some parameters. These
parameters are useful to receive values from outside of the function. They are
called 'formal arguments'. When we call the function, we should pass data or
values to the function. These values are called 'actual arguments'. In the
following code, 'a' and 'b' are formal arguments and 'x' and 'y' are actual
arguments.
def sum(a,b): #a,b are formal arguments
c=a+b
print(c)

x=10
y=15
sum(x,y)

Types of Formal Arguments


 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required Arguments
By default, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you have to call
the function with 2 arguments, not more, and not less.
Example
This function expects 2 arguments, and gets 2 arguments:
def my_function(fname, lname):
print(fname + " " + lname)

my_function("Emil", "Refsnes")

Output: Emil Refsnes

Example:
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
24

print str
return;

# Now you can call printme function


printme()
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)

Keyword Arguments
You can also send arguments with the key = value syntax. This way the
order of the arguments does not matter.
Example
def my_function(child3, child2, child1):
print("The youngest child is " + child3)

my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")


Output: The youngest child is Linus

Arbitrary Keyword Arguments, **kwargs


If you do not know how many keyword arguments that will be passed into
your function, add two asterisk: ** before the parameter name in the function
definition.
This way the function will receive a dictionary of arguments, and can
access the items accordingly:
Example
If the number of keyword arguments is unknown, add a double ** before
the parameter name:
def my_function(**kid):
print("His last name is " + kid["lname"])

my_function(fname = "Tobias", lname = "Refsnes")


Output: His last name is Refsnes

Default arguments
A default argument is an argument that assumes a default value if a value
is not provided in the function call for that argument. The following example
gives an idea on default arguments, it prints default age if it is not passed −
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
25

# Now you can call printinfo function


printinfo( age=50, name="miki" )
printinfo( name="miki" )

Output:
Name: miki
Age 50
Name: miki
Age 35

Variable-length arguments
You may need to process a function for more arguments than you
specified while defining the function. These arguments are called variable-
length arguments and are not named in the function definition, unlike required
and default arguments.
Syntax for a function with non-keyword variable arguments is this −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of
all nonkeyword variable arguments. This tuple remains empty if no additional
arguments are specified during the function call. Following is a simple example
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print "Output is: "
print arg1
for var in vartuple:
print var
return;

# Now you can call printinfo function


printinfo( 10 )
printinfo( 70, 60, 50 )

Output is:
10
Output is:
70
60
50

Arbitrary Arguments, *args


26

If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition. This way
the function will receive a tuple of arguments, and can access the items
accordingly:
Example
If the number of arguments is unknown, add a * before the parameter
name:
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")


Output: The youngest child is Linus

The Anonymous Functions


These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. You can use the lambda keyword to
create small anonymous functions.
 Lambda forms can take any number of arguments but return just one
value in the form of an expression. They cannot contain commands or
multiple expressions.
 An anonymous function cannot be a direct call to print because lambda
requires an expression
 Lambda functions have their own local namespace and cannot access
variables other than those in their parameter list and those in the global
namespace.
 Although it appears that lambda's are a one-line version of a function,
they are not equivalent to inline statements in C or C++, whose purpose is
by passing function stack allocation during invocation for performance
reasons.
Syntax
The syntax of lambda functions contains only a single statement, which is
as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is the example to show how lambda form of function works −
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )

Output:
Value of total : 30
Value of total : 40
27

The return Statement


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.
All the above examples are not returning any value. You can return a
value from a function as follows −
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total

Output:
Inside the function : 30
Outside the function : 30

The pass Statement


function definitions cannot be empty, but if you for some reason have a
function definition with no content, put in the pass statement to avoid getting an
error.
Example
def myfunction():
pass

Recursion
Python also accepts function recursion, which means a defined function
can call itself.
Recursion is a common mathematical and programming concept. It means
that a function calls itself. This has the benefit of meaning that you can loop
through data to reach a result.
The developer should be very careful with recursion as it can be quite
easy to slip into writing a function which never terminates, or one that uses
excess amounts of memory or processor power. However, when written
correctly recursion can be a very efficient and mathematically-elegant approach
to programming.
In this example, tri_recursion() is a function that we have defined to call
itself ("recurse"). We use the k variable as the data, which decrements (-1) every
time we recurse. The recursion ends when the condition is not greater than 0
(i.e. when it is 0).
28

To a new developer it can take some time to work out how exactly this
works, best way to find out is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Example Results")


tri_recursion(6)

Output:
Recursion Example Results
1
3
6
10
15
21

Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in Python
 Global variables
 Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.
This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed throughout
the program body by all functions. When you call a function, the variables
declared inside it are brought into scope. Following is a simple example −
total = 0; # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
29

return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total

Output:
Inside the function local total : 30
Outside the function global total : 0
30

Modules
A module allows you to logically organize your Python code. Grouping
related code into a module makes the code easier to understand and use. A
module is a Python object with arbitrarily named attributes that you can bind
and reference.
Simply, a module is a file consisting of Python code. A module can define
functions, classes and variables. A module can also include runnable code.
The Python code for a module named aname normally resides in a file
named aname.py.
Here is an example of a simple module, support.py-
def print_func( par ):
print "Hello : ", par
return
Importing Modules
The import Statement
You can use any Python source file as a module by executing an import
statement in some other Python source file. The import has the following syntax
import module1[, module2[,... moduleN]
When the interpreter encounters an import statement, it imports the
module if the module is present in the search path. A search path is a list of
directories that the interpreter searches before importing a module. For example,
to import the module support.py, you need to put the following command at the
top of the script-
import support
support.print_func("Zara")

Output: Hello : Zara

A module is loaded only once, regardless of the number of times it is


imported. This prevents the module execution from happening repeatedly, if
multiple imports occur.

Variables in Module
The module can contain functions, as already described, but also variables
of all types (arrays, dictionaries, objects etc):
Example
Save this code in the file mymodule.py
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}

Example
Import the module named mymodule, and access the person1 dictionary:
31

import mymodule
a = mymodule.person1["age"]
print(a)

Output: 36

Naming a Module
You can name the module file whatever you like, but it must have the file
extension .py

Re-naming a Module
You can create an alias when you import a module, by using the as
keyword:
Example
Create an alias for mymodule called mx:
import mymodule as mx
a = mx.person1["age"]
print(a)

Output: 36

The from...import Statement


Python's from statement lets you import specific attributes from a module
into the current namespace. The from...import has the following syntax-
from modname import name1[, name2[, ... nameN]]
For example, to import the function fibonacci from the module fib, use the
following statement-
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result

>>> from fib import fib


>>> fib(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
This statement does not import the entire module fib into the current
namespace; it just introduces the item fibonacci from the module fib into the
global symbol table of the importing module.

The from...import * Statement:


It is also possible to import all the names from a module into the current
namespace by using the following import statement-
32

from modname import *

This provides an easy way to import all the items from a module into the
current namespace; however, this statement should be used sparingly.

Executing Modules as Scripts


Within a module, the module’s name (as a string) is available as the value
of the global variable __name__. The code in the module will be executed, just
as if you imported it, but with the __name__ set to "__main__".

Add this code at the end of your module-


# Fibonacci numbers module
def fib(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while b < n:
result.append(b)
a, b = b, a+b
return result
if __name__ == "__main__":
f=fib(100)
print(f)
When you run the above code, the following output will be displayed.
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Locating Modules
When you import a module, the Python interpreter searches for the
module in the following sequences-
 The current directory.
 If the module is not found, Python then searches each directory in
the shell variable PYTHONPATH.
 If all else fails, Python checks the default path. On UNIX, this
default path is normally /usr/local/lib/python3/.

The module search path is stored in the system module sys as the sys.path
variable. The sys.path variable contains the current directory, PYTHONPATH,
and the installation-dependent default.

The PYTHONPATH Variable


The PYTHONPATH is an environment variable, consisting of a list of
directories. The syntax of PYTHONPATH is the same as that of the shell
variable PATH.
Here is a typical PYTHONPATH from a Windows system-
set PYTHONPATH=c:\python34\lib;
And here is a typical PYTHONPATH from a UNIX system-
33

set PYTHONPATH=/usr/local/lib/python

Standard modules or Built-in Modules


There are several built-in modules in Python, which you can import
whenever you like.
Example
#Import and use the platform module:
import platform
x = platform.system()
print(x)
output: Windows

The dir( ) Function


The dir() built-in function returns a sorted list of strings containing the
names defined by a module.
The list contains the names of all the modules, variables and functions
that are defined in a module. Following is a simple example-
# Import built-in module math
import math
content = dir(math)
print (content)
When the above code is executed, it produces the following result-
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan',
'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp',
'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log',
'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh',
'sqrt', 'tan', 'tanh']
Here, the special string variable __name__ is the module's name, and
__file__is the filename from which the module was loaded.

The globals() and locals() Functions


The globals() and locals() functions can be used to return the names in the
global and local namespaces depending on the location from where they are
called.
 If locals() is called from within a function, it will return all the names that
can be accessed locally from that function.
 If globals() is called from within a function, it will return all the names
that can be accessed globally from that function.

The return type of both these functions is dictionary. Therefore, names


can be extracted using the keys() function.

The reload() Function


When a module is imported into a script, the code in the top-level portion
of a module is executed only once.
34

Therefore, if you want to reexecute the top-level code in a module, you


can use the reload() function. The reload() function imports a previously
imported module again.
The syntax of the reload() function is this-
reload(module_name)
Here, module_name is the name of the module you want to reload and not
the string containing the module name. For example, to reload hello module, do
the following-
reload(hello)

Namespaces and Scoping


Variables are names (identifiers) that map to objects. A namespace is a
dictionary of variable names (keys) and their corresponding objects (values).
 A Python statement can access variables in a local namespace and in the
global namespace. If a local and a global variable have the same name,
the local variable shadows the global variable.
 Each function has its own local namespace. Class methods follow the
same scoping rule as ordinary functions.
 Python makes educated guesses on whether variables are local or global.
It assumes that any variable assigned a value in a function is local.
 Therefore, in order to assign a value to a global variable within a function,
you must first use the global statement.
 The statement global VarName tells Python that VarName is a global
variable. Python stops searching the local namespace for the variable.

For example, we define a variable Money in the global namespace.


Within the function Money, we assign Money a value, therefore Python assumes
Money as a local variable.
However, we accessed the value of the local variable Money before
setting it, so an UnboundLocalError is the result. Uncommenting the global
statement fixes the problem.

Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print (Money)
AddMoney()
print (Money)

Packages in Python
A package is a hierarchical file directory structure that defines a single
Python application environment that consists of modules and subpackages and
sub-subpackages, and so on.
35

Consider a file Pots.py available in Phone directory. This file has the
following line of source code-
def Pots():
print ("I'm Pots Phone")
Similarly, we have other two files having different functions with the same
name as above.
They are –
 Phone/Isdn.py file having function Isdn()
 Phone/G3.py file having function G3()
Now, create one more file __init__.py in the Phone directory
 Phone/__init__.py

To make all of your functions available when you have imported Phone,
you need to put explicit import statements in __init__.py as follows-
from Pots import Pots
from Isdn import Isdn
from G3 import G3

After you add these lines to __init__.py, you have all of these classes
available when you import the Phone package.

# Now import your Phone Package.


import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()

When the above code is executed, it produces the following result


I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
In the above example, we have taken example of a single function in each
file, but you can keep multiple functions in your files. You can also define
different Python classes in those files and then you can create your packages out
of those classes.

You might also like