PPFD 2
PPFD 2
(303105257)
Anand Jawdekar
Functions
Unit-2
Functions :
Defining and using functions, including the use of arguments and return values
OOPS Concepts :
Object, class, abstraction, encapsulation, polymorphism, Inheritence.
Exceptions and File handling:
Handling exceptions and working with files
Defining and using functions
A Python function is a block of organized, reusable code that is used to perform a
single, related action. Functions provide better modularity for your application and a
high degree of code reusing.
User-defined functions
3 In addition to the built-in functions and functions in the built-in modules, you can also
create your own functions. These functions are called user-defined functions.
Defining a Python Function
You can define custom functions to provide the required functionality. Here are simple rules to define
a function in Python −
Function blocks begin with the keyword def 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.
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 to Define a Python Function
def function_name( parameters ):
"function_docstring"
function_suite return
[expression]
By default, parameters have a positional behavior and you need to inform them in the same order
that they were defined.
Once the function is defined, you can execute it by calling it from another function or directly from
the Python prompt.
Example to Define a Python Function
The following example shows how to define a function greetings(). The bracket is empty so there
aren't any parameters. Here, the first line is a docstring and the function block ends with return
statement.
def greetings():
"This is docstring of greetings function"
print ("Hello World")
return
When this function is called, Hello world message will be printed.
Calling a Python Function
Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code. Once the basic structure of a function is finalized, you can
call it by using the function name itself. If the function requires any parameters, they should be
passed within parentheses. If the function doesn't require any parameters, the parentheses should
be left empty.
Example to Call a Python Function
# Function definition is here
def printme( str ):
"This prints a passed string into this function“
print (str)
return; # Now you can call the function
printme("I'm first call to user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following output −
I'm first call to user defined function! Again second call to the same function
Pass by Reference vs Value
In programming languages like C and C++, there are two main ways to pass variables to a function,
which are Call by Value and Call by Reference (also known as pass by reference and pass by value).
However, the way we pass variables to functions in Python differs from others.
call by value − When a variable is passed to a function while calling, the value of actual arguments is
copied to the variables representing the formal arguments. Thus, any changes in formal arguments
does not get reflected in the actual argument. This way of passing variable is known as call by value.
call by reference − In this way of passing variable, a reference to the object in memory is passed.
Both the formal arguments and the actual arguments (variables in the calling code) refer to the same
object. Hence, any changes in formal arguments does get reflected in the actual argument.
Python uses pass by reference mechanism. As variable in Python is a label or reference to the
object in the memory, both the variables used as actual argument as well as formal arguments
really refer to the same object in the memory. We can verify this fact by checking the id() of the
passed variable before and after passing.
Cont..
def testfunction(arg):
print ("ID inside the function:", id(arg))
var = "Hello" print ("ID before passing:", id(var))
testfunction(var)
If the above code is executed, the id() before passing and inside the function will be displayed.
ID before passing: 1996838294128 ID
inside the function: 1996838294128
Types of Python Function Arguments
Based on how the arguments are declared while defining a Python function, they
are classified into the following categories −
Default arguments
Keyword arguments
Required arguments
Variable-length arguments
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the function call for
that argument. The following example illustrates Default arguments to write functions in Python.
# Python code to demonstrate the use of default arguments
# defining a function
def function( n1, n2 = 20 ):
print("number 1 is: ", n1)
print("number 2 is: ", n2)
# Calling the function and passing only one argument
print( "Passing only one argument" )
function(30)
# Now giving two arguments to the function
print( "Passing two arguments" )
function(50,30)
Output:
Passing only one argument number 1 is: 30 number 2 is: 20
Passing two arguments number 1 is: 50 number 2 is: 30
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller does not need to
remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname=‘Hello', lastname='Pyhton’)
Output:
Hello Python
Positional Arguments
We used the Position argument during the function call so that the first argument (or value) is
assigned to name and the second argument (or value) is assigned to age. By changing the position, or
if you forget the order of the positions, the values can be used in the wrong places, as shown in the
Case-2 example below, where 27 is assigned to the name and Suraj is assigned to the age.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because
# argument is given in order
print("Case-1:")
nameAge("Suraj", 27)
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")
Calling Function With Keyword Arguments
Output:
Case-1:
Hi, I am Suraj
My age is 27
Case-2:
Hi, I am 27
My age is Suraj
Arbitrary Keyword Arguments
You may want to define a function that is able to accept arbitrary or variable number of arguments.
Moreover, the arbitrary number of arguments might be positional or keyword arguments.
An argument prefixed with a single asterisk * for arbitrary positional arguments.
An argument prefixed with two asterisks ** for arbitrary keyword arguments.
# sum of numbers
def add(*args):
s=0
for x in args:
s=s+x
return s
result = add(10,20,30,40)
print (result)
result = add(1,2,3)
print (result)
Output: 100 6
Example Arbitrary Keyword Arguments (**kwargs)
def addr(**kwargs):
for k,v in kwargs.items():
print ("{}:{}".format(k,v))
class Base2:
<class-suite>
.
.
.
class BaseN:
<class-suite>
# instance of child
c = Child()
# child calls overridden method
c.myMethod()
Output: Calling child method
Data abstraction in python
Abstraction is an important aspect of object-oriented programming. In python, we
can also perform data hiding by adding the double underscore (___) as a prefix to
the attribute which is to be hidden. After this, the attribute will not be visible
outside of the class through the object.
Example
class Employee:
__count = 0;
def __init__(self):
Employee.__count = Employee.__count+1
def display(self):
print("The number of employees",Employee.__count)
emp = Employee()
emp2 = Employee()
try:
print(emp.__count)
finally:
emp.display()
Output:
The number of employees 2 AttributeError: 'Employee' object has no attribute '__count'
Abstraction in Python
Abstraction is used to hide the internal functionality of the function from the users.
The users only interact with the basic implementation of the function, but inner
working is hidden. User is familiar with that "what function does" but they don't
know "how it does."
In simple words, we all use the smartphone and very much familiar with its
functions such as camera, voice-recorder, call-dialing, etc., but we don't know how
these operations are happening in the background. Let's take another example -
When we use the TV remote to increase the volume. We don't know how pressing a
key increases the volume of the TV. We only know to press the "+" button to
increase the volume.
Why Abstraction is Important?
In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the complexity.
It also enhances the application efficiency.
Abstraction classes in Python
A class that consists of one or more abstract method is called the abstract class. Abstract methods do
not contain their implementation. Abstract class can be inherited by the subclass and abstract
method gets its definition in the subclass. Abstraction classes are meant to be the blueprint of the
other class. An abstract class can be useful when we are designing large functions. An abstract class
is also helpful to provide the standard interface for different implementations of components. Python
provides the abc module to use the abstraction in the Python program. Let's see the following
syntax.
from abc import ABC
class ClassName(ABC):
We import the ABC class from the abc module.
Working of the Abstract Classes
Unlike the other high-level language, Python doesn't provide the abstract class itself. We need to
import the abc module, which provides the base for defining Abstract Base classes (ABC). The ABC
works by decorating methods of the base class as abstract. It registers concrete classes as the
implementation of the abstract base. We use the @abstractmethod decorator to define an abstract
method or if we don't provide the definition to the method, it automatically becomes the abstract
method. Let's understand the following example.
Example -
# Python program demonstrate
# abstract base class work
from abc import ABC, abstractmethod
class Car(ABC):
def mileage(self):
pass
class Tesla(Car):
def mileage(self):
print("The mileage is 30kmph")
class Suzuki(Car):
def mileage(self):
print("The mileage is 25kmph ")
class Duster(Car):
def mileage(self):
print("The mileage is 24kmph ")
class Renault(Car):
def mileage(self):
print("The mileage is 27kmph ")
Example
# Driver code
t= Tesla ()
t.mileage()
r = Renault()
r.mileage()
s = Suzuki()
s.mileage()
d = Duster()
d.mileage()
The mileage is 30kmph The mileage is 27kmph The mileage is 25kmph The mileage is 24kmph
Python Exceptions
An exception in Python is an incident that happens while executing a program that causes the regular
course of the program's commands to be disrupted. When a Python code comes across a condition it
can't handle, it raises an exception. An object in Python that describes an error is called an exception.
When a Python code throws an exception, it has two options: handle the exception immediately or
stop and quit.
Exceptions versus Syntax Errors
When the interpreter identifies a statement that has an error, syntax errors occur.
Example
#Python code after removing the syntax error
string = "Python Exceptions"
for s in string:
if (s != o:
print( s )
Output:
if (s != o: ^ SyntaxError: invalid syntax
The arrow in the output shows where the interpreter encountered a syntactic error. There was one
unclosed bracket in this case. Close it and rerun the program:
#Python code after removing the syntax error
string = "Python Exceptions"
for s in string:
if (s != o):
print( s )
Example
Output:
2 string = "Python Exceptions"
4 for s in string: ----> 5 if (s != o):
6 print( s ) NameError: name 'o' is not defined
We encountered an exception error after executing this code. When syntactically valid Python code
produces an error, this is the kind of error that arises. The output's last line specified the name of the
exception error code encountered. Instead of displaying just "exception error", Python displays
information about the sort of exception error that occurred. It was a NameError in this situation.
Python includes several built-in exceptions. However, Python offers the facility to construct custom
exceptions.
Try and Except Statement - Catching Exceptions
In Python, we catch exceptions and handle them using try and except code blocks. The try clause
contains the code that can raise an exception, while the except clause contains the code lines that
handle the exception. Let's see if we can access the index from the array, which is more than the
array's length, and handle the resulting exception.
Example
# Python code to catch an exception and handle it using try and except code blocks
a = ["Python", "Exceptions", "try and except"]
try:
#looping through the elements of the array a, choosing a range that goes beyond the length of the
array
for i in range( 4 ):
print( "The index and element from the array is", i, a[i] )
#if an error occurs in the try block, then except block will be executed by the Python interpreter
except:
print ("Index out of range")
Output:
The index and element from the array is 0
Python The index and element from the array is 1 Exceptions
The index and element from the array is 2 try and except
Index out of range
Explanation of code
The code blocks that potentially produce an error are inserted inside the try clause in the preceding
example. The value of i greater than 2 attempts to access the list's item beyond its length, which is
not present, resulting in an exception. The except clause then catches this exception and executes
code without stopping it.
How to Raise an Exception
If a condition does not meet our criteria but is correct according to the Python interpreter, we can
intentionally raise an exception using the raise keyword. We can use a customized exception in
conjunction with the statement.
If we wish to use raise to generate an exception when a given condition happens, we may do so as
follows:
#Python code to show how to raise an exception in Python
num = [3, 4, 5, 7]
if len(num) > 3:
raise Exception( f"Length of the given list must be less than or equal to 3 but is {len(num)}" )
Output:
1 num = [3, 4, 5, 7] 2 if len(num) > 3: ----> 3 raise Exception( f"Length of the given list must be less
than or equal to 3 but is {len(num)}" ) Exception: Length of the given list must be less than or equal
to 3 but is 4
Assertions in Python
When we're finished verifying the program, an assertion is a consistency test that we can switch on
or off. The simplest way to understand an assertion is to compare it with an if-then condition. An
exception is thrown if the outcome is false when an expression is evaluated.
Assertions are made via the assert statement, which was added in Python 1.5 as the latest keyword.
Assertions are commonly used at the beginning of a function to inspect for valid input and at the end
of calling the function to inspect for valid output.
The assert Statement
Python examines the adjacent expression, preferably true when it finds an assert statement. Python
throws an AssertionError exception if the result of the expression is false.
The syntax for the assert clause is −
assert Expressions[, Argument]
Example
#Python program to show how to use assert keyword
# defining a function
def square_root( Number ):
assert ( Number < 0), "Give a positive integer"
return Number**(1/2)
rb
2 Opens a file for reading only in binary format. The file pointer is placed at the beginning of the
file. This is the default mode.
3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+
4 Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
w
5 Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
Example
# Opening a file in read mode
file = open("example.txt", "r")
Hello!!!
Welcome to Parul University!!!
Example: Using readline() method
In here, we are using the readline() method to read one line at a time, making it memory efficient for
reading large files line by line −
Hello!!!
Welcome to Parul University!!!
Example: Using readlines() method
Now, we are using the readlines() method to read the entire file and splits it into a list where each
element is a line −
Hello!!!
Welcome to Parul University!!!
Writing to a File in Python
Writing to a file in Python involves opening the file in a mode that allows writing, and then using
various methods to add content to the file.
To write data to a file, use the write() or writelines() methods. When opening a file in write mode
('w'), the file's existing content is erased.
Example: Using the write() method
In this example, we are using the write() method to write the string passed to it to the file. If the file
is opened in 'w' mode, it will overwrite any existing content. If the file is opened in 'a' mode, it will
append the string to the end of the file −
Open Compiler
with open("foo.txt", "w") as file:
file.write("Hello, World!")
print ("Content added Successfully!!")
Output of the above code is as follows −
Open Compiler
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("example.txt", "w") as file:
file.writelines(lines)
print ("Content added Successfully!!")
The result obtained is as follows −
Open Compiler
file = open("example.txt", "w")
file.write("This is an example.")
file.close()
print ("File closed successfully!!")
The output produced is as shown below −
Open Compiler
with open("example.txt", "w") as file:
file.write("This is an example using the with statement.")
print ("File closed successfully!!")
Following is the output of the above code −