Python Module 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Functions :

Definition: - Function is a group of related statements that perform a specific task.


Functions help to break our program into smaller parts that’s why debugging of program is
very easy.
It avoids repetition and makes code reusability.
Advantages of functions :
→User-defined functions are reusable code blocks; they only need to be written once, then
they can be used multiple times.
→These functions are very useful, from writing common utilities to specific business logic.
→The code is usually well organized, easy to maintain, and developer-friendly.
→A function can have different types of arguments & return value.

Functions can be divided into two types:


- Library functions
- User defined functions.
Library Functions: - The functions which are coming along with Python software
automatically are called built in functions or pre-defined functions.
Ex: id(), type(), input(), print()….

User defined Functions: - The functions which are developed by programmer explicitly
according to business requirements are called user defined functions.
Syntax:
def functionname(parameters):
statements
return

→def is a keyword to start function definition.


→A function name is used to uniquely identify it. Function naming follows the same rules of
identifiers.
→Write the arguments inside the opening and closing parentheses of the function, and end
the declaration with a colon.
→Parameters (arguments) through which we pass values to a function. They are optional.
→return statement to return a value. return is optional.
Ex :
def disp():
print("hi how r u")
print("where r u")

disp() # function calling

Parameters: - Parameters are inputs to the function. If a function contains parameters, then
at the time of calling, compulsory we should provide values otherwise we will get error.
Ex:
def wish(name):
print("Hello",name," Good morning")
wish("satish")
Ex:
def square(number):
print("The square of ",number," is",number*number)
square(6)

return statement: - The return statement is used to exit a function and go back to the place
from where it was called.
return [expressionlist];
This statement can contain expression which gets evaluated and the value is returned.
Example 1:
def addition(x,y):
return a+y
a,b=10,20
sum=addition(a ,b)
print (sum)
Ex:
def big(a,b):
if a>b:
return a
else:
return b
print(big(10,20))
print(big(50,40))
Types of arguments:
def f1(a,b):
-------
-------
f1(10,20)
→a,b are formal arguments whereas 10,20 are actual arguments.
There are 4 types of actual arguments are allowed in Python.
1. Positional arguments.
2. Keyword arguments.
3. Default arguments.
4. Variable length arguments.

Positional arguments: - This is the default method. These are the arguments passed to
function in correct positional order.
Ex:
def cal(a,b):
s=a-b
return s
print(cal(100,10))
print(cal(10,100))

→The number of arguments and position of arguments must be matched. If we change the
order then result may be changed.
→If we change the number of arguments then we will get error.

Keyword Arguments: - The keywords are mentioned during the function call along with
their corresponding values. These keywords are mapped with the function arguments so the
function can easily identify the corresponding values even if the order is not maintained
during the function call.
Using the Keyword Argument, the argument passed in function call is matched with function
definition on the basis of the name of the parameter.

Ex:
def cal(a,b,c):
s=a+b+c
return s
print(cal(c=33,a=23,b=55))

default: - Function arguments can have default values in Python. We can provide a default
value to an argument by using the equal operator.
Ex:
def cal(a=100,b=200,c=300):
s=a+b+c
return s
print(cal(10,44,55))
print(cal())
print(cal(10))
print(cal(10,44))

var-arg: -
→var-arg means variable length argument.
→Sometimes, we don’t know in advance the number of arguments that will be passed into a
function Python allows us to handle this type of situation through function calls with arbitrary
number of arguments.
→In this function, we use “*” before the parameter.

Ex:
def disp(*var):
for i in var:
print("var arg=",i)
disp()
disp(10,20,30)
disp(10,20.3,"satish")
Ex:
def sum(*a):
s=0
for x in a:
s=s+x
return s
print(sum(10,20))
print(sum(10,20,45,66))
print (sum())
Types of variables:
Global variables: - A variable which is declared outside of the function or in global scope is
known as global variable. That means, global variable can be accessed inside or outside of
the function.
Ex:
def wish():
print("Inner:",x)

x=10
wish()
print("Outer:",x)

Local variables: - A variable which is declared inside the function body or in a local scope is
known as local variables. These variables are accessed within the function.
Ex:
def f1():
y=10
print("Inner=",y)
f1()
print("outer=",y)

NameError: name ‘y’ is not defined

global keyword: -
global keyword allows to modify the variable outside of the function.
Rules:
→When we create a variable inside a function, it is local by default.
→ When we define a variable outside a function, it is global by default.
→We use global to read and write a global variable inside a function.
→Use of global keyword outside a function has no effect.
Ex:
def wish():
global x
x=10
print("Inner x:",x)
wish()
print("Outer x:",x)

Recursive functions: -
A function called by itself is known as recursion.
It reduces length of the code and improves readability. We can solve complex problems very
easily.
Ex: Write a program for factorial of a given number
def fact(n):
if n==0:
res=1
else:
res=n*fact(n-1)
return res
print(fact(5))
print(fact(6))

Anonymous functions: - A function without having a name is called anonymous function.


These functions are used for instant use.
Syntax:
lambda input:expression

Ex:
s=lambda n:n*n
print(s(4))
print(s(6))

→Normal functions are defined by using def keyword.


→Anonymous functions are defined by using lambda keyword. That’s why anonymous
functions are also called as lambda functions.

Ex: Sum of two numbers using lambda


s=lambda a,b:a+b
print("sum =",s(10,200))
Generators: -
→Generators are a simple way of creating iterators; all the overhead iterators are
automatically handled by generators.
→ It is the responsible to generate a sequence of values. It is used to generate values using
yield keyword.
Creating generator:
→To define a normal function with yield statement is called generator function.
→Both yield and return will return some values from a function.
→The difference is that the return statement terminates a function entirely, yield statement
pauses the function saving all its states and later continues from there on successive calls.
Difference between generator function and normal function:
→Generator function contains one or more yield statements.
→When called, it returns an object(iterator) but does not start execution immediately.
→Once the function yields, the function is paused and the control is transferred to the caller.
→Local variables and their states are remembered between successive calls.
Ex:
def mygen():
yield 'A'
yield 'B'
yield 'C'

g=mygen()
print(type(g))
print(next(g))
print(next(g))
print(next(g))
#print(next(g)) #StopIteration
Files
As the part of programming requirement, we have to store our data permanently for future
purpose. For this requirement we should go for files.
File is a name location on disk to store related information. It is used to permanently store
data in a non-volatile memory.
File types: -
→In Python, a file is categorized as either text or binary files.
→Text files are structured as a sequence of characters. Each line is terminated with a
special character, called EOL or End Of Line character.
→A binary file is any type of file that is not a text file. Binary files are used to create non-text
files like image or exe files.

In Python, a file operations are:


1. Open a file
2. Read or Write operation
3. Close a file
To open a file:
→To handle data files in python, we need to have a file object. Object can be created by
using open() function or file() function.
→Before performing any operation (like read or write) on the file, first we have to open that
the file. For this we should use Python’s inbuilt function open().
→But at the time of open, we have to specify mode, which represents the purpose of
opening file
Syntax:
file_object = open(filename [, access_mode] [,buffering])
Ex:
f=open("data",'w')
f=open("d:/satish/abc.txt",'a')
→open() requires three arguments to work, first one ( filename ) is the name of the file on
secondary storage media, which can be string constant or a variable. The name can include
the description of path, in case, the file does not reside in the same folder / directory in
which we are working.
→The second parameter (access_mode) describes how file will be used
throughout the program. This is an optional parameter and the default access_mode is
reading.
→The third parameter (buffering) is for specifying how much is read from the file in one read.
The function will return an object of file type using which we will manipulate the file, in our
program. ----→When we work with file(s), a buffer (area in memory where data is temporarily
stored before being written to file), is automatically associated with file when we open the
file. While writing the content in the file, first it goes to buffer and once the buffer is full, data
is written to the file. Also when file is closed, any unsaved data is transferred to file. flush()
function is used to force transfer of data from buffer to file.
Python File modes: -
r: - Open an existing file for read operation. The file pointer is positioned at the beginning of
the file. This is default mode. If the specified file does not exist then we will get
FileNotFoundError.
w: - Open a file for writing only. It creates a new file if it does not exist. If the file is exist then
it overrides the file.
a: - Open a file for appending. The file pointer at the end of the file if the file exists. If the file
does not exist, it creates a new file for writing.
r+: - To read and write data into the file. The previous data in the file will no be deleted. The
file pointer is placed at the beginig of the file.
w+: - Opens a file for writing and reading. It creates a new file if it does not exist. If the file is
exists then it overrides the file.
a+: - Open a file for both appending and reading. The file pointer at the end of the file if the
file exists. If the file does not exist, it creates a new file for writing.
x: - To open a file in exclusive creation mode for write operation. If the file already exists
then we will get FileExistsError.
Note: - All the above modes are applicable for text files. If the above modes suffixed with ‘b’
then these represents binary files.
Ex: rb,wb,ab,r+b,w+b,a+b,xb

Closing a file:
After completing our operations on the file, it is highly recommended to close the file. For
this we have to use close() function.
Syntax:
fileobject.close()
Ex:
f.close()

Writing data to files: -


write(): - This method writes any string to the file.
Syntax:
fileobject.write("string")
Ex:
f=open("test.txt",'w')
f.write("Python")
f.write("Java")
print("Write operation completed")
f.close()

In the above program all lines write in a file as single line. We can use \n to convert line
by line.
Ex:
f=open("test.txt",'w')
f.write("Python \n")
f.write("Java \n")
f.close()
print("Write operation completed")

writelines(list of lines): - To write multiple lines at one time.


Ex:
f=open("test.txt",'w')
l=["satish","lokesh","rajesh","lohit"]
f.writelines(l)
f.close()
print("Write operation completed")

Ex: To write multiple lines using list


f=open("test.txt",'w')
l=["satish \n","lokesh \n","rajesh \n","lohit \n"]
f.writelines(l)
f.close()
print("Write operation completed")

Reading data from files:


read(): - This method reads total data from the file.
Syntax:
fileobject.read()

Ex:
f=open("test.txt",'r')
print(f.read())
f.close()

read(n): - To read n characters from file


Syntax:
fileobject.read(n)
Here, passed parameter is the number of bytes to be read from the opened file. This method
starts from the beginning of the file.
Ex: To read required number of bytes
f.open("test.txt",'r')
print(f.read(10))
f.close()

readline(): - To read only one line.


Ex:
f=open("test.txt",'r')
line=f.readline()
print(line)
line=f.readline()
print(line)
f.close()

→readline method by default provide new line at the end of the line. That’s every time two
lines created. To overcome the problem we can use end attribute in print statement.
Ex:
f=open("test.txt",'r')
line=f.readline()
print(line,end='')
line=f.readline()
print(line, end='')
f.close()
readlines(): - To read all the lines into list.
Ex:
f=open("test.txt",'r')
print(f.readlines())
f.close()
#output will be in form list

Ex:
f=open("test.txt",'r')
lines=f.readlines()
for line in lines:
print(line)
f.close()

You might also like