[go: up one dir, main page]

0% found this document useful (0 votes)
31 views13 pages

Class XII - L3 - Working With Functions

This document discusses functions in Python. It defines what a function is, how to call and define functions, and how the flow of execution works with functions. Functions allow breaking programs into reusable pieces of code through parameters and returns.

Uploaded by

Harsh Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views13 pages

Class XII - L3 - Working With Functions

This document discusses functions in Python. It defines what a function is, how to call and define functions, and how the flow of execution works with functions. Functions allow breaking programs into reusable pieces of code through parameters and returns.

Uploaded by

Harsh Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

LESSON 3 : WORKING WITH FUNCTIONS

1
3.1 UNDERSTANDING A FUNCTION:
• Consider the example
def calcSomething (x):
r = 2 *x ** 2
return r
where,
• def means a function definition is starting.
• Identifier following ‘def’ is the name of the function, i.e., the function name is
calcSomething.
• The variable/identifiers inside the parentheses are the arguments or
parameters, i.e., here x is the argument to function calcSomething.
• There is a colon at the end of def line, meaning it requires a block.
• The statement indented below the def function, define the functionality
of the function. This block is called body-of-the-function.
• The return statement returns the computed result.

3.1.1 Calling/Inworking/Using a function:


• A function call statement takes the following syntax:
<function-name> (< value-to-be-passed-to-argument>)
• Example 1:
a=7
calcSomething( a)
• Example 2:
calcSomething( 5)
• The syntax of the function call is very similar to that of the
declaration, except that the key word def and colon are missing.

2
3.1.2 Python Function Type:
Python comes preloaded with many function-definitions that we can use
as per the needs. There are three following categories:
1. Built-in functions:
These are pre-defined functions and are always available for use.
Like len( ), type( ), int( ), input( ), etc.
2. Functions defined in modules:
These functions are pre-defined in particular modules and can only
be used when the corresponding module is imported.
Example : if you want to use sign() we need to import math
3. User defined functions:
These are defined by the programmer. As programmers can create
their own functions.

3.2 DEFINING FUNCTIONS IN PYTHON:


• A function once defined can be invoked as many time as needed by using its
name, without having to rewrite its code.
• General format:
def< function-name> ([parameter]):
[“ “ “< functions docstring> “ “ “]
<statement>
[<statement>]
…..
• Example:
def sum(x, y):
s=x+y
return s
• A function definition defines a user-function. The function definition does
not execute the function body, this gets executed only when the function is called
or invoked.

3
3.2.1
Structure of A Python Program:
• In python, all function definitions are given at the top followed by
statements which are not part of any functions. These are called
top-level statements.
• The python interpreter starts the execution of a program/ script
from the top-level statements.
• The top level statements are part of the main program, python
gives a special name as _main_.

3.2.2 Functions defined in modules:


These functions are pre-defined in particular modules and can only be used
when the corresponding module is imported.
Example : if you want to use sign() we need to import math

3.2.3 User defined functions:


These are defined by the programmer. As programmers can create their own
functions.

3.3 DEFINING FUNCTIONS IN PYTHON:


• A function once defined can be invoked as many time as needed by using its
name, without having to rewrite its code.
• General format:
def< function-name> ([parameter]):
[“ “ “< functions docstring> “ “ “]
<statement>
[<statement>]
…..
• Example:
def sum(x, y):
s=x+y
return s
• A function definition defines a user-function. The function definition does not
execute the function body, this gets executed only when the function is called
or invoked.

4
3.3.1 Structure of A Python Program:

• In python, all function definitions are given at the top followed by


statements which are not part of any functions. These are
called top-level statements.

• The python interpreter starts the execution of a program/ script from


the top-level statements.

• The top level statements are part of the main program, python gives
a special name as _main_.

• The structure of python program is as follow:

def function1( ) :

…..

def function2( ) :

…..

def function3( ) :

…..

#top-level statements here

Statement 1

Statement 2

…….

• Example:

def greet( ) :

print(“ Hi there!”)

print(“At the top-most level right now “)

print(“Inside”,_name_)

5
3.4 FLOW OF EXECUTION IN A FUNCTION:
• The flow of execution refers to the order in which statements are executed
during a program run.
• An execution frame contains:
i. Some internal information.
ii. Name of the function.
iii. Values passed to function.
iv. Variables created within function
v. Information about the next instruction to be executed
• Whenever a function call statement is encountered, an execution frame for
the called function is created and the control is transferred to it.
• Within the functions execution frame, the statements in the function-body
are executed, and with the return statement or the last statement of
function body, the control returns to the statement wherefrom the function
was called.
• Program execution begins with the first statement of _main_ segment
• Python starts reading from line 1 downwards. Statements are executed one
at a time, in order from top to bottom. Python follows the guidelines while
executing:
i. Execution always begins at the first statement of the program.
ii. Comment lines are ignored and not executed.
iii. If python notices that it is a function definition, then python just executes
the function header line to determine that it is proper function header
and skips all lines in the function body.
iv. The statements inside a function-body are not executed until the function
is called.
v. A function can define another function inside it.
vi. When a code-line contains a function call, python first jumps to the
function header line and then to the first line of the function body and starts
executing it.

6
vii. A function ends with a return statement or the last statement of function
body, whichever occurs earlier.
viii. If the called function returns a value then the control jump back to the
function call statement and completes it.
ix. If the called function does not return any value, then the controls jumps
back to the line following the function call statement.

3.4.1 Arguments and Parameters:


• Values can be passed to functions, for passing we need to define variables
to receive values in function definition and we send through a function
call statement.
• Example:
def multiply ( a, b) :
print(a * b)
y=3
multiply( 12, y)
multiply( y, y)
x = 5
multiply( y, x)
• In the above example, program has a function namely multiply( ) that
receive two values. This function can be called thrice by passing different
values.
• The three function values are:
1. multiply( 12, y)
2. multiply( y, y)
3. multiply( y, x)
• The values being passed through a function-call statement are called
arguments. And the values received in the function definition header are
called parameters.
• Arguments in python can be of literals, variables and expressions. But
parameters in python have to be some names i.e., variables to hold incoming
values.

7
3.5 PASSING PARAMETERS:
• A function call must provide all the values as required by function definition.
If a function header has three parameters named in its header then the
function call should also pass three values.
• Python supports three types of formal arguments/parameters:
1. Positional arguments.
2. Default arguments.
3. Keywords.

3.5.1 Positional/ Required Arguments:


• When the function call statement must match the number and order
of arguments as defined in the function definition, this is called the
positional argument matching.
• Example:
def check (a, b, c)
…….
• In the above function calls, the number of passed values has matched
with the number of received values. The values are given position
wise or order wise, the first parameter receives the value of
first argument, second argument receives second value and so on.
• Through function calls,
1. The arguments must be provided for all parameters
2. The values of arguments are matched with parameters, position wise.

3.5.2 Default Arguments:


• Python allows to assign default values to a functions parameters
which is useful in case a matching argument is not passed in
the function call statement.
• The default values are specified in the function header of function
definition.
• Example:
def interest ( principle, time, rate = 0.10 )

8
• The default value is specified in a manner syntactically similar to a
variable initialization. In the above example, function declaration
provides a default value of 0.10 to the parameter rate.
• In a function header, any parameter cannot have a default value
unless all parameter appearing on its right have their default values.
• The default values for parameters are considered only if no value is
provided in the function call statement.
• Advantages of default parameters:
1. They can be used to add new parameters to the existing functions.
2. They can be used to combine similar functions into one.

3.5.3 Keyword Arguments:


• Keyword arguments are the named arguments with assigned values
being passed in the function call.
• To have a complete control and flexibility over the values sent as
arguments for the corresponding parameters, python offers keyword
arguments.
• We can write any argument in any order provided we name the
arguments when calling the function.
• Example:
interest(prin = 2000, time = 2, rate = 0.10 )
interest(time = 2, prin = 2000, rate = 0.10 )
interest(time = 2, rate = 0.10,prin = 2000, )
• All the above function calls are valid, even if the order of arguments
does not match the order of parameters as defined in the header.

3.5.4 Using Multiple Argument Types Together:


• Python allows to combine multiple argument types in a function call.
• Example:
interest( 5000, time = 5 )
• The first argument value 5000 in the above statement is representing
a positional argument as it will be assigned to first parameter on the
basis of position.

9
• The second argument time = 5 is representing the keyword argument.
• Rules for combining all three types of argument:
1. An argument list must first contain positional argument followed
by key word argument.
2. Keyword should be taken from the required arguments
preferably.
3. You cannot specify a value for an argument more than once.

3.6 RETURNING VALUES FROM FUNCTION:


Functions in python may or may not return a value. There can be two types of
functions in python:

1. Functions returning some values:


• The functions that returns some computed results in terms of values
falls under this type.
• The computed value is returned using return statement as per the syntax:
return<value>
• The values being returned can be a literal, a variable, or an expression.
• Example:
return 5
return 6+4
return (a + 8 ** 2) / b
• When we call a function that is returning a value, the returned value
is made available to the caller function or program by
internally substituting the function call statement.
• The returned value of a function should be used in the caller function
or program inside an expression or a statement.
• The return statement ends a function execution even if it is in the
middle of the function.

10
2. Functions not returning any values:

• The functions that perform some actions or do some task but not return
any computed values or final value to the caller are called void
functions.

• A void function may or may not have a return statement. If a void


function has a return statement, then it would take the following form,
return

• The void functions are generally not used inside a statement or ex


pression in the caller, their function call statement is standalone
complete statement in itself.

• The void function do not return a value but they return a legal empty
value of python. Every void function returns value None to its caller

3.7 COMPOSITION:

• Composition in general refers to using an expression as part of a larger


expression, or a statement as a part of larger statement.

• The arguments of function call can be any kind of expression:

1. An arithmetic expression.

2. Logical expression

3. A function call.

3.8 SCOPE OF VARIABLE:

• The scope rules of a language are the rules that decide, in which parts of
the program, a particular piece of code or data item would be known and
can be accessed within.

• Parts of program within which a name is legal and accessible is called scope of
the name.

11
• There are broadly two kinds of scopes in python:
1. Global scope:
• A name declared in top level segment of a program is said to
have a global scope and is usable inside the whole program
and all blocks within the program.
• A global variable is a variable defined in the main program
(_main _ section). Such variables are said to have global scope.

2. Local scope:
• A name declared in a function-body is said to have local
scope. it can be used only within this function and the other
blocks contained under it.
• A local scope can be multi-level, there can be an enclosing
local scope having a nested local scope of an inside block.
• A local variable is a variable defined within a function, such
variables are said to have local scope.

3.8.1 Name Resolution (Resolving Scope of a Name):


• For every name reference within a program, when we access a
variable from within a program or function, python follows name
resolution rule, also known as LEGB rule.
• Python does the following to resolve it:
i. It checks within its Local environment (LEGB) if it has a variable with
the same name, if yes, python uses its value.
If not, then it moves to step ii
ii. Python now checks the Enclosing environment (LEGB). If yes, python
uses its values
If the variable is not found in the current environment, python
repeats this step to higher level enclosing environment, if any.
If not, then it moves to step iii
iii. Python now checks the Global environment (LEGB) whether there is
a variable with the same, if yes, python uses it.
If not, then it moves to step iv

12
iv. Python checks its Built-in environment (LEGB) that contains all built-in
variables and functions of python, if there is a variable with the
same name, if yes, python uses its value.
v. Otherwise python would report error.

3.9 MUTABLE / IMMUTABLE PROPERTIES OF PASSED DATA OBJECT


• Python’s variable are not storage containers, rather python variables are like
memory references, and they refer to the memory address where the value
is stored.
• Depending upon the mutable or immutability of its data type, a variable
behaves differently.
• If a variable is referring to an immutable type then any change in its value
will also change the memory address it is referring to, but if a variable is
referring to mutable type then any change in the value of mutable type will
not change the memory address of the variable.
• Changes in immutable types are not reflected in the caller function at all.
• Changes, if any, in mutable types
i. Are reflected in caller function if its name is not assigned a different
variable or datatype.
ii. Are not reflected in the caller function if it is assigned a different
variable or data type.

13

You might also like