PP&DS 2
PP&DS 2
Defining a Function:
• Using functions, we can avoid rewriting the same logic/code again and
again in a program.
• 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.
Creating a Function
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
In the above function it consists of the following components.
Example of a function
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
>>> greet('anand')
Docstrings
Syntax
return [expression_list]
Output:
In the above code, we have defined the function named sum, and it has
a statement c = a+b, which computes the given values, and the result is
returned by the return statement to the caller function.
# Defining function
def sum():
a = 10
b = 20
c = a+b
# calling sum() function in print statement
print(sum())
Output: None
In the above code, we have defined the same function without the return
statement as we can see that the sum() function returned the None object to
the caller function.
Arguments in function
• The arguments are types of information which we can be passed into the
function.
• The arguments are specified in the parentheses.
• We can pass any number of arguments, but they must be separate them
with a comma.
Consider the following example, which contains a function that accepts a string
as the argument.
Example:
Output: Hi Arjun
Example :
Example:
Output:
list inside function = [10, 30, 40, 50, 20, 30]
list outside function = [10, 30, 40, 50, 20, 30]
Example:
#defining the function
def change_string (str):
str = str + " World "
print("printing the string inside function :",str)
string1 = "Hello"
#calling the function
change_string(string1)
print("printing the string outside function :",string1)
Output:
There may be several types of arguments which can be passed at the time
of function call.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
Example :
def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))
Output:
Example :
#The function accepts three arguments and returns the simple interest accordi
ngly
def simple_interest(p,t,r):
return (p*t*r)/100
p = float(input("Enter the principle amount? "))
r = float(input("Enter the rate of interest? "))
t = float(input("Enter the time in years? "))
print("Simple Interest: ",simple_interest(p,r,t))
Output:
Example :
def printme(name,age=36):
print("My name is",name,"and age is",age)
printme(name = "Anand")
Output:
printme(name = "Arjun") #the variable age is not passed into the function howe
ver the default value of age is considered in the function
printme(age = 10,name="Devdut") #the value of age is overwritten here, 10 will
be printed as age
Output:
Variable-length Arguments
Example
def printme(*names):
print("type of passed argument is ",type(names))
print("printing the passed arguments...")
for name in names:
print(name)
printme("Anand","Arjun","Devdut","Baldev")
Output:
Keyword arguments
Example :
#function func is called with the name and message as the keyword arguments
def func(name,message):
print("printing the message with",name,"and ",message)
#name and message is copied with the values John and hello respectively
func(name = "Anand",message="Hello")
Output:
Example :
#The function simple_interest(p, t, r) is called with the keyword arguments the
order of arguments doesn't matter in this case
def simple_interest(p,t,r):
return (p*t*r)/100
print("Simple Interest: ",simple_interest(t=1,r=7.5,p=10000))
Output:
Example :
Output:
Example :
def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
#the first argument is not the keyword argument
func("Arjun",message="Anirudh",name2="Anand")
Output:
Example :
def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
func("Anand",message="hello","Arjun")
Output:
• The scopes of the variables depend upon the location where the variable
is being
• declared. The variable declared in one part of the program may not be
accessible to the other parts.
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope,
whereas the variable defined inside a function is known to have a local scope.
def print_message():
message = "hello !! I am going to print a message." # the variable message is l
ocal to the function itself
print(message)
print_message()
print(message) # this will cause an error since a local variable cannot be accessi
ble here.
Output:
sum=0
def calculate(*args):
sum=0
for arg in args:
sum = sum +arg
print("The sum is",sum)
calculate(10,20,30) #60 will be printed as the sum
print("Value of sum outside the function:",sum) # 0 will be printed Output:
Output:
The sum is 60
Value of sum outside the function: 0
Recursion in Python
We use the factorial itself to define the factorial. Hence, this is a suitable case
to write a recursive function. Let us expand the above definition for the
calculation of the factorial value of 5.
5! = 5 X 4!
5 X4 X 3!
5 X4 X 3 X 2!
5 X4 X 3 X 2 X 1!
5 X4 X 3 X 2 X 1
= 120
Example:
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 = 5
print("The factorial of", num, "is", factorial(num))
Output:
The factorial of 5 is 120
ERRORS IN PYTHON
Errors are the problems in a program due to which the program will stop
the execution.
Two types of Error occurs in python.
1. Syntax errors
2. Logical errors/RunTime Errors (Exceptions)
Syntax Errors:
When the proper syntax is not followed then syntax error is thrown.
Example:
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase a product
if(amount>999)
print("You are eligible to purchase a product")
Output:
File "<ipython-input-4-8d8659ac7476>", line 5
if(amount>2999)
^
SyntaxError: invalid syntax
Python Exception
➢ An exception is an event, which occurs during the execution of a program
that disrupts the normal flow of the program's instructions.
➢ Whenever an exception occurs, the program stops the execution, and
thus the further code is not executed.
➢ An exception is a Python object that represents an error
➢ 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.
Suppose we have two variables a and b, which take the input from the user and
perform the division of these values. What if the user entered the zero as the
denominator? It will interrupt the program execution and through
a ZeroDivision exception.
Example:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")
Output:
Enter a:50
Enter b:0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-11-a104c1c193bd> in <module>
1 a = int(input("Enter a:"))
2 b = int(input("Enter b:"))
----> 3 c = a/b
4 print("a/b = %d" %c)
5
➢ 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, which
contains a block of code that will be executed if there is some exception
in the try block.
Syntax
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
Output:
Enter a:90
Enter b:0
Can't divide with zerodivide 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: to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Example:
try:
a = int(input("Enter a:"))
b = int(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:40
Enter b:0
can't divide by zero
<class 'Exception'>r a:
Example:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:
print("Hi I am else block")
Output:
Enter a:90
Enter b:0
can't divide by zero
division by zer
Example:
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
Output:
File not found
Syntax
try:
#block of code
else:
#block of code
Example:
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
Syntax
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
Raising exceptions
Example: There is a program that requires 2GB memory for execution, and if the
program tries to occupy 2GB of memory, then we can raise an exception to stop
the execution of the program.
Syntax
raise Exception_class,<value>
1. To raise an exception, the raise statement is used. The exception class
name follows it.
2. An exception can be provided with a value that can be given in the
parenthesis.
3. To access the value "as" keyword is used. "e" is used as a reference
variable which stores the value of the exception.
4. We can pass the value to an exception to specify the exception type.
Example:
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
Enter the age:9
The age is not valid
try:
num = int(input("Enter a positive integer: "))
if(num >= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number!")
except ValueError as e:
print(e)
Output:
Enter a positive integer: 50
That is a negative number!
The Assert Statement
The assert statement is used to continue the execute if the given condition
evaluates to True.
Syntax
Output:
x is a positive number.
In the above example, the assert condition, x > 0 evalutes to be True, so it will
continue to execute the next statement without any error.
The assert statement can optionally include an error message string, which gets
displayed along with the AssertionError. Consider the following assert
statement with the error message.
x=0
assert x > 0, 'Only positive numbers are allowed'
print('x is a positive number.')
Output:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-2-76d333a96219> in <module>
1x=0
----> 2 assert x > 0, 'Only positive numbers are allowed'
3 print('x is a positive number.')
def square(x):
assert x>=0, 'Only positive numbers are allowed'
return x*x
n = square(2) # returns 4
n = square(-2) # raise an AssertionError
Output:
User-defined Exception
# Constructor or Initializer
def __init__(self, value):
self.value = value
try:
raise(MyError(3*2))