Python Unit 2
Python Unit 2
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.
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.
Pre-defined Functions:
Pre-defined functions are defined (created) by language developers. These functions having
their own purpose which can’t modifiable.
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.
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()
Ex:2)
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
Output: 30
return statement :
It terminates the function execution and transfers the result where the function is called.
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())
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:
print(fun())
2) Using List:
By using list we can return multiple values from a function.
Ex:
print(fun())
3) Using Dictionary:
By using dictionary also we can able to return multiple values.
print(fun())
Recursive Function:
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
When we call this function with a positive integer, it will recursively call itself by decreasing the
number.
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.
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.
Object:
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.
def cube(x):
"""Cube of x."""
return x*x*x
funcs = {
'square': square,
'cube': cube,
}
x=2
print square(x)
print cube(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.
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.
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.
Example:
def add(a,b,c):
return (a+b+c)
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 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.
Exception Description
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.
If you are dealing with logical errors make sure your logic is correct. The following are Logical
Errors:
• 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:
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”.
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.
Ex:
a = 10
b=0
c = a/b
print("a/b = %c" %c)
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.
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")
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:
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
# Constructor or Initializer
def __init__(self, value):
self.value = value
try:
raise(MyError(3*2))
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.
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:
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.
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>
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))
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 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.
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
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.
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")
Syntax:
except Exception1:
#block of code
else:
#this code executes if no except block is executed
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