0% found this document useful (0 votes)
2 views

Class12_CS_Chapter7

Chapter 7 covers the concept of functions in Python, including user-defined, built-in, lambda, and recursive functions. It explains how to define and call functions, the use of function arguments, and the advantages of using functions for code modularity and reuse. Additionally, it discusses variable scope, the return statement, and the composition of functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Class12_CS_Chapter7

Chapter 7 covers the concept of functions in Python, including user-defined, built-in, lambda, and recursive functions. It explains how to define and call functions, the use of function arguments, and the advantages of using functions for code modularity and reuse. Additionally, it discusses variable scope, the return statement, and the composition of functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

CHAPTER 7

PYTHON FUNCTION
LEARNING
OBJECTIVES

•Understand the concept of function and


their types.
• Know the difference between User
defined and Built in functions.
• Know how to call a function.
•Understand the function arguments.
• Know Anonymous functions.
•Know Mathematical and some String
functions.
FUNCTIONS
 Functions are named blocks of code that are designed to do
specific job.
 When you want to perform a particular task that you have
defined in a function, you call the name of the function
responsible for it.
 If you need to perform that task multiple times throughout your
program, you don’t need to type all the code for the same task
again and again; you just call the function dedicated to handling
that task, and the call tells Python to run the code inside the
function.
 You’ll Advantages
find that usingoffunctions
functions areyour programs easier to
makes
write, read, test, and fix errors.
• It avoids repetition and makes high degree of code
reusing.
• It provides better modularity for your application.
Types of Functions
Functions Description

Functions defined by
User-defined functions
the users themselves.

Functions that are


Built-in functions
inbuilt with in Python.

Functions that are


Lambda functions anonymous un-named
function.
Functions that calls
itself is known as
Recursion functions
recursive
Defining Functions
Functions must be defined, to create and use certain
functionality.
There are many built-in functions that comes with the
language python (for instance, the print() function), but
you can also define your own function.
When defining functions there are multiple things that
• Function blocks begin with the keyword “def” followed by
need to be noted;
function name and parenthesis ().

• Any input parameters or arguments should be placed


within these parentheses when you define a function.

• The code block always comes after a colon (:) and is


indented.

• The statement “return [expression]” exits a function,


optionally passing back an expression to the caller. A
“return” with no arguments is the same as return None.
syntax
def <function_name ([parameter1,
parameter2…] )> :
<Block of Statements>
return <expression / None>
Block
A block is one or more lines of code, grouped together so that
they are treated as one big sequence of statements while
execution.
In Python, statements in a block are written with indentation.
Usually, a block begins when a line is indented (by four
spaces) and all the statements of the block should be at
same indent level. Nested block
A block within a block is called nested
block.
When the first block statement is
indented by a single tab space, the
second block of statement is indented
EXAMPLES
by double tab spaces.
def hello(): def my_function():
print ("sunesh") print("Hello from a
return function")
Advantages of User-defined
Functions

1. Functions help us to divide a program into modules. This makes


the code easier to manage.

2. It implements code reuse. Every time you need to execute a


sequence of statements, all you need to do is to call the function.

3. Functions, allows us to change functionality easily, and different


programmers can work on different functions.
Passing Parameters in
Functions
The parameters that you place in the
parenthesis will be used by the function
itself. You can pass all sorts of data to the
functions.
EXAMPLES

def my_function(fname):
print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")

def area(w,h):
return w * h
print (area (3,5))
Parameters Arguments

The variables used in The values we pass to


the function definition the function parameters
Function
Arguments
Arguments are used to call a function and
there are primarily 4 types of functions that
one can use:

1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Required Arguments
“Required Arguments” are the arguments passed to a
function in correct positional order.
Here, the number of arguments in the function call
should match exactly with the function definition.
You need at least one parameter to prevent syntax
errors to get the required output.

WRONG CODE CORRECT CODE


def printstring(str): def printstring(str):
print ("Example - Required print ("Example - Required
arguments ") arguments ")
print(str) print(str)
return return
printstring() printstring("Sunesh")
Keyword arguments
Keyword arguments will invoke the function after
the parameters are recognized by their parameter
names.
The value of the keyword argument is matched
with the parameter name and so, one can also
put arguments in improper order (not in order).
CORRECT CODE WRONG CODE

def printdata (name): def printdata (name):


print ("Example-2 Keyword print (“Example-2 Keyword
arguments") arguments”)
print ("Name :", name) print (“Name :”, name)
return return
# Now you can call printdata() # Now you can call printdata()
function function
printdata (name = "shan") printdata (name1 = “Gshan”)
Default argument
In Python the default argument is an argument
that takes a default value if no value is provided
in the function call.
EXAMPLES
def my_function(food): def my_function(country =
for x in food: "Norway"):
print(x) print("I am from " + country)
fruits = ["apple", "banana", my_function("Sweden")
"cherry"] my_function("India")
my_function()
my_function(fruits) my_function("Brazil")

def printinfo( name, salary = 3500):


print ("Name: ", name)
print ("Salary: ", salary)
return
printinfo("Mani")
Variable-Length Arguments
Python has *args which allow us to pass the variable number
of non keyword arguments to function.

SYNTAX
def function_name(*args):
function_body
return_statement

EXAMPLE
def sum(x,y,z):
print("sum of three nos :",x+y+z)
sum(5,10,15)
EXAMPLES
def printnos (*nos): def adder(*num):
print for n in nos: sum = 0
return for n in num:
# now invoking the printnos()
sum = sum + n
function
print ("Printing two values") print("Sum:",sum)
printnos (1,2) adder(3,5)
print ('Printing three values') adder(4,5,6,7)
printnos (10,20,30) adder(1,2,3,5,6)

def printnames (*names):


for n in names:
print(n)
return
# now invoking the printnos()
function
print ("Printing four names")
printnames (‘ABC',DEF', GHI',JKL')
print ('Printing three names')
In Variable Length arguments we can pass the
arguments using two methods.
1. Non keyword variable arguments
2. Keyword variable arguments

Non-keyword variable arguments are called


tuples.
Anonymous function
In Python, anonymous function is a function that
is defined without a name.

While normal functions are defined using the def


keyword, in Python anonymous functions are
defined using the lambda keyword.
Hence, anonymous functions are also called as
lambda functions.
What is the use of lambda or anonymous function?
• Lambda function is mostly used for creating
small and one-time anonymous function.
• Lambda functions are mainly used in
combination with the functions like filter(),
map() and reduce().
lambda [argument(s)] :expression
EXAMPLES

sum = lambda arg1, arg2: arg1 +


arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,-40))

x = lambda a : a + 10
print(x(5))

x = lambda a, b : a * b
print(x(5, 6))

def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
The return Statement
• The return statement causes your function to exit and
returns a value to its caller. The point of functions in
general is to take inputs and return something.
• The return statement is used when a function is ready
to return a value to its caller. So, only one return
statement is executed at run time even though the
function contains multiple return statements.
• Any number of 'return' statements are allowed in a
function definition but only one
return [expression list ]of them is executed at
run time.
This statement can contain expression which gets evaluated
and the value is returned. If there is no expression in the
statement or the return statement itself is not present inside
a function, then the function will return the None object.

def usr_abs (n):


if n>=0:
return n
else:
return -n
x=int (input("Enter a number :"))
print(usr_abs (x))
Scope of variable
Scope of variable refers to the part of the program, where it
is accessible, i.e., area where you can refer (use) it. We can
say that scope holds the current set of variables and their
values. Two types of scopes :
• LOCAL SCOPE
• GLOBAL
Local Scope SCOPE
A variable declared inside the function's body or in the local
scope is known as local variable.
Rules of local variable
• A variable with local scope can be accessed only within the
function/block that it is created in.
• When a variable is created inside the function/block, the
variable becomes local to it.
• A local variable only exists while the function is executing.
• The format arguments are also local to function.
def loc():
y=0 # local scope
print(y)
Global Scope
• A variable, with global scope can be used anywhere in
the program. It can be created by defining a variable
outside the scope of any function/block.
Rules of global Keyword
The basic rules for global keyword in Python are:
• When we define a variable outside a function, it’s global
by default. You don’t have to use global keyword.
• We use global keyword to read and write a global variable
inside a function.
• Use of global keyword outside a function has no effect

c = 1 # global x = 0 # global variable


variable def add():
def add(): global x
print(c) x = x + 5 # increment by 2
add() print ("Inside add() function x value is
:", x)
add()
print ("In main x value is :", x)
Built-in and
Mathematical
functions
Composition in functions
The value returned by a function may be used as an
argument for another function in a nested manner. This is
called composition.
if we wish to take a numeric value or an expression as a
input from the user, we take the input string from the user
using the function
input() and eval() function to evaluate its value
Python recursive functions
When a function calls itself is known as recurs
A recursive function calls itself.
def parrot(): def fact(n):
print("parrot start") if n == 0:
print("parrot end") return 1
def cheese(): else:
print("cheese start") return n * fact (n-1)
parrot() print (fact (0))
print("cheese end")
print (fact (5))
cheese()

def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example
Overview of how recursive
function works
1. Recursive function is called by some external code.

2. If the base condition is met then the program gives


meaningful output and exits.

3. Otherwise, function does some required processing


and then calls itself to continue recursion.

You might also like