0% found this document useful (0 votes)
11 views26 pages

PP&DS 2

The document provides an overview of functions in Python, explaining their definition, types (user-defined and built-in), and advantages such as reusability and organization. It details how to create and call functions, the significance of docstrings and return statements, and the various types of arguments (required, keyword, default, and variable-length). Additionally, it covers variable scope, recursion, and error handling, including syntax and runtime errors.

Uploaded by

shatviklakshman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views26 pages

PP&DS 2

The document provides an overview of functions in Python, explaining their definition, types (user-defined and built-in), and advantages such as reusability and organization. It details how to create and call functions, the significance of docstrings and return statements, and the various types of arguments (required, keyword, default, and variable-length). Additionally, it covers variable scope, recursion, and error handling, including syntax and runtime errors.

Uploaded by

shatviklakshman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

FUNCTIONS

Defining a Function:

• A function is a group of related statements that performs a specific task


when it is called.
• Functions help break our program into smaller and modular chunks.
• As our program grows larger and larger, functions make it more
organized and manageable.
• Furthermore, it avoids repetition and makes the code reusable.

There are mainly two types of functions.

• User-define functions - The user-defined functions are those define by


the user to perform the specific task.
• Built-in functions - The built-in functions are those functions that are pre-
defined in Python.

Advantage of Functions in Python

• 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

Python provides the def keyword to define the function.

The syntax of the define function is given below.

Syntax of Function

def function_name(parameters):
"""docstring"""
statement(s)
In the above function it consists of the following components.

• Keyword def that marks the start of the function header.


• A function name which uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function.
They are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the function
does.
• One or more valid python statements that make up the function body.
Statements must have the same indentation level (usually 4 spaces).
• An optional return statement to return a value from the function.

Example of a function

def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")

How to call a function in python?

Once we have defined a function, we can call it from another function. To


call a function we simply type the function name with appropriate parameters.

>>> greet('anand')

Hello, anand. Good morning!


Example:
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
greet('Anand')

Output: Hello, Anand. Good morning!

Docstrings

• The first statement of a function can be an optional. It is briefly used to


explain what a function does.
• Although optional, documentation is a good programming practice.
• In the above example, we have a docstring immediately below the
function header.
• We generally use triple quotes so that docstring can extend up to
multiple lines.
The return statement:
• The return statement is used at the end of the function and 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]

It can contain the expression which gets evaluated and value is


returned to the caller function. If the return statement has no expression or
does not exist itself in the function then it returns the None object.

Example: Creating function with return statement


# 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

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.

Example: Creating function without return statement

# 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:

#defining the function


def fun (name):
print("Hi ",name)
#calling the function
fun("Arjun")

Output: Hi Arjun

Example :

#Python function to calculate the sum of two variables


#defining the function
def sum (a,b):
return a+b;
#taking values from the user
a = 50
b = 40
#printing the sum of a and b
print("Sum = ",sum(a,b))

Output: Sum = 90a


Call by reference in Python

• Call by reference means passing the actual value as an argument in the


function.
• All the functions are called by reference, i.e., all the changes made to the
reference inside the function revert back to the original value referred by
the reference.

Example:

#defining the function


def change_list(list1):
list1.append(20)
list1.append(30)
print("list inside function = ",list1)
#defining the list
list1 = [10,30,40,50]
#calling the function
change_list(list1)
print("list outside function = ",list1)

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:

printing the string inside function : Hello World


printing the string outside function : Hello
Types of arguments

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

• Required arguments are the arguments passed to a function in correct


positional order.
• Here, the number of arguments in the function call should match exactly
with the function definition.
Consider the following example.

Example :

def func(name):
message = "Hi "+name
return message
name = input("Enter the name:")
print(func(name))

Output:

Enter the name: AnAnd


Hi AnAnd

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:

Enter the principle amount: 5000


Enter the rate of interest: 5
Enter the time in years: 3
Simple Interest: 750.0
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.

Example :

def printme(name,age=36):
print("My name is",name,"and age is",age)
printme(name = "Anand")

Output:

My name is Anand and age is 36


Example:
def printme(name,age=22):

print("My name is",name,"and age is",age)

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:

My name is Arjun and age is 22


My name is Devdut and age is 10

Variable-length Arguments

In large projects, sometimes we may not know the number of arguments


to be passed in advance. In such cases, Python provides us the flexibility to offer
the comma-separated values which are internally treated as tuples at the
function call. By using the variable-length arguments, we can pass any number
of arguments.

However, at the function definition, we define the variable-length argument


using the *args (star) as *<variable - name >.

Consider the following example.

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:

Type of passed argument is <class 'tuple'>


printing the passed arguments...
Anand
Arjun
Devdut
Baldev

In the above code, we passed *names as variable-length argument. We


called the function and passed values which are treated as tuple internally. The
tuple is an iterable sequence the same as the list. To print the given values, we
iterated *arg names using for loop.

Keyword arguments

• Keyword arguments are related to the function calls.


• When you use keyword arguments in a function call, the caller identifies
the arguments by the parameter name.
• This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters.

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:

printing the message with Anand and Hello

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:

Simple Interest: 750.0

If we provide the different name of arguments at the time of function call, an


error will be thrown.

Consider the following example.

Example :

#The function simple_interest(p, t, r) is called with the keyword arguments.


def simple_interest(p,t,r):
return (p*t*r)/100
# doesn't find the exact match of the name of the arguments (keywords)
print("Simple Interest: ",simple_interest(time=10,rate=10,principle=1900))

Output:

TypeError: simple_interest() got an unexpected keyword argument 'time'

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:

printing the message with Arjun , Anirudh ,and Anand

Example :
def func(name1,message,name2):
print("printing the message with",name1,",",message,",and",name2)
func("Anand",message="hello","Arjun")

Output:

SyntaxError: positional argument follows keyword argument


Scope of variables

• 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.

Variables are defined with the two types of scopes.

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.

Consider the following example.

Example: Local Variable

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:

hello !! I am going to print a message.


File "/root/PycharmProjects/PythonTest/Test1.py", line 5, in
print(message)
NameError: name 'message' is not defined
Example: Global variables

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

• The term Recursion can be defined as the process of defining something


in terms of itself.
• In simple words, it is a process in which a function which calls itself
directly or indirectly is called Recursion.

The most popular example of recursion is the calculation of the factorial.


Mathematically the factorial is defined as: n! = n * (n-1)!

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

It returns a syntax error message because after if statement a colon: is


missing. We can fix this by writing the correct syntax.
logical Errors/Runtime Errors(Exception) :
A runtime error happens when python understands what you are saying,
but runs into trouble when following your instructions is called exception or
logical error.
Example:
when we divide any number by zero then ZeroDivisionError exception is
raised, or when we import a module that does not exist then ImportError is
raised.
Example 1:
# initialize the amount variable
a = 100
# perform division with 0
b=a/0
print(b)
Output:
ZeroDivisionError Traceback (most recent call last)
<ipython-input-10-9dea001e8f72> in <module>
2 a = 100
3 # perform division with 0
----> 4 b = a / 0
5 print(b)
ZeroDivisionError: division by zero

In the above example the ZeroDivisionError as we are trying to divide a number


by 0.

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.

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.

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


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

The problem without handling exceptions

As we have already discussed, the exception is an abnormal condition that halts


the execution of the program.

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.

Let's see the following example.

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

ZeroDivisionError: division by zero

o The above program is syntactically correct, but it through the error


because of unusual input.
o That kind of programming may not be suitable or recommended for the
projects because these projects are required uninterrupted execution.
o That's why an exception-handling plays an essential role in handling these
unexpected exceptions.
o We can handle these exceptions in the following way.

Exception handling in python

The try-expect statement

➢ 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

Consider the following example.

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

Consider the following program.

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:

The except statement using with exception variable


We can use the exception variable with the except statement. It is used by
using the as keyword. this object will return the cause of the exception.

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

Declaring Multiple Exceptions

Python allows us to declare the multiple exceptions with the except


clause. Declaring multiple exceptions is useful in the cases where a try block
throws multiple exceptions.

Syntax

try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#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

The try...finally block

o Python provides the optional finally statement, which is used with


the try statement.
o It is executed no matter what exception occurs and used to release the
external resource.
o The finally block provides a guarantee of the execution.
o We can use the finally block with the try block in which we can place the
necessary code, which must be executed before the try statement throws
an exception.
o Try: This block will test the excepted error to occur
o Except: Here you can handle the error
o Else: If there is no exception then this block will be executed
o Finally: Finally block always gets executed either exception is
generated or not

The syntax to use the finally block is given below.

Syntax

try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

finally:
# Some code .....(always executed)
Example:

# Python code to illustrate


# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional
# Part as Answer
result = x / y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')

# Look at parameters and note the working of Program


divide(10, 2)
divide(3, 0)
Output:
Yeah ! Your answer is : 5.0
This is always executed
Sorry ! You are dividing by zero
This is always executed

Raising exceptions

An exception can be raised forcefully by using the raise clause in Python.

It is useful in that scenario where we need to raise an exception to stop the


execution of the program.

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.

The syntax to use the raise statement is given below.

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

Example: Raise the exception with message

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.

If the assert condition evaluates to False, then it raises


the AssertionError exception with the specified error message.

Syntax

assert condition [, Error Message]


Example:
x = 10
assert x > 0
print('x is a positive number.')

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.

Example: Assert Statement with 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.')

AssertionError: Only positive numbers are allowed


In the above example, x=0, so the assert condition x > 0 becomes False, and
so it will raise the AssertionError with the specified message 'Only positive
numbers are allowed'. It does not execute print('x is a positive
number.') statement.

Example: Uses the assert statement in the function

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:

AssertionError Traceback (most recent call last)


<ipython-input-11-82ea0a629ecc> in <module>
4
5 n = square(2) # returns 4
----> 6 n = square(-2) # raise an AssertionError
<ipython-input-11-82ea0a629ecc> in square(x)
1 def square(x):
----> 2 assert x>=0, 'Only positive numbers are allowed'
3 return x*x
4
5 n = square(2) # returns 4

AssertionError: Only positive numbers are allowed

Above, square(2) willreturn 4, whereas square(-2) will raise


an AssertionError because we passed -2.

User-defined Exception

• Users may name their own exceptions by creating a new exception


class.
• Exceptions need to be derived from the Exception class, either directly
or indirectly.
• Although not mandatory, most of the exceptions are named as names
that end in “Error” similar to naming of the standard exceptions in
python.
Example:
# 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)

You might also like