0% found this document useful (0 votes)
243 views

Python (Unit 5)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
243 views

Python (Unit 5)

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

Unit – 5

Definition of Functions
Functions are reusable blocks of code that perform a specific task. They help in organizing code, making it
more readable, and reducing redundancy.

Syntax:
def function_name(parameters):
"""Docstring explaining the function."""
# function body
return value
Example:

def greet(name):
"""This function greets the person passed as parameter."""
print(f"Hello, {name}!")
greet("Alice")
Modules

• There some standard functionalities in python that are written in particular module.

For using those functionalities, it is essential to import the corresponding module first.

• Python module is basically a file containing some functions and statements.

• When Python file is executed directly it is considered as main module.

• The main module is recognized as __main__ and provide the basis for a complete Python

program.

• The main module can import any number of other modules. But main module cannot be

imported into some other module.

• For example : There are various functionalities available under the module math. For instance, if you
want to find out the square root of some number then you need to import module math first and then
use the sqrt function.

• Following screenshot illustrates this idea :

• Basically modules in python are .py files in which set of functions are written.

• Modules are imported using import command.

1. The from... import Statement

• There are many variables and functions present in the module. We can use them by using the import
statement.

• When we simply use import statement, then we can use any variable or function present within that
module.

• When we use from...import statement, then we can use only selected variables or functions present
within that module.
For example -

from math import sqrt

print("Square root(25) = ",sqrt(25))


Output

• If we want to use some different name for the standard function present in the module, then we can
use as keyword. Following code illustrates this -

moduleProg1.py

from math import sqrt as my_sq_root

print("Square root(25)= "my_sq_root(25))

Output

Square root(25) = 5.0

>>>

2. Creating a Module

• We can create our own module. Every Python program is a module. That means every file that we
save using .py extension is a module.

• Following are the steps that illustrates how to create a module –

Step 1: Create a file having extension .py. Here we have created a file PrintMsg.py. In this file, the
function fun is defined.

PrintMsg.py

def fun(usr):

print("Welcome ", usr)

Step 2: Now open the python shell and import the above module and then call the functionality present
in that module.

Output
Step 3: We can also call the above created PrintMsg module in some another file. For that purpose,
open some another file and write the code in it as follows –

Test.py
import PrintMsg #importing the user defined module
PrintMsg.fun("Rupali") #calling the function present in that module

Step 4: Now run the test.py program and you will get the output as follows –

Example 5.4.1 Write a module for displaying the Fibonacci series.

Solution:

Step 1:

FibSeries.py

def fib(n): # write Fibonacci series up to n

a, b = 0,1

while b < n:

print(b, end='')

a, b = b, a + b

print()

Step 2: Open the python shell and import the above module and access the functionality within it. The
output will be as follows:
Example- Write a Python program to define a module for swapping the two values. Then write a driver
program that will call the function defined in your swap module.

Solution :

Step 1: Create a module in a file and write a function for swapping the two values. The code is as
follows -

swapProg.py
def Swap(a,b):
tempr a = b
b = temp
print("After Swapping")
print(a)
print(b)

Save and Run the above code.

Step 2: Now create a driver program that will invoke the swap function created in above module.

Test.py

import swapProg

print("Swap(10,20)")

swapProg.Swap(10,20)

print("Swap('a','b')")

swapProg. Swap('a','b')

Step 3: Save and run the above code. The output will be as follows –
Modules and Namespace

• Namespace is basically a collection of different names. Different namespaces can time but are
completely isolated.

• If two names(variables) are same and are present in the same scope then it will cause name clash.
To avoid such situation we use the keyword namespace.

• In Python each module has its own namespace. This namespace includes all the names of its
function and variables.

• If we use two functions having same name belonging to two different modules at a time in some other
module then that might create name clash. For instance –

Step 1 : Create first module for addition functionality.

FirstModule.py
def display(a,b):
return a + b

Step 2: Create second module for multiplication functionality.

SecondModule.py
def display(a,b):
return a*b

Step 3: If we call above modules in our driver program for performing both addition and multiplication,
then we get error because of name clash for the function.

Test.py
import FirstModule
import SecondModule
print(display(10,20))
print(display(5,4))

Step 4: To resolve this ambiguity we should call these functionalities using their module names. It is
illustrated as follows -

import FirstModule
import SecondModule
print(FirstModule.display(10,20))
print(SecondModule.display(5,4))

Output

30
20
Packages

• Packages are namespaces which contain multiple packages and modules. They are simply
directories.

• Along with packages and modules the package contains a file named __init_ _.py. In fact to be a
package, there must be a file called __init_ _.py in the folder.

• Packages can be nested to any depth, provided that the corresponding directories contain their own
_init__.py file.

• The arrangement of packages is as shown in Fig.


Errors and Exceptions

Errors are normally referred as bugs in the program. They are almost always the fault of the
programmer. The process of finding and eliminating errors is called debugging.

There are mainly two types of errors :

1. Syntax errors: The python finds the syntax errors when it parses the source program. Once it find
a syntax error, the python will exit the program without running anything. Commonly occurring syntax
errors are :

(i) Putting a keyword at wrong place

(ii) Misspelling the keyword

(iii) Incorrect indentation

(iv) Forgetting the symbols such as comma, brackets, quotes

(v) Empty block

2. Run time errors: If a program is syntactically correct - that is, free of syntax errors – it will be run by
the python interpreter. However, the program may exit unexpectedly during execution if it encounters
a runtime error. The run-time errors are not detected while parsing the source program, but will occur
due to some logical mistake. Examples of runtime error are :

(i) Trying to access the a file which does not exists

(ii) Performing the operation of incompatible type elements

(iii) Using an identifier which is not defined

(iv) Division by zero Such type of errors are handled using exception handling mechanism.

Handling Exceptions

Definition of exception : An exception is an event which occurs during the execution of a program
that interrupts the normal flow of the program.

• In general, when a python script encounters a situation that it cannot cope with, it raises an exception.

• When a python script raises an exception, it must either handle the exception immediately otherwise
it terminates and quits.

• The exception handling mechanism using the try...except...else blocks.

• The suspicious code is placed in try block.

• After try block place the except block which handles the exception elegantly.

• If there is no exception then the else block statements get executed.


Syntax of try...except...else

try:

write the suspicious code here

except Exception 1:

If Exception 1 occurs then execute this code

except Exception 2:

If Exception 2 occurs then execute this code

else:

If there is no exception then execute this code.

Example

Suppose programmer wants some integer value and some character value is entered then python will
raise error. This scenario can be illustrated by following screenshot

Such situation can be gracefully handled using exception handling mechanism as follows:

Step 1: Create a python script as follows:


Step 2: Now run the above code for both valid and invalid inputs.

Output(Run1: Execution of except block)

• A single try can have multiple except statements. We can specify standard exception names for
handling specific type of exception.

For Example

Write a python program to perform division of two numbers. Raise the exception if the wrong input(other
than integer) is entered by the user. Also raise an exception when divide by zero occurs,

Solution :

try:
a = int(input("Enter value of a: "))
b = int(input("Enter value of b: "))
c = a/b
except ValueError:
print("You have entered wrong data")
except Zero DivisionError:
print("Divide by Zero Error!!!")
else:
print("The result: ",c)
Output(Run1) Output(Run2) Output(Run3)
Standard Exceptions in Python

You might also like