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

Python Unit 2

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

Python Unit 2

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

UNIT-II

Functions:

 A function is a block of organized, reusable code that is used to perform a single, related
action.
 Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable.

Advantage of Functions in Python


There are the following advantages of Python functions.

 Using functions, we can avoid rewriting the same logic/code again and again.
 We can call Python functions multiple times in a program and anywhere in a program.
 We can track a large Python program easily when it is divided into multiple functions.
 Reusability is the main achievement of Python functions.

There are two types of Functions.

1) Pre-defined (Built-in) Functions


2) User defined Functions

Pre-defined Functions:

 Pre-defined functions are defined (created) by language developers. These functions having
their own purpose which can’t modifiable.

Ex: print(), input(), type() etc.,

User defined Functions:

 User defined functions can be defined by the users.


 By using “def” keyword we can able to create a function.

Defining 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” and 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.

Dept. Of CSE-CBIT Page 1


 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]

EX:1)

def evenOdd(x):
if (x % 2 == 0):
print "even"
else:
print "odd"
evenOdd(3)

Output: odd

Calling a Function:
 After the function is created, we can call it from another function.
 A function must be defined before the function call; otherwise, the Python interpreter gives
an error.
 To call the function, use the function name followed by the parentheses.

Consider the following example of a simple example that prints the message "Hello World".

Ex:1)

def hello_world():
print("hello world")
# function calling
hello_world()

Output: hello world

Dept. Of CSE-CBIT Page 2


 We can call the function as argument to some other functions.

Ex:2)
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())

Output: 30

return statement :

 The return statement is used at the end of the function

 return statement can returns the result of the function

 It terminates the function execution and transfers the result where the function is called.

 The return statement cannot be used outside of the function.

Syntax:

return [expression_list]

EX:

# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print statement
print("The sum is:",sum())

Output: The sum is: 30

Dept. Of CSE-CBIT Page 3


returning multiple values from a function:

In Python, we can return multiple values from a function. Following are different ways

1) Using Tuple:
By using tuples we can return multiple values from a function.
Ex:

# A Python program to return multiple


# values from a method using tuple

# This function returns a tuple


def fun():
str = "hello"
x = 20
return (str, x);

print(fun())

output: ('hello', 20)

2) Using List:
By using list we can return multiple values from a function.
Ex:

# A Python program to return multiple


# values from a method using list

# This function returns a list


def fun():
str = "List"
x = 20
return [str, x];

print(fun())

output: [‘List’, 20]

3) Using Dictionary:
By using dictionary also we can able to return multiple values.

Dept. Of CSE-CBIT Page 4


Ex:
# A Python program to return multiple
# values from a method using dictionary

# This function returns a dictionary


def fun():
d = dict{};
d['str'] = "dictionary"
d['x'] = 20
return d

print(fun())

output: {'x': 20, 'str': 'dictionary'}

Recursive Function:

 The word recursion comes from the Latin word recurrere,


 Definition of recursion is the process of defining something in terms of itself.
 In Python, we know that a function can call other functions. It is even possible for the function
to call itself. These types of functions are termed as recursive functions.
 Following is an example of a recursive function to find the factorial of an integer.

def factorial(x):
"""This is a recursive function to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

output:

The factorial of 3 is 6

In the above example, factorial() is a recursive function as it calls itself.

When we call this function with a positive integer, it will recursively call itself by decreasing the
number.

Dept. Of CSE-CBIT Page 5


Each function multiplies the number with the factorial of the number below it until it is equal to one.
This recursive call can be explained in the following steps.

factorial(3) # 1st call with 3

3 * factorial(2) # 2nd call with 2

3 * 2 * factorial(1) # 3rd call with 1

3*2*1 # return from 3rd call as number=1

3*2 # return from 2nd call

6 # return from 1st call

Let's look at an image that shows a step-by-step process of what is going on:

Our recursion ends when the number reduces to 1. This is called the base condition.

Dept. Of CSE-CBIT Page 6


Advantages of Recursion
1. Recursive functions make the code look clean and elegant.

2. A complex task can be broken down into simpler sub-problems using recursion.

3. Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.

2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.

3. Recursive functions are hard to debug.

Functions are First Class Objects:

Object:

 An object is a software bundle of variables and related methods.


 First class objects in a language are handled uniformly throughout. They may be stored in
data structures, passed as arguments, or used in control structures.
 A programming language is said to support first-class functions if it treats functions as first-
class objects.

Properties of first class functions:


 A function is an instance of the Object type.
 You can store the function in a variable.
 You can pass the function as a parameter to another function.
 You can return the function from a function.
 You can store them in data structures such as hash tables, lists, …

In Python, functions behave like any other object, such as an int or a list. That means that you can use
functions as arguments to other functions, store functions as dictionary values, or return a function
from another function. This leads to many powerful ways to use functions.

Dept. Of CSE-CBIT Page 7


Ex: def square(x):
"""Square of x."""
return x*x

def cube(x):
"""Cube of x."""
return x*x*x

# create a dictionary of functions

funcs = {
'square': square,
'cube': cube,
}

x=2

print square(x)
print cube(x)

for func in sorted(funcs):


print func, funcs[func](x)

4
8
cube 8
square 4

In the example below, we are assigning function to a variable. This assignment doesn’t call the
function. It takes the function object referenced by shout and creates a second name pointing to it,
yell.

Dept. Of CSE-CBIT Page 8


Ex:
# Python program to illustrate functions yell = shout
# can be treated as objects print (yell('Hello'))
def shout(text):
return text.upper()
OUTPUT: HELLO
print (shout('Hello')) HELLO

Formal and Actual arguments:


Formal Arguments (Formal Parameters):

 The formal arguments are the parameters/arguments in a function declaration.

<def keyword> <method name> (formal parameters):


# set of statements to be executed

The method name is to identify the method. The “def” keyword is a statement for defining a function
in Python. The formal parameter is enclosed in parenthesis. The list consists variable names and data
types of all the necessary values for the method. Each formal parameter is separated by a comma.
When method is not accepting any input values, then the method should have an empty set of
parenthesis after method name. e.g. addition ().

def addition(x, y) :

addition = x+y
print(f”{addition}”)

addition(2, 3)
addition(4, 5)

Formal parameters are the variables defined by the function that receives values when the
function is called. According to the above program, the variable x and y are known as formal
parameters. These variables are only accessible within the method. After printing the addition of two
numbers, the control is returned back to the main program.

Dept. Of CSE-CBIT Page 9


Actual Arguments (Actual Parameters):

 The arguments that are passed in a function call are called actual arguments.

Ex:

def addition(x, y) :

addition = x+y
print(f”{addition}”)

addition(2, 3)
addition(4, 5)

According to the above Python program, there is a function named addition. In the main function, the
value 2 and 3 are passed to the function addition. This value 2 and 3 are the actual parameters. Those
values are passed to the method addition, and the sum of two numbers will display on the screen.
Again, new two integer values are passed to the addition method. Now the actual parameters are 4
and 5. The summation of 4 and 5 will display on the screen.

Positional Arguments:
An argument is a variable, value or object passed to a function or method as input.
Positional arguments are arguments that can be called by their position in the function definition.
During function call, values passed through arguments should be in the order of parameters in the
function definition.

Dept. Of CSE-CBIT Page 10


The first positional argument always needs to be listed first when the function is called. The second
positional argument needs to be listed second and the third positional argument listed third, etc.

Example:

def add(a,b,c):
return (a+b+c)

The above function can be called in the following way:

 During function call, all arguments are given as positional arguments.

 Values passed through arguments are passed to parameters by their position. 10 is assigned
to a,20 is assigned to b and 30 is assigned to c.

print (add(10,20,30))
#Output:60

Positional Arguments Specified by an Iterable

Positional arguments can also be passed to functions using an iterable object. Examples of iterable
objects in Python include lists and tuples. The general syntax to use is:

function(*iterable)

Where function is the name of the function and iterable is the name of the iterable proceeded by the
asterisk * character.
An example of using a list to pass positional arguments to the add() function is below. Note the
asterisk * character is included before the term_list argument.

Ex: term_list=[56,89,12]

print(add(*term_list))

output: 157

NOTE: The list or tuple which we are passing as iterable object need to have the same no of values
how many parameters we had passed at the time of function declaration.

Dept. Of CSE-CBIT Page 11


Exceptions

Errors in a Python program:


 Errors are the problems in a program due to which the program will stop the execution.
 The most common reason of an error in a Python program is when a certain statement
is not in accordance with the prescribed usage. Such an error is called a syntax error.
 Syntax errors are discovered by the interpreter when it is translating the source code
into byte code. They indicate that there is something wrong with the structure of the
program.
 Some of the following are the errors can be occured:

Exception Description

IndexError When the wrong index of a list is retrieved.

AttributeError It occurs when an attribute assignment is failed.

ImportError It occurs when an imported module is not found.

KeyError It occurs when the key of the dictionary is not found.

NameError It occurs when the variable is not defined.

MemoryError It occurs when a program run out of memory.

TypeError It occurs when a function and operation is applied in an incorrect type.

 These errors can be solving process can be called as debugging.


 The first step in debugging is to figure out which kind of error you are dealing with.
 If you are dealing syntax errors.

Here are some ways to avoid the most common syntax errors:

1) Make sure you are not using a Python keyword for a variable name.
2) Check that you have a colon at the end of the header of every compound statement, including
for, while, if, and def statements.

Dept. Of CSE-CBIT Page 12


3) Make sure that any strings in the code have matching quotation marks. Make sure that all
quotation marks are straight quotes, not curly quotes.
4) If you have multiline strings with triple quotes (single or double), make sure you have
terminated the string properly. An un-terminated string may cause an invalid token error.
5) An unclosed opening operator—(, {, or [—makes Python continue with the next line as part of
the current statement. Generally, an error occurs almost immediately in the next line.
6) Check for the classic = instead of == inside a conditional.
7) Check the indentation to make sure it lines up the way it is supposed to.

 If you are dealing with logical errors make sure your logic is correct. The following are Logical
Errors:

If the program hangs:


If a program stops and seems to be doing nothing, it is “hanging”. Often that means that it is caught in
an infinite loop or infinite recursion.

• If there is a particular loop that you suspect is the problem, add a print statement immediately
before the loop that says “entering the loop” and another immediately after that says “exiting the
loop”. Run the program. If you get the first message and not the second, you’ve got an infinite loop.
Go to the “Infinite loop” section below.

For example:

while x > 0 and y > 0 :


# do something to x
# do something to y
print('x: ', x)
print('y: ', y)
print("condition: ", (x > 0 and y > 0))

Now when you run the program, you will see three lines of output for each time through the loop.
The last time through the loop, the condition should be False. If the loop keeps going, you will be able
to see the values of x and y, and you might figure out why they are not being updated correctly.

• Most of the time, an infinite recursion will cause the program to run for a while and then produce a
“RuntimeError: Maximum recursion depth exceeded” error. If that happens you are not getting this
error but you suspect there is a problem with a recursive method or function, you can still use the
techniques in the “Infinite recursion” .

• If neither of those steps works, start testing other loops and other recursive functions and methods.

• If that doesn’t work, then it is possible that you don’t understand the flow of execution in your
program. Go to the “Flow of execution”.

Dept. Of CSE-CBIT Page 13


Exceptions:

 An Exception nothing but an error which can cause at run-time of the program.
 Whenever an exception occurs, the program stops the execution, and thus the further code is
not executed.
 When a Python script meets an exception, it must either handle the exception immediately
otherwise it terminates and quits.
 Python provides a way to handle the exception so that the code can be executed without any
interruption. If we do not handle the exception, the interpreter doesn't execute all the code
that exists after the exception.

Python has many built-in exceptions that enable our program to run without interruption and give
the output. These exceptions are given below:

Common Exceptions

Python provides the number of built-in exceptions, but here we are describing the common standard
exceptions. A list of common exceptions that can be thrown from a standard Python program is given
below.

 ZeroDivisionError: Occurs when a number is divided by zero.


 NameError: It occurs when a name is not found. It may be local or global.
 IndentationError: If incorrect indentation is given.
 IOError: It occurs when Input Output operation fails.
 EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

Ex:
a = 10
b=0
c = a/b
print("a/b = %c" %c)

output: Traceback (most recent call last):


File "C:/Users/DCS/Desktop/exceptionex.py", line 3, in <module>
c = a/b
ZeroDivisionError: integer division or modulo by zero

The above program is syntactically correct, but it throwing the error because of unusual input. That
kind of programming may not be suitable for the projects. That's why an exception-handling plays an
essential role in handling these unexpected exceptions.

Dept. Of CSE-CBIT Page 14


Exception Handling:
 Exception Handling is a process to Handle the exceptions i.e., we in python program itself we
will write the code to solve the exceptions.
 For Exception handling python providing us two keywords. Those are 1) try 2) except
 If the Python program contains suspicious code that may throw the exception, we must place
that code in the try block.
 The try block must be followed with the except statement.
 The except statement contains a block of code that will be executed if there is some
exception in the try block.

Syntax:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.

Ex:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("divison of {} and {} is:{}".format(a,b,c))
except:
print("Can't divide with zero")

Dept. Of CSE-CBIT Page 15


output: Enter a:24
Enter b:0
Can't divide with zero
 We can also use the else statement with the try-except statement in which, we can place the code
which will be executed in the scenario if no exception occurs in the try block.

Syntax:

try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

Ex:

try:
a = input("Enter a:")
b = input("Enter b:")
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:

Dept. Of CSE-CBIT Page 16


print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Output: Enter a:56
Enter b:28
a/b = 2
Hi I am else block

Types of exceptions:
In python two types of exceptions are there. Those are :
1) Built-in Exceptions
2) User-defined Exceptions

1) User-defined Exceptions:

These exceptions are defined by the user. According to their error raising chances. For creating user
defined exception we need to create a class and it’s name can be used as Exception.

Ex:
# A python program to create user-defined exception

# class MyError is derived from super class Exception


class MyError(Exception):

# Constructor or Initializer
def __init__(self, value):
self.value = value

# __str__ is to print() the value


def __str__(self):
return(repr(self.value))

try:
raise(MyError(3*2))

# Value of Exception is stored in error


except MyError as error:
print('A New Exception occured: ',error.value)

output: ('A New Exception occured: ', 6)

Dept. Of CSE-CBIT Page 17


2) Built-in Exceptions:

 Built-in Exceptions are those which were already defined by python.


 In Python, all exceptions must be instances of a class that derives from BaseException.
 The built-in exceptions listed below can be generated by the interpreter or built-in functions.
1) Base class Exceptions
2) Concrete exceptions
3) OS exceptions

Base Class Exceptions:

 These exceptions are used mostly as base classes for other exceptions.
 The following are some of the Base Class Exceptions.

a) exception ArithmeticError:
 The base class for those built-in exceptions that are raised for various arithmetic
errors:OverflowError, ZeroDivisionError,FloatingPointError.

b) exception LookupError:
 The base class for the exceptions that are raised when a key or index used on a
mapping or sequence is invalid: IndexError, KeyError.

c) exception BufferError:
 Raised when a buffer related operation cannot be performed.

Concrete exceptions:

 These exceptions are the exceptions that are usually raised when the program execution is
taking place.
 The following are the some of the Concrete Exceptions.

a) exception AttributeError:
 These exceptions Raised when an attribute reference or assignment fails.

Dept. Of CSE-CBIT Page 18


b) exception EOFError:

 These Exceptions raised when the input() function hits an end-of-file condition
(EOF)without reading any data. Mostly these exception can ariase while working with
files.

c) exception ImportError:

 Raised when the import statement has troubles trying to load a module. Also raised
when the “from list” in from ... import has a name that cannot be found.

d) exception NameError:

 Raised when a local or global name is not found. This applies only to unqualified
names. The associated value is an error message that includes the name that could
not be found.

e) exception KeyError:

 Raised when a mapping (dictionary) key is not found in the set of existing keys.

f) exception KeyboardInterrupt:

 Raised when the user hits the interrupt key (normally Control-C or Delete). During
execution, a check for interrupts is made regularly.

OS exceptions:

 These exceptions raised depending on the systemerror code.


 The following exceptions are subclasses of OSError,

a) exception ConnectionError:
 These exceptions can raised for connection-related issues.

b) exception FileNotFoundError:
 Raised when a file or directory is requested but doesn’t exist.

c) exception PermissionError:
 These exceptions raised when trying to run an operation without the adequate access
rights - for example file system permissions.

Dept. Of CSE-CBIT Page 19


d) exception TimeoutError:
 These exceptions raised when a system function timed out at the system level.

The assert statement:


 Assertions are statements that assert or state a fact confidently in your program.
 Assertions are mainly assumptions that a programmer knows always wants to be true and
hence puts them in code so that failure of them doesn’t allow the code to execute further.
 Assert statements are used to debug code and handle errors.
 In python assert keyword tests the condition and return true or not.

 If it is true, the program does nothing and moves to the next line of code. If it's false, the
program stops and throws an error.
 In Python we can use assert statement in two ways as mentioned above.

1) assert statement has a condition and if the condition is not satisfied the program will stop and
give Assertion Error.

Syntax:
assert <condition>

2) assert statement can also have a condition and an optional error message. If the condition is
not satisfied assert stops the program and gives Assertion Error along with the error message.
Syntax:
assert <condition>, <error message>

Dept. Of CSE-CBIT Page 20


EX:1)
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)

mark1 = []
print("Average of mark1:",avg(mark1))
output: Assertion Error

For the above program we passed an empty list mark1 to assert statement, the condition became
false and assert stops the program and give AssertionError.

EX:2)

def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))

output: Average of mark2: 78.0


AssertionError: List is Empty

For the above program We passed a non-empty list mark2 and also an empty list mark1 to the avg()
function and we got output for mark2 list but after that we got an error AssertionError: List is Empty.
The assert condition was satisfied by the mark2 list and program to continue to run. However, mark1
doesn't satisfy the condition and gives an AssertionError.

User defined exception:


Users can define custom exceptions by creating a new class. This exception class has to be derived,
either directly or indirectly, from the built-in Exception class.

User-defined exception class can implement everything a normal class can do, but we generally make
them simple and concise. Most implementations declare a custom base class and derive others
exception classes from this base class.

Dept. Of CSE-CBIT Page 21


Ex:

# define Python user-defined exceptions


class Error(Exception):
"""Base class for other exceptions"""
pass

class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass

class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass

# you need to guess this number


number = 10

# user guesses a number until he/she gets it right


while True:
try:
i_num = int(input("Enter a number: "))
if i_num < number:
raise ValueTooSmallError
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()

print("Congratulations! You guessed it correctly.")

output: Enter a number: 2


This value is too small, try again!
()
Enter a number: 10
Congratulations! You guessed it correctly.

Dept. Of CSE-CBIT Page 22


In the above program We have defined a base class called Error. The other two exceptions
(ValueTooSmallError and ValueTooLargeError) that are actually raised by our program are derived

from this class. This is the standard way to define user-defined exceptions in Python programming,
but you are not limited to this way only.

The except Block:


 The except statement contains a block of code that will be executed if there is some
exception in the try block.

Syntax:
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.

Ex:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("divison of {} and {} is:{}".format(a,b,c))
except:
print("Can't divide with zero")

Dept. Of CSE-CBIT Page 23


output: Enter a:24
Enter b:0
Can't divide with zero
 We can also use the else statement with the try-except statement in which, we can place the code
which will be executed in the scenario if no exception occurs in the try block.

Syntax:

except Exception1:
#block of code

else:
#this code executes if no except block is executed

Dept. Of CSE-CBIT Page 24


Ex:

try:
a = input("Enter a:")
b = input("Enter b:")
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
else:
print("Hi I am else block")
Output: Enter a:56
Enter b:28
a/b = 2
Hi I am else block

Dept. Of CSE-CBIT Page 25

You might also like