Functions, Exception, Modules and Files
Functions: Difference between a Function and a Method, Defining a Function, Calling a Function, Returning Results from a Function, Returning Multiple Values from a Function, Functions are First Class Objects, Pass by Object Reference, Formal and Actual Arguments, Positional Arguments, Keyword Arguments, Default Arguments, Variable Length Arguments, Local and Global Variables, The Global Keyword, Passing a Group of Elements to a Function, Recursive Functions, Anonymous Functions or Lambdas (Using Lambdas with filter() Function, Using Lambdas with map() Function, Using Lambdas with reduce() Function), Function Decorators, Generators, Structured Programming, Creating our Own Modules in Python, The Special Variable __name__
Exceptions: Errors in a Python Program (Compile-Time Errors, Runtime Errors, Logical Errors),Exceptions, Exception Handling, Types of Exceptions, The Except Block, The assert Statement, UserDefined Exceptions, Logging the Exceptions
20%
Files: Files, Types of Files in Python, Opening a File, Closing a File, Working with Text Files Containing Strings, Knowing Whether a File Exists or Not, Working with Binary Files, The with Statement, Pickle in Python, The seek() and tell() Methods, Random Accessing of Binary Files, Random Accessing of Binary Files using mmap, Zipping and Unzipping Files, Working with Directories, Running Other Programs from Python Program
1. A 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.
Function
Defining a 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 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 code block within every function starts with a colon (:) and is
indented.
The statement return [expression] exits a function,
Maulik Borsaniya - Gardividyapith
2. User Defining Function
• Simple function
def my_function():
print("Hello from a function")
my_function()
• Parameterized Function
Def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
• Return Value
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Maulik Borsaniya - Gardividyapith
8. ABS()
integer = -20
print('Absolute value of -20 is:',abs(integer))
Chr()
print(chr(97))
print(chr(65))
Max & Min
# using max(arg1, arg2, *args)
print('Maximum is:', max(1, 3, 2, 10, 4))
# using min(iterable)
num = [1, 3, 2, 8, 5, 10, 6]
print('Maximum is:', min(num))
Maulik Borsaniya - Gardividyapith
9. Method
• Python has some list methods that you can use
to perform frequency occurring task (related to
list) with ease. For example, if you want to add
element to a list, you can use append() method.
Simple Example
animal = ['cat', 'dog', 'rabbit']
animal.append('pig')
#Updated Animal List
print('Updated animal list: ',
animal)
• Eg-1 Eg-2
numbers = [2.5, 3, 4, -5]
numbersSum = sum(numbers)
print(numbersSum)
Maulik Borsaniya - Gardividyapith
12. Difference Between method and function
Python Method
• Method is called by its name, but it is associated to an object (dependent).
• A method is implicitly passed the object on which it is invoked.
• It may or may not return any data.
• A method can operate on the data (instance variables) that is contained by
the corresponding class
Functions
• Function is block of code that is also called by its name. (independent)
• The function can have different parameters or may not have any at all. If any
data (parameters) are passed, they are passed explicitly.
• It may or may not return any data.
• Function does not deal with Class and its instance concept.
Maulik Borsaniya - Gardividyapith
13. # Basic Python method
class class_name
def method_name () :
......
# method body
#Function Syntex
def function_name ( arg1, arg2, ...) :
......
# function body
......
Maulik Borsaniya - Gardividyapith
14. Lambda
• A lambda function is a small anonymous
function.
• A lambda function can take any number of
arguments, but can only have one expression.
Syntax
• lambda arguments : expression
• Eg.1 x = lambda a : a + 10
print(x(5))
• Eg.2 x = lambda a, b : a * b
print(x(5, 6))
Maulik Borsaniya - Gardividyapith
15. Why Use Lambda Functions?
The power of lambda is better shown when you use them as
an anonymous function inside another function.
Say you have a function definition that takes one argument,
and that argument will be multiplied with an unknown
number.
• Eg.
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
print(mydoubler(10))
Maulik Borsaniya - Gardividyapith
16. Filter With Lambda
• The filter() function in Python takes in a function and a list
as arguments.
• The function is called with all the items in the list and a new
list is returned which contains items for which the function
evaluates to True.
• Here is an example use of filter() function to filter out only
even numbers from a list.
• Eg.1
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Maulik Borsaniya - Gardividyapith
17. Map With Lambda
• The map() function in Python takes in a function and
a list.
• The function is called with all the items in the list and
a new list is returned which contains items returned
by that function for each item.
• Here is an example use of map() function to double
all the items in a list.
• Eg.1
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)
Maulik Borsaniya - Gardividyapith
18. Creating our own module
1) Hello.py
# Define a function
def world():
print("Hello, World!")
2) Main.py
# Import hello module
import hello
# Call function
hello.world()
print(hello.variable)
variable = "Sammy"
Maulik Borsaniya - Gardividyapith
19. Exception Handling
• An exception is an event, which occurs during
the execution of a program that disrupts the
normal flow of the program's instructions. In
general, when a Python script encounters a
situation that it cannot cope with, it raises an
exception. An exception is a Python object
that represents an error.
• When a Python script raises an exception, it
must either handle the exception immediately
otherwise it terminates and quits.(there are
many built in exception is there)Maulik Borsaniya - Gardividyapith
20. Syntax
try:
You do your operations here;
......................
except Exception 1:
If there is Exception 1, then execute this block.
…………………….
except Exception 2:
If there is Exception 2, then execute this block.
......................
else:
If there is no exception then execute this block.
finally :
This would always be executed
Maulik Borsaniya - Gardividyapith
21. • Example
try:
fh = open("asd.txt", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can't find file or read data"
else:
print "Written content in the file successfully"
fh.close()
Finally:
Print “wow Yaar !! You wrotted hainn !”
Maulik Borsaniya - Gardividyapith
22. Exception Handling With Assert Statement
• Syntex : assert
expression, argument,
messag
Eg . assert 2 + 2 == 4
assert 2 + 3 == 3, ’’error is
here’’
Eg.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))
• Python has built-in assert
statement to use assertion
condition in the program.
• assert statement has a
condition or expression which
is supposed to be always true.
• If the condition is
false assert halts the program
and gives an AssertionError.
Maulik Borsaniya - Gardividyapith
23. User Define Exception
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
# our main program
# user guesses a number until
he/she gets it right
# you need to guess this number
number = 10
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.")
Maulik Borsaniya - Gardividyapith
24. • File Handling
The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
• "r" - Read - Default value. Opens a file for reading, error if the file
does not exist
• "a" - Append - Opens a file for appending, creates the file if it does
not exist
• "w" - Write - Opens a file for writing, creates the file if it does not
exist
• "x" - Create - Creates the specified file, returns an error if the file
exists
Maulik Borsaniya - Gardividyapith
25. DemoFile.txt
• Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!
Python file read
f = open("demofile.txt", "r")
print(f.read())
#print(f.readline())
append
f = open("demofile.txt", "a")
f.write("Now the file has one more line!")
Write
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
Maulik Borsaniya - Gardividyapith
26. Remove file
import os
if os.path.exists(“demofile"):
os.remove(“demofile")
else:
print("The file does not exist")
Maulik Borsaniya - Gardividyapith
27. File Positions
• The tell() method tells you the current position within
the file; in other words, the next read or write will
occur at that many bytes from the beginning of the file.
• The seek(offset[, from]) method changes the current
file position. The offset argument indicates the number
of bytes to be moved. The from argument specifies the
reference position from where the bytes are to be
moved.
• If from is set to 0, it means use the beginning of the file
as the reference position and 1 means use the current
position as the reference position and if it is set to 2
then the end of the file would be taken as the
reference position.
Maulik Borsaniya - Gardividyapith
28. • # Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Check current position
position = fo.tell();
print "Current file position : ", position
# Reposition pointer at the beginning once again
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# Close opend file
fo.close()
Maulik Borsaniya - Gardividyapith
29. Sr.No. Modes & Description
1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
2 rb
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.
4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the
file.
5 w
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.
Maulik Borsaniya - Gardividyapith
30. 6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not
exist, creates a new file for writing.
7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If
the file does not exist, creates a new file for reading and writing.
9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in
the append mode. If the file does not exist, it creates a new file for writing.
10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists.
That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists.
The file opens in the append mode. If the file does not exist, it creates a new file for reading and
writing.
12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if
the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
Maulik Borsaniya - Gardividyapith
31. Running Other Programs from Python
Program – Windows python
• import os
• command = "cmd"
• os.system(command)
Maulik Borsaniya - Gardividyapith
32. Python For Loops
• A for loop is used for iterating over a sequence (that is
either a list, a tuple or a string).
• This is less like the for keyword in other programming
language, and works more like an iterator method as found
in other object-orientated programming languages.
• With the for loop we can execute a set of statements, once
for each item in a list, tuple, set etc.
Example
• fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Maulik Borsaniya - Gardividyapith
33. • fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
• for x in range(2, 30, 3):
print(x)
• i = 1
while i < 6:
print(i)
i += 1
Maulik Borsaniya - Gardividyapith