Unit 5: Function,
Exception and File Handling
[10]
5.1 Introduction
to Functions
5.2 Defining
and Calling Function
5.3 Passing
Arguments to Functions
5.4 Value-Returning
Functions
5.5 Introduction
to File Input and Output
5.6 Using
Loops to Process Files
5.7 Exception
Handling
Practical Works
• Write program to divide
work in functions.
• Write different variety of
functions: function with arguments, value returning function, function without
arguments.
• Write program to store
output in file.
• Write program to read input
from file.
Write
program to handle different types of exception.
Introduction
to Functions:
A
collection of related assertions that carry out a mathematical, analytical, or
evaluative operation is known as a function. An assortment of proclamations
called Python Capabilities returns the specific errand. Python functions are
necessary for intermediate-level programming and are easy to define. Function
names meet the same standards as variable names do. The objective is to define
a function and group-specific frequently performed actions. Instead of
repeatedly creating the same code block for various input variables, we can
call the function and reuse the code it contains with different variables.
Syntax
- # An example Python Function
- def function_name( parameters ):
- # code block
Defining
and Calling Function:
We
will define a function that returns the argument number's square when called.
- # Example Python Code for User-Defined function
- def square( num ):
- """
- This function computes the square of the number.
- """
- return num**2
- object_ = square(6)
- print( "The square of the given number is: ", object_ )
Output:
The
square of the given number is: 36
Calling
a Function
Calling
a Function To define a function, use the def keyword to give it a name, specify
the arguments it must receive, and organize the code block.
When
the fundamental framework for a function is finished, we can call it from
anywhere in the program. An illustration of how to use the a_function function
can be found below.
- # Example Python Code for calling a function
- # Defining a function
- def a_function( string ):
- "This prints the value of length of string"
- return len(string)
-
- # Calling the function we defined
- print( "Length of the string Functions is: ", a_function( "Functions" ) )
- print( "Length of the string Python is: ", a_function( "Python" ) )
Output:
Length
of the string Functions is: 9
Length
of the string Python is: 6
Passing
Arguments to Functions/Value-Returning Functions:
Be it
any programming language, Arguments and Parameters are the two words that cause
a lot of confusion to programmers. Sometimes, these two words are used
interchangeably, but actually, they have two different yet similar meanings.
This tutorial explains the differences between these two words and dives deep
into the concepts with examples.
Both
arguments and parameters are variables/ constants passed into a function. The
difference is that:
- Arguments are the variables passed to the function in
the function call.
- Parameters are the variables used in the function
definition.
- The number of arguments and parameters should always be
equal except for the variable length argument list.
Example:
- def add_func(a,b):
- sum = a + b
- return sum
- num1 = int(input("Enter the value of the first number: "))
- num2 = int(input("Enter the value of the second number: "))
- print("Sum of two numbers: ",add_func(num1, num2))
Output:
Enter
the value of the first number: 5
Enter
the value of the second number: 2
Sum
of two numbers: 7
Points
to grasp from the Example:
- (num1, num2) are in the function call, and (a, b) are in
the function definition.
- (num1, num2) are arguments and (a, b) are parameters.
Mechanism:
Observe
that in the above example, num1 and num2 are the values in the function call
with which we called the function. When the function is invoked, a and b are
replaced with num1 and num2, the operation is performed on the arguments, and
the result is returned.
Functions
are written to avoid writing frequently used logic again and again. To write a
general logic, we use some variables, which are parameters. They belong to the
function definition. When we need the function while writing our program, we
need to apply the function logic on the variables we used in our program,
called the arguments. We then call the function with the arguments.
Introduction
to File Input and Output:
The
file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information. We can access the stored information (non-volatile) after the
program termination.
In
Python, files are treated in two modes as text or binary. The file may be in
the text or binary format, and each line of a file is ended with the special
character like a comma (,) or a newline character. Python executes the code
line by line. So, it works in one line and then asks the interpreter to start
the new line again. This is a continuous process in Python.
Opening
a file
A
file operation starts with the file opening. At first, open the File then
Python will start the operation. File opening is done with the open() function
in Python. This function will accepts two arguments, file name and access mode
in which the file is accessed. When we use the open() function, that time we
must be specified the mode for which the File is opening. The function returns
a file object which can be used to perform various operations like reading,
writing, etc.
Syntax:
The
syntax for opening a file in Python is given below -
- file object = open(<file-name>, <access-mode>, <buffering>)
The
close() Method
The
close method used to terminate the program. Once all the operations are done on
the file, we must close it through our Python script using the close() method.
Any unwritten information gets destroyed once the close() method is called on a
file object.
We
can perform any operation on the file externally using the file system which is
the currently opened in Python; hence it is good practice to close the file
once all the operations are done. Earlier use of the close() method can cause
the of destroyed some information that you want to write in your File.
The
syntax to use the close() method is given below.
Syntax
The
syntax for closing a file in Python is given below -
- fileobject.close()
Consider
the following example.
Program
code for Closing Method:
Here
we write the program code for the closing method in Python. The code is given
below -
- # opens the file file.txt in read mode
- fileptr = open("file.txt","r")
-
- if fileptr:
- print("The existing file is opened successfully in Python")
-
- #closes the opened file
- fileptr.close()
Using Loops
to Process Files:
Using
loops to process files in Python is a common technique for tasks such as
reading data, modifying content, or analyzing text. Below are some examples and
tips for working with files using loops in Python.
Basic File
Reading with a Loop:
#
Reading a file line by line
file_path
= "example.txt"
with
open(file_path, "r") as file:
for line in file:
# Process each line
print(line.strip())
Reading
Files in Chunks:
chunk_size
= 1024 # 1 KB
with
open("large_file.txt", "r") as file:
while chunk := file.read(chunk_size):
# Process each chunk
print(chunk)
Processing
Multiple Files in a Directory:
import
os
directory
= "data_files"
for
filename in os.listdir(directory):
file_path = os.path.join(directory,
filename)
if os.path.isfile(file_path):
with open(file_path, "r") as
file:
print(f"Processing
{filename}:")
for line in file:
# Process each line of the file
print(line.strip())
Writing
Processed Data to a New File:
input_file
= "input.txt"
output_file
= "output.txt"
with
open(input_file, "r") as infile, open(output_file, "w") as
outfile:
for line in infile:
# Example: Convert text to uppercase
before writing
outfile.write(line.upper())
Using Loops
to Search for Specific Content:
search_term
= "error"
with
open("log.txt", "r") as file:
for line_number, line in enumerate(file,
start=1):
if search_term in line:
print(f"Found '{search_term}'
on line {line_number}: {line.strip()}")
Exception
Handling:
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.
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.
Code
# 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
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.
No comments:
Post a Comment