Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

PP_UNIT-3(PART-2)

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

Unit III(PART-2)

Functions
Function:
Functions are self-contained chunks of code that perform a particular task.
(OR)
Functions are self-contained block of statements that perform a particular task.
• For every function, it has name that identifies what it does and this name is used to call
the function to perform its task when needed.
• Function may have arguments and many return values.
• Python programming has a lot of built-in-functions.
The basic form of a function in python is:
• All function definitions begin with the keyword “def”, followed by the function name
and the argument list in the parenthesis.
• The closing parenthesis of the argument list is followed by colon.
• Finally, there will be a bunch of statements going under the function with same level of
indentation like the ‘if-statements’
Note 1: def keyword is used to define function
Note 2: The arguments are the information that you pass into the function.
General syntax of keyword def is as follows:
def function_name(parameters):
statement-1
statement-2
----------------
----------------
----------------
Note 1: There is no need to specify the datatype of the parameters
Note 2: A function can take any number and the type of input parameters
Note 3: A function can return any number and any type of result
Uses of Functions:
• Code reusability
• Breaking a big program into smaller functions, the different programmers working on
that project can divide the work load.
We can do two things with function:
• define it
• call it
Example:
# Function to say hello on call the function
def greet():
print(“Hello”)
#Function call
greet()
Output:
Hello
Note 1: The names given in the function define are called parameters.
Note 2: The values we specify in the function call are called arguments.
Example:
def add(a,b):
c=a+b
return c
print(add(10,20))
In the above program
a, b are parameters
10, 20 are arguments
Example:
def greet(name):
print(“Hello {}” .format(name))
greet(“Raju”)
greet(“Hari”)
Note: When we call a function with arguments, the values of those arguments are copied to
their corresponding parameters inside the function.
Example:
def greet(name,gender):
if gender is ’f’:
print(“Hello Ms.{ }” .format(name))
elif gender is ‘m’:
print(“Hello Mr.{ }” .format(name))
else:
print(“Hello { }” .format(name))
greet(“raju”,”m”)
greet(“machine”,””)
greet(“radha”,”f”)
Function calling syntax:
function_name()
(or)
function_name(variable1, variable2, …………..)
Example:
def add(a,b):
c=a+b
return c
print(“Sum of two numbers is “,add(10,20))
arguments
Function arguments:
You can call a function by using the following types of arguments
• Positional (or) required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Positional arguments:
Positional arguments are arguments whose values are copied to their corresponding
parameters in order.
Keyword Arguments:
To avoid the positional argument confusion, you can specify arguments by the names of
their corresponding parameters. (Even it is in different order)
It helps this function to identify the arguments by the parameter name.
Default Arguments:
Python allows users to specify default values for parameters.
The default value is used if the caller does not provide a corresponding argument
Note: A default argument assumes a default value if a value is not provided in the function
call for that argument.
Note: You can specify any no. of default arguments in your function
Note: If you have default arguments, then they must be written after the non-default
arguments.
Variable-length argument:
• In some situations, it is not known in advance how many arguments will be passed to a
function.
• In such cases, python allows programmer to make function call with arbitrary no. of
arguments (or) Variable-length arguments.
• When we use arbitrary arguments (or) variable-length argument, then the function
definition uses an asterisk(*) before the parameter name.
Syntax:
def function_name(arg1, arg2, arg3, ……………….):
function statements
return statement

Example: (One Example for all arguments)

#Example Program for positional,keyword and default arguments

def emp_details(name,age,salary=20000):

print("Name of the employee:",name)

print("age of the employee:",age)

print("salary of the employee:",salary)

print("Example for Positional argument(without order)")


emp_details(34,29000,"Raju") #Positional argument

print("\nExample for Positional argument(with order)")

emp_details("raju",34,29000) #positional argument

print("\nExample for keyword argument")

emp_details(age=34,salary=29000,name="Raju") #Keyword arguments

print("\nExample for default argument")

emp_details(name='raju',age=34)# default argument

#Example Program for variable-length arguments

def print_args(*arg):

print("\nvariable length argumentsa: ",arg)

print_args(3, 2, 1, 'o!', 'start', 'stop')

Anonomyous Function or Lambda function:


In python anonymous function is a function i.e., defined without name.(Function without no
name)
While normal functions are defined by using def keyword in python anonymous functions
are defined by using "lambda" keyword
Hence anonymous functions are called as lambda function
A lambda function has the following syntax
lambda argument: expression
Lambda function can have any number of arguments but only one expression the expression
is evaluated and return a value.
e.g.
a=lambda x:x*2
print(a(10))
e.g.2
sum=lambda x,y:x+y
print(sum(2,8)
e.g.3
sq=lambda x:x**2
print(sq(4))
Write a lambda function o swap two numbers
swap=lambda x,y:x,y=y,x
print(swap(2,5))

Uses:
1. We use this function when we required nameless function for a short period of time
2. In python we generally use it as an argument to a higher order function
3. Lambda functions are used along with the built in functions like filter and map

Higher order function

A higher order function (HOF) is a function that follows at least one of the following
conditions −

• Takes on or more functions as argument

• Returns a function as its result

Example:
mylist={1,5,6,4,7,8,12}
newlist = list(filter(lambda x:x%2==0,mylist))
print(newlist)
e.g.
mylist={1,2,3,4,5,6}
newlist = list(map(lambda x:x*2,mylist))
print(newlist)

Scope of variables in the function:


The scope of a variable determines the portion of a program where we can access a
particular identifier. There are two basic scopes of a variable in python.
i) Local Scope or Local Variable
ii) Global scope or Global variable
Local Scope or Local Variables:
Variables that are defined inside a function body have a local scope and those variables are
called Local Variables.
Global Scope or Global Variables:
Variables that are defined outside all the functions have a global scope and these variables
are called global variables.
Local Variables can be accessed only unside the function where they are defined.
Global Variables can be accessed only through out the program by all the functions.
e.g.
y=2 #global variable
def print1():
x=3 #local variable
print(x)
print1()
print(y)
e.g. 2
x=2 #global variable
def print1():
x=3 #local variable
print(x)
print1()
print(x)
fruithful Function (function returning a value):
In fruitful function the return statement include a return value
(OR)
Functions which can return something to the users are called fruitful functions.
e.g.
import math
def circumference(r):
return math.pi*r**2
Recursive function:

A recursive function is a function that calls itself during its execution. This enables
the function to repeat itself several times, outputting the result and the end of each iteration.

Example:

def factorial(i):

if i == 1:

return 1

else:

return (i * factorial(i-1))

number = 9

print("The factorial of", number, "is", factorial(number))

Name spacing:
It is a mapping from names to objects
Namespace is dictionary of variable names (keys) and their corresponding objects (values)

Names Objects
x=3
y=4 x 3

x=y y 4

There are two namespaces


I) local namespace
ii) global namespace
If local and global variables have same name the local variable shadows the global variable
e.g.
x=3
def fun():
x=2
print (x)
print(x)
Output:
2
To assign a value to a global variable within a function within a, we must global statement
before that variable.
Syntax:
global variablename
The statement global variablename tells the python that variable name is global variable
and python stops searching for local namespace of the variable.
e.g.
x=4
def fun():
global x=4
x=2
print(x)

Case Study Gathering Information from a File System:


Modern file systems come with a graphical browser, such as Microsoft's Windows Explorer
or Apple's Finder. These browsers allow the user to navigate to files or folders by selecting
icons of folders, opening these by double-clicking, and selecting commands from a drop-
down menu. Information on a folder or a file, such as the size and contents, is also easily
obtained in several ways. Users of terminal based user interfaces must rely on entering the
appropriate commands at the terminal prompt to perform these functions. In this case study,
we develop a simple terminal-based file system navigator that provides some information
about the system. In the process, we will have an opportunity to exercise some skills in top-
down design and recursive design.

Request
Write a program that allows the user to obtain information about the file system.

Analysis
File systems are tree-like structures, as shown in below figure

Fig: Structure of a file system

The program we will design following commands:

Program:

import os, os. path


QUIT = '7'
COMMANDS = ('1', '2', '3', '4', '5', '6', '7')
MENU = """'
1 List the current directory
2 Move up
3 Move down
4 Number of files in the directory
5 Size of the directory in bytes
6 Search for a filename
7 Quit the program""""
def main():
while True:
print(os.getcwd()
print (MENU)
command = acceptCommand
runCommand(command)
if command == QUIT:
print("Have a nice day!")
break
def acceptCommand():
"Inputs and returns a legitimate command number."
command = input("Enter a number: ")
if command in COMMANDS:
return command
else:
print("Error: command not recognized")
return (acceptCommand)
def runCommand(command):
"'"'Selects and runs a command."
if command == '1':
listCurrentDir(os.getcwd())
elif command == '2':
moveUp()
elif command == '3':
moveDown (os.getcwd()
elif command == '4':
print("The total number of files is", \ countFiles(os.getcwd))
elif command == '5':
print("The total number of bytes is", \ countBytes (os.getcwd())
elif command == '6':
target = input("Enter the search string:")
filelist = findFiles(target, os.getcwd)
if not fileList:
print("String not found")
else:
for f in filelist:
print(f)
def listCurrentDir(dirName):
"Prints a list of the cwd's contents.'
Tyst = os. listdir(dirName)
for element in lyst:
print(element)
def moveUp():
"Moves up to the parent directory."
os.chdir("..")
def moveDown (currentDir):
"Moves down to the named subdirectory if it exists."
newDir = input("Enter the directory name: ")
if os.path.exists(currentdir + os. sep + newDir) and os.path.isdir(newDir):
os.chdir(newDir)
else:
print("ERROR: no such name")
def countFiles(path):
"'"'Returns the number of files in the cwd and all its subdirectories."
count = 0
lyst = os.listdir(path)
for element in lyst:
if os.path. isfile(element):
count += 1
else:
os.chdir(element)
count += countFiles(os.getcwd())
os.chdir("..")
return count
def countBytes(path):
"'"Returns the number of bytes in the cwd and all its subdirectories."
count = 0
lyst = os.listdir(path)
for element in lyst:
if os. path.isfile(element):
count += os.path.getsize(element)
else:
os.chdir(element)
count += countBytes(os.getcwd())
os.chdir("..")
return count
def findFiles (target, path):
"Returns a list of the filenames that contain the target string in the cwd and all its
subdirectories."
files = []
lyst = os.listdir(path)
for element in lyst:
if os.path. isfile(element):
if target in element:
files.append(path + os. sep element
else:
os.chdir(element)
files.extend(findFiles (target, os.getcwd()))
os.chdir("..")
return files
if _ _name_ _ == "_ _main_ _"():
main()

You might also like