0% found this document useful (0 votes)
4 views66 pages

STD-12th - Chapter - 3 Working With Functions

This document is a comprehensive guide on functions in Python, covering their definition, types (built-in, user-defined, and module functions), and how to define and call them. It explains the flow of execution, passing parameters (positional, default, keyword), and returning values from functions. The document also highlights the importance of function structure, including the use of the 'def' keyword, parameters, and return statements.

Uploaded by

solankikshitij70
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)
4 views66 pages

STD-12th - Chapter - 3 Working With Functions

This document is a comprehensive guide on functions in Python, covering their definition, types (built-in, user-defined, and module functions), and how to define and call them. It explains the flow of execution, passing parameters (positional, default, keyword), and returning values from functions. The document also highlights the importance of function structure, including the use of the 'def' keyword, parameters, and return statements.

Uploaded by

solankikshitij70
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/ 66

Search . . .

STD 12th

WORKING
WITH FUNCTIONS
CHAPTER 3
Welcome To The Programming World…….

1
3.1 Introduction Search . . .

3.2 Understanding Functions


INDEX
3.3 Defining Functions in Python

3.4 Flow of Execution in a Function Call

3.5 Passing Parameters

3.6 Returning Values From Functions

3.7 Composition

3.8 Scope of Variables


2
3.1 INTRODUCTION
 The concept of functions is widely applied in real life.

Example: Consider this scenario: your mother has asked u to serve drinking
water to everyone during dinner, and your sister has been asked to switch off
the lights and fans that are not in use. Your mother divided the work into 2
parts

 This is similar to the concept of functions, in which a large program is broken


down into individual blocks of code that work together to complete the task
3
3.2 UNDERSTANDING FUNCTIONS
 A large program is broken down into smaller units known as functions.

 function is a piece of code written to carry out a specified task

 In Python, the function acts in a similar manner. It takes the input, performs an
operation on it, and produces the result.

 The input values are called arguments or parameters.


4
3.2 UNDERSTANDING FUNCTIONS
 There are three types of functions in Python as discussed below:

Classification of Functions
5
3.2 UNDERSTANDING FUNCTIONS
 Built-in Functions - The built-in functions are already defined in Python and
you can use them directly without referring to any module or library.

For example, print(), input(), type(), len() etc.

 Functions Defined in Modules - These functions are pre-defined in particular


modules and can only used when the corresponding module is imported.

For example, To use pre-defined / library functions inside a module, say sin( ),
cos(), tan() you need to import the module math function in your program

import math

 Then you can use math library's functions as math.<function-name> .


6
3.2 UNDERSTANDING FUNCTIONS
 User-defined Functions - A user-defined function enables you to define your
own code to accomplish a particular task.
 These are defined by the programmer.

 As programmers you can create your own functions.

Classification of Functions

7
3.3 DEFINING FUNCTIONS IN PYTHON
 It can be defined using the following syntax:

 Consider the following example of a function definition:

8
3.3 DEFINING FUNCTIONS IN PYTHON
 Consider the following example of a function definition:

9
3.3 STRUCTURE OF A PYTHON FUNCTION

 def Keyword: The function definition starts with the

def keyword, followed by the name of the function,

arguments/parameters , and ends with a colon (:).


 The keyword def is reserved and cannot be used as a variable or function name
in the programs.

 Function Name: The name of the function can be any valid identifier.
10
3.3 STRUCTURE OF A PYTHON FUNCTION

 Parameters: Here a list of parameters or arguments is given inside the


parentheses separated by a comma (,).
• These parameters are used to pass necessary data to a function.

• A function can take any number of arguments or none.

• If the function does not accept any arguments, then the parentheses is left
empty.

11
3.3 STRUCTURE OF A PYTHON FUNCTION

 Colon (:) : A colon at the end of the definition statement signifies the
beginning of the block of code and further body of function starts.

 Body of the Function: The function body contains the statements, which
define what the function does.
• It is an indented block. All the statements in the body of the function must be
equally indented, else it will create a syntax error.
12
3.3 STRUCTURE OF A PYTHON FUNCTION

 Return Statement: The return statement is used to return a value from the
function to the place where it has been called in the program.
• The return statement is an optional field.

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

• If a function does not have a return statement in the body, then a reserved
keyword None is returned automatically.

13
3.3 STRUCTURE OF A PYTHON FUNCTION

14
3.2 CALLING / INVOKING / USING A FUNCTION

 The process of using a function in a program after defining it is called calling


a function or invoking a function or function call

Syntax: <function name> (input values as arguments)

Function Header

15
3.2 CALLING / INVOKING / USING A FUNCTION

 The number of parameters passed to a function should be equal to the


number of arguments defined in the function.

16
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.

17
3.4 FLOW OF EXECUTION IN A FUNCTION

 Whenever a function call statement is encountered,


an execution frame for the called function is created and
the control (program control) is transferred to it.

18
3.4 FLOW OF EXECUTION IN A FUNCTION

 An execution frame contains :


• some internal information from the user

• name of the function

• values passed to function

• variables created within function

• information about the next instruction to be executed.

19
3.4 FLOW OF EXECUTION IN A FUNCTION

# After adding return statement pass value i.e. 11 to variable sum

# Statement 1

# Statement 2

20
3.4 FUNCTION ARGUMENTS & PARAMETERS
 Parameters (formal parameter or formal arguments) are the names given to variables
that are given in the parentheses in the function definition.

 Parameters in Python have to be some names i.e., variables to hold values

 Arguments (actual parameter or actual arguments) are the actual values that are
passed during the function call.

 Arguments in Python can be one of these value data types that is variables,
literals and expressions.
Function Header

Function Call 21
3.4 FUNCTION ARGUMENTS & PARAMETERS
Please remember one thing

 if you are passing values of immutable types (e.g., numbers, strings etc.) to
the called function then the called function cannot alter the values of passed
arguments

 But if you are passing the values of mutable types (e.g., list or dictionaries)
then called function would be able to make changes in them

Function Header

Function Call

22
3.5 PASSING PARAMETERS
 Parameters are the variables that are defined or used inside parentheses
while defining a function,

 Whereas arguments are the values passed for these parameters while calling
a function at run-time so that the function can do the designated task using
these values.

 If defining a function has three parameters then the function call should also
pass three values.

23
3.5 PASSING PARAMETERS
 There are three types of parameters arguments that Python supports

1 . Po s i t i o n a l A r g u m e n t s / R e q u i r e d A r g u m e n t s /

Mandatory Arguments

2. Default Arguments

3. Keyword Arguments / Named Arguments

4. Using Multiple Arguments

24
3 . 5 PA S S I N G PA R A M E T E R S - P O S I T I O N A L A R G U M E N T S

 when we create a function call statement for a given function definition, we

need to match

the number of arguments with number of parameters required.

 The following are some key points for the positional parameters:
• It is a must provide arguments for every parameter.

• Values to be passed as arguments must match with the parameters position-


wise and order-wise.

25
3 . 5 PA S S I N G PA R A M E T E R S - P O S I T I O N A L A R G U M E N T S

Passed 2 values

Parameter position
Passing 2 values

OUTPUT 

 In the above example, the function welcome_note() has two parameters.

 If you provide these two parameters according to their order (both string),
then there will be no error, otherwise an error will be generated.
26
3 . 5 PA S S I N G PA R A M E T E R S - P O S I T I O N A L A R G U M E N T S
Passed 2 values

Parameter position
Passing 2 values

OUTPUT 

 In the above example, the function welcome_note() has two parameters.

 If you provide two parameters without correct order (one string & number can’t add),
then an error will be generated.

27
3 . 5 PA S S I N G PA R A M E T E R S - D E FAU LT A R G U M E N T S

 Python allows us to assign default value(s) to a function's parameter(s).

 The default values are specified in the function header of function definition.
Following is an example of function header with default values
Passed 1 value

Function Header
Function Definition

Default value / argument / parameter

Function Passing 1 value and OUTPUT


Call
2 argument is missing
28
3 . 5 PA S S I N G PA R A M E T E R S - D E FAU LT A R G U M E N T S

 Default Argument / Parameter - A parameter having default value in the


function header is known as a default parameter/argument

Passed 1 value

Function Header
Function Definition

Default value / argument / parameter

Function Passing 1 value and OUTPUT


Call
2 argument is missing

29
3 . 5 PA S S I N G PA R A M E T E R S - D E FAU LT A R G U M E N T S
 A parameter having a default value in function header becomes optional in
function call.

 Function call may have value or may not have value for it.

Passed 2 values, here default value / argument / parameter will not work
because by default Function Call has passed 2 values

OUTPUT
Function
Call
Passing 2 values and
no argument is missing
30
3 . 5 PA S S I N G PA R A M E T E R S - D E FAU LT A R G U M E N T S
 Following are examples of function headers with default values :
Simple Interest
1. def interest (principal, time, rate=0.10) :  # legal

2. def interest (principal, time=2, rate=0.10) :  # legal

3. def interest (principal=200, time=2, rate=0.10) :  # legal


Positional argument / Non-Default arguments are placed before any default arguments in your function definition.

1. def interest (principal=200, time, rate) :  # illegal


First
Positional
Default Argument Positional Argument / Non Default Argument or
Non-Default Arguments
comes then
2. def interest (principal=200, time=2, rate) :  # illegal Second comes
Default Argument

3. def interest (principal, time=2, rate) :  # illegal


Default Argument Positional Argument / Non Default Argument
31
3 . 5 PA S S I N G PA R A M E T E R S - D E FAU LT A R G U M E N T S

 Non-default arguments cannot follow default argument.

Default Argument Positional Argument / Non Default Argument

#illegal argument / parameter passing

32
3 . 5 PA S S I N G PA R A M E T E R S - K E Y W O R D A R G U M E N T S

 The keyword or named arguments in Python functions provide flexibility to


provide values as parameters in any order and sequence.

 That means, you can change the order of the arguments while passing the
values to the function in a function call, provided you mention the names of
the arguments. The positional arguments cannot be placed after keyword arguments as it will produce an error.

The sequence of arguments in function header and


function call is different.

OUTPUT

33
3.5 Dif ference

Positional Arguments Default Arguments

Keyword Arguments

 OUTPUT

34
3 . 5 PA S S I N G PA R A M E T E R S - U S I N G M U LT I P L E A R G U M E N T S

 Python allows you to combine multiple argument types in a single function call.

Rules Description
In the sequence of arguments, first the positional arguments must be there followed by the keyword
Rule 1
arguments.
Rule 2 The positional arguments cannot be placed after the keyword arguments.
Rule 3 You cannot specify a value for an argument more than once.

35
3 . 5 PA S S I N G PA R A M E T E R S - U S I N G M U LT I P L E A R G U M E N T S

Legal /
Function call statement RULE Reason
illegal
First the positional arguments must be there followed
interest ( 5000, 4, rate=0.12) Legal Rule 1 by the keyword
arguments.
The positional arguments cannot be placed after the
interest (rate=0.12, 5000, 4) illegal Rule 2
keyword arguments.
Multiple values provided for prin ;
You cannot specify a value for an argument more than
interest (3000, prin= 5000, t= 4 ) illegal Rule 3
once.

Rules Description
In the sequence of arguments, first the positional arguments must be there followed by the keyword
Rule 1
arguments.
Rule 2 The positional arguments cannot be placed after the keyword arguments.
Rule 3 You cannot specify a value for an argument more than once.
36
 Functions in Python may or may not return a

3.6 value.

 There can broadly two types of functions in

RETURNING Python :

1. Non Void Functions / Fruitful Functions

VA LU E S These functions return some value.

2. Void Functions / Non-Fruitful Functions


FROM
These Functions do not return any value.
or
FUNCTIONS These Functions has empty return statement.

37
3 . 6 Re t u r n i n g Va l u e s f r o m F u n c t i o n s - NON VOID FUNCTIONS

 A function that returns a value using the return statement after execution is
called non-void function.

 Here, the function add() is returning the sum of two numbers using
the return statement. Thus, this function is a non-void function.

38
3 . 6 Re t u r n i n g Va l u e s f r o m F u n c t i o n s - NON VOID FUNCTIONS

 The return statement can return any of the following values:

1. A Literal 2. A Variable 3. An Expression


Return Statement Return Type
return 5 Literal
if there is no return statement Literal
return a variable
return 6+4 Expression
return a**3 Expression
return (a+8**2) / b Expression
return a+b/c Expression

 Remember, the return statement will not print the value. It returns the value to
the place where it has been called in the program.
39
3 . 6 Re t u r n i n g Va l u e s f r o m
F u n c t i o n s - NON VOID FUNCTIONS

 The returned value of a function


should be used in the function call
or inside the program of an function call or
inside the program of an expression or
expression or a statement. a statement

The returned value being used in assignment statement

The returned value being used in print statement

The returned value being used in relational expression

 OUTPUT
40
3 . 6 Re t u r n i n g Va l u e s f r o m F u n c t i o n s - NON VOID FUNCTIONS

 The return statement ends a function execution even if it is in the middle of the
function.

Here,
print statement is unreachable
because sum() function already end with return

 OUTPUT
41
3 . 6 Re t u r n i n g Va l u e s f r o m F u n c t i o n s - VOID FUNCTIONS
 The function is called void if it does not return any value or has an empty return statement.

You may or may not write the return statement,


because here the return statement returns nothing.

It is just given to return the flow of control


to the place where the function has been called.

OUTPUT
Function
Call

Function Call

Void function with no return statement

Void function with return statement

42
3 . 6 Re t u r n i n g Va l u e s f r o m F u n c t i o n s - VOID FUNCTIONS

You may or may not write the return statement,


because here the return statement returns nothing.

It is just given to return the flow of control


to the place where the function has been called.

OUTPUT
Function
Call

Function Call

 On calling the function, first, the flow will go to the msg() function body and
print the statement "Welcome".

 Then, it encounters the next line, i.e., return statement, which has nothing.

 So, the function will return None, which is the legal empty value of Python. 43
3 . 6 Re t u r n i n g M u l t i p l e Va l u e s f r o m F u n c t i o n
 To return multiple values from a function, you have to ensure following things :

i. In Python, you can return multiple values by using the return statement, separated by
a comma.

 Consider the following example:

OUTPUT

return statement, separated by a comma.

Function calc(5,5) will return two values add and sub.

 Observe that the function calc(a, b) returns two values, add and sub. These values are
treated as a tuple in Python.

44
3 . 6 Re t u r n i n g M u l t i p l e Va l u e s f r o m F u n c t i o n
 To return multiple values from a function, you have to ensure following things :

ii. The function call statement should receive or use the returned values in one of the
following ways :
a) Either receive the returned values in form a tuple variable as shown below:

 Here, the return statement returns two values


that form a tuple.

 The function calc(5, 6) returns the value to the


variable x.

 So, the x variable is a tuple type that


comprises two values in this example.
OUTPUT
This is called packing of tuple elements.
45
3 . 6 Re t u r n i n g M u l t i p l e Va l u e s f r o m F u n c t i o n
 To return multiple values from a function, you have to ensure following things :

ii. The function call statement should receive or use the returned values in one of the
following ways :
b) we can directly unpack the received values of tuple by specifying the same
number of variables on the left-hand side of the assignment in function call.

 Here, the return statement returns two values


that but not in the form a tuple.

 The function calc(5, 6) returns the value to the


variable x and y.

 So, the x variable & y variable is a int type This


is called Unpacking of tuple elements.

 OUTPUT
46
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 a function call can be any kind of expression :

 The above examples show you composition of function calls


— a function call as part of larger function call.

47
3 . 8 S c o p e o f Va r i a b l e s

 Suppose we want to go to Gandhinagar from Rajkot then…..

Ticket valid from Rajkot to Ahmedabad Ticket valid from Ahmedabad to Gandhinagar

Local

Ticket valid from Rajkot to Gandhinagar

Global

48
3 . 8 S c o p e o f Va r i a b l e s

 Similarly, there is a scope of variables in a Python program.

 The scope of a variable refers to the different parts of the function or the program within
which a variable or value is legal and accessible.

 A variable is only available inside a specific region of the program. This region of the
variable is called its scope.

 There are two types of scope in Python: Global Scope and Local Scope.

49
3 . 8 S c o p e o f Va r i a b l e s – G l o b a l S c o p e

 A variable created in the main body of the Python code is a global variable and has a
global scope.

 A global variable can be accessed anywhere in a program, whether inside or outside of a


function.

 Example:

50
3 . 8 S c o p e o f Va r i a b l e s – G l o b a l S c o p e

“a” is a global variable as it is defined outside the function and can be accessed anywhere in the program.

“y” is a global variable as it is defined inside the function and can be accessed anywhere in the program.

Global variables can be created using the global keywords.

“b” is a global variable as it is defined in the main program and can be accessed anywhere in the program.

OUTPUT

51
3 . 8 S c o p e o f Va r i a b l e s – L o c a l S c o p e

 A variable is said to have a local scope if it is created inside a function body.

 It can be accessed only from the particular function for which it has been defined.

 If you try to access the local variable outside the function body, an error will be
generated.

 Example:

52
3 . 8 S c o p e o f Va r i a b l e s – G l o b a l S c o p e

Here, “x” is a Local Variable.

So, it can’t access here

OUTPUT

53
3 . 8 S c o p e o f Va r i a b l e s – D i f f e r e n c e

Sr.No Local Variable Global Variable

It is a variable that is declared It is a variable which is declared


1
within a function or within a block. outside all the functions.
For global variables, lifetime is entire
For local variables, lifetime is their
program run (i.e., they live in
2 function's run (i.e., as long as their
memory as long as the program is
function is being executed.)
running)
It is accessible within a function only It is accessible throughout the
3
in which it is declared. program.

 The time for which a variable or name remains in memory called Lifetime of variable

54
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )

 Consider an example:
There are two students in your class with the first name Ayushi.

How will you recognize both of them? Obviously, with their last names. This way you will be able
to identify two different people.

 Similarly, in Python also, we deal with variables, functions, libraries, modules, etc.

 There is a possibility that the name of the variable you are intending to use has already
been used as the name of another variable, function, or method.

 In such a situation, it is necessary to learn how a Python program manages these names.
The term "namespace" refers to this concept.

55
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )

 In Python, a namespace is a mechanism that gives each


object a unique name.

Space Container
Names
 A variable or a method can be considered an object. Names
Names
 Python has its own namespace (Space is a container of Names

many names), which is kept in the form of a Python


dictionary.

 Whenever such a situation (multiple objects having the same


name in a program, but in different scopes) arises in Python,
then this can be resolved by following the LEGB rule.

 The acronym LEGB stands for Local, Enclosing, Global, and


Built-in scopes.

56
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )

 The acronym LEGB stands for Local, Enclosing, Global, and Built-in scopes.

1. LOCAL - It checks within its Local environment (or local namespace) ,


if it has a variable with the same name ;
if yes, Python uses its value. If not, then it moves to step 2.

LOCAL

OUTPUT

57
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )
 The acronym LEGB stands for Local, Enclosing,
Global, and Built-in scopes.
LOCAL
2. ENCLOSING ENVIRONMENT -
Python now checks the Enclosing
environment
if whether there is a variable with the same
name.
if yes, Python uses its value.
If the variable is not found in the current
environment, Python repeats this step to OUTPUT

higher level enclosing environments, if any.


If not, then it moves to step 3

58
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )

 The acronym LEGB stands for Local, Enclosing, LOCAL


Global, and Built-in scopes.

3. GLOBAL ENVIRONMENT -
Python now checks the Global environment
whether there is a variable with the same
name ;
if yes, Python uses its value.
If not, then it moves to step 4.

OUTPUT

59
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )
 The acronym LEGB stands for Local, Enclosing,
Global, and Built-in scopes.

4. Built-In ENVIRONMENT -
Python checks its Built-in environment that
contains all built-in variables and functions of
Python,
if there is a variable with the same if yes,
Python uses its value Otherwise Python would
report the error :

Example pi=3.14
OUTPUT

60
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )
 3 examples as given in textbook

Case – 1 : Variable in global Scope but not in local scope

61
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )
 3 examples as given in textbook

Case – 2 : Variable neither in local scope nor in global scope

62
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )
 3 examples as given in textbook

Case – 3 : Some Variable name in local scope as well as in global scope

63
3 . 8 N a m e Re s o l u t i o n ( Re s o l v i n g S c o p e o f a N a m e )
 Question from textbook

What if you want to use the global variable inside the local scope?

Ans: we can use the global variable inside the local scope by using global
keyword
“y” is a global variable as it is defined inside the function and can be accessed anywhere in the program.

OUTPUT

64
3.9 Mutable / Immutable Properties of Passed Data Objects

 In Python, immutable types are passed as parameter mechanisms. The called function

makes a separate copy of the passed values and then works with them.

So, the original values remain unchanged.

 On the other hand, in mutable types of implementations, the called function works

with the original values passed to it.

Thus, any changes made take place in the original values only.

65
Search . . .
STD 12th

THANK YOU
[email protected]

END SLIDE

You might also like