0% found this document useful (0 votes)
33 views65 pages

CH 3 - Working With Functions

This document provides an overview of functions in Python, including their definition, types, and how to create and use them. It explains the difference between parameters and arguments, the need for functions, and various types of functions such as built-in and user-defined functions. Additionally, it covers function syntax, argument types, return values, and variable scope within functions.

Uploaded by

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

CH 3 - Working With Functions

This document provides an overview of functions in Python, including their definition, types, and how to create and use them. It explains the difference between parameters and arguments, the need for functions, and various types of functions such as built-in and user-defined functions. Additionally, it covers function syntax, argument types, return values, and variable scope within functions.

Uploaded by

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

CH 3.

Working with Functions


CBSE – CLASS – XII
COMPUTER SCIENCE WITH PYTHON (NEW)
(SUBJECT CODE : 083)
Objective 2

► What is function?
► Why do we need function?
► Types of function.
► How to create / write your own function?
► How a function works?
► How to use the function?
What is function? 3

Relate it with school function


What is function? 4

► Function is a sub program that acts on data and often return a value.

► Syntax:
def <function_name> ([ item ]):
function_ Body

Example: Lets write a function for this notation Q=2x 2


def calculate (x):
Q=2 * x ** 2
return Q
What is function? 5

Example: Lets write a function for this notation Q=2x 2


def calculate (x):
Q=2 * x ** 2
return Q

► Where :
► ‘def’ is a keyword, every function must begin with this
keyword ‘def’ and end with ‘ : ’ it indicate it requires a block.
► ‘calculate’ is the name of the function.
► The variable / identifier which are present in the parentheses
are called ‘arguments / parameter’.
► The ‘ return ’statement returns the computed result.
Python Function Anatomy 6

Parameter to the function

Name of the function

Keyword

Statement to return Body of the function- calculate


computed result

Function call inside


the print ()
DIFFERENCE BETWEEN PARAMETER AND
ARGUMENT 7

Parameters are defined by the names


that appear in a function definition.

Arguments are the values actually


passed to a function when calling it.
Parameters/arguments 8

►Parameters formal parameters formal arguments

►Argument Actual arguments Actual Parameters

To remember
Param is formal Argu is Actual
Why do we need function? 9

► Function is useful for…


► To handle the program easier.
► To reduce the program size.
► To make the program more readable.
► To make program management much easier.
Types of Function 10

Types of function

Functions
Built-in User Defined
defined in
Functions Functions
Modules
Types of Function 11
► Built-in Function:
► These functions are already built in the python library.

► Functions defined in modules:


► These functions defined in particular modules.
► When you want to use these functions in program, you have to import
the corresponding module of that function.

► User Defined Functions:


► The functions those are defined by the user are called user defined
functions.
Built-in Function in Python 12

► These functions are already built in the library of python.


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

► Functions defined in modules:


Functions of math module:
To work with the functions of math module, we must import math
module in
program.
import math
import math 13

SL NO Functio Description Example


n
1 sqrt( ) Returns the square root of a number >>>math.sqrt(49)
7.0
2 ceil( ) Returns the upper integer >>>math.ceil(81.3)
82
3 floor( ) Returns the lower integer >>>math.floor(81.
3)
81
4 pow( ) Calculate the power of a number >>>math.pow(2,3)
8.0
5 fabs( ) Returns the absolute value of a number >>>math.fabs(-
5.6)
5.6
6 exp( ) Returns the e raised to the power i.e. >>>math.exp(3)
e3 20.0855369231876
import random 14

► Function in random module:

► randint( )- function generates the random integer values


including start and end values.
► Syntax: randint(start, end)
► It has two parameters. Both parameters must have integer
values.
► Example:
► import random n=random.randint(3,7)
► *The value of n will be 3 to 7.
► Practice pip 3.1 in Lab Manual - LAB
Importing Modules in a Python 15

Program
► Python provides “import” statement to import modules in a program.
► This import statements can be used in two forms:

To import entire module.


import <module>
1 Ex: import math

► import
To import selected objects from a module.
2 From <module> import <object>
Eg: from math import pi

CS/ Working with Functions


To import Entire Module 16

► Syntax: import <module1>,[module 2], [module 3]….


► Ex: import math
► import time
► import decimal, fraction #To import more than one
module

After importing the module if you want to access the element / function
of the module you need to write like this…
Syntax: <module_name>.<function_name>
import tempconversion
tempconversion.to_centigrade (35.0)

tempconversion.to_fahrenheit (90.2)
CS/ Working with Functions
Alias name to imported module 17

► Syntax: import <module> as <alias_name>


► Example:
import tempconversion as tc
import random as rm
► Now I can use like this…

tc.to_centigrade (33)
rm.randint(10,20)

CS/ Working with Functions


To import selected objects from a 18

module
► Syntax: from <module> import <object_name>
OR

from <module> import


<Object_name>[,<object_name>[,..]
#To import single object
from math import pi
print(pi ) #Now the ‘pi’ is a part of the program
print(math.pi) #Not necessary

CS/ Working with Functions


To import selected objects from a 19

module conti….
► Syntax: from <module> import <object_name>
OR

from <module> import


<Object_name>[,<object_name>[,..]

#To import multiple object


from math import sqrt, pow
print(sqrt )
print(pow)

CS/ Working with Functions


To import All Objects from a 20

Module Using *
► Syntax: from <module> import *

#To import all objects of module


from math import *
From random import *
Note: But this is not advisable . It will create name clash

CS/ Working with Functions


Defining Functions in Python 21

► In a syntax language:
► Item(s) inside the angle brackets < > has to be provided by the programmer.
► Item(s) inside the [ ] is optional. ie: Can be omitted.
► Items / punctuator / word outside the < > and [ ] have to be written as specified
► Syntax:
► def <Function _Name> ([Parameter]): Example 2:
[ ‘’’ Function’s docstring if required ‘’’ ]
def greet ( ):
Statement(s) print(“Functions in
Statement(s) Example 1: Python”)

…… def sum (x,y):


s=x+y
return s
Defining Functions in Python 22
Some More Function Definitions 23

Example 1: Example 2:

def sum_of_3multiples_1 def sum_of_3multiples_2


(n): (n):
s=n*1+n*2+n*3 s=n*1+n*2+n*3
return s print(s)

► Both theses functions are doing the same but example 1 function
is returning the computed value using return statements and
example 2 function is printing the computed values using print()
statement.
Some More Function Definitions 24

Example 3: Example 4:

def area_of_squar (n): def area_of_rectangle (n,m):


return n * n return n * m

Example 5: Example 6:

def perimeter_of_circle def perimeter_of_rectangle


(n): (l,b):
pi=3.14 return 2 * (l + b)
return 2 * pi * r

Note: The above functions will not work until you call it explicitly
Structure of the Python Program 25

Syntax Example

def fun_name ():


statement 1
statement 2

#_ _ Top Level statement here _ _


statement 1
statement 2
statement 3
Flow of Execution in a Function 26

Call
5 1
6
7
2
3
8 4
9
Arguments Vs Parameters 27

Note:
Parameter Arguments
appear in
Function Call
Statement and
Parameters
appear in
function header

Argument
Passing Parameter 28

► Python supports three types of formal arguments/parameters

► 1. Positional Arguments(Required Arguments)


► 2. Default Arguments
► 3. Keyword (or Named )Arguments
Positional Arguments 29

► Required Argument or Mandatory


Arguments
► Note:
► The function call statement must match the
number and order of arguments as defined
in the function definition, that is called
“Positional arguments matching”
Positional Arguments 30

► Example:
► def check (a, b, c):
…..
…..

► The possible function calls for the above function definition


can be:
► Examples:-
► check (x, y, z) #3 Values all ,variables passed
► check (2, x, y) #3 values, variable + literals passed
► check (4, 8, 12) #3 values ,all literals passed
Positional Arguments 31
def check (a, b, c):
…..
…..
Example:
► check (x, y, z) #3 Values all variables passed
► check (2, x, y) #3 values variable + literals passed
► check (4, 8, 12) #3 values all literals passed

In function call 1 In function call 2 In function call 3

▪ a will get value of x ▪ a will get value of 2 ▪ a will get value of 4


▪ b will get value of y ▪ b will get value of x ▪ b will get value of 8
▪ c will get value of z ▪ c will get value of y ▪ c will get value of
12
Default Arguments 32

Third Argument Missing No Argument Missing


Default Arguments 33

► def simple_int(a, b, c=2):


si=(a*b*c/100)
return si
#_ _ Main Program_ _
……….
……….
……….
Note: Non default arguments cannot follow default argument.
What is default parameter? A parameter having default value in
function header is known as default parameter.
Example of Function Header with 34

Default Value
Keyword (Named) Arguments 35

► The default arguments give you the flexibility to specify the default
value for a parameter so that they can be skipped in the function
call,
if needed. However still you cannot change the order of the
arguments
in the function call.

► To have the complete control and flexibility over the values sent as
arguments for the corresponding parameters ,Python offers another
type of arguments: Keyword arguments
► In this we can write any argument in any order provided that you
name the arguments when calling the function.
Keyword (Named) Arguments 36
#function definition
Def interest (prin, time, rate):
si= (prin*time*rate)/100
print(si)
#main program
Interest(prin=2000, time=2,rate=.10)
Interest(rate=.04,prin=2900,time=1)
Interest(4,time=2,rate=.09)

Note: Here only we need to remember the names of formal


parameters. order is not important as we mention the name of
formal parameters while calling.
Using Multiple Argument Type 37

Together
► Rules for combining all three types of arguments:
► 1. an argument list must first contain “Positional
argument” followed by any “keyword argument”
(To remember: PK)
► 2. you can’t specify a value for an argument more
than once.

► Note: Having a positional arguments after


keyword arguments will result into error.
Example:
def interest(prin, cc,time=2,rate=0.09) 38
Returning Value from Functions 39

► Python Function Types:


► 1. Function returning some value (Non void function)
► 2. Function not returning values (Void function)
General Syntax:
► return <value>
► Example:
► return simple_int
► The value being returned can be one of the following:
► 1) a literal 2) a variable 3) an expression
Function Returning Some Value 40

(Non Void Function)


Function Returning Some Value 41

(Non Void Function)


► The returned value of a function should be used in the caller function/ program
inside an expression or a statement.
► Example:
def sum (x, y):
s=x + y
return s

► I can write function call as follows


► Functions returning a value are also known as fruitful
► result = sum(5,10) #The returned value being used in assignment
statement functions
► result = sum (a, b)
► print(sum(5, 10)) #The returned value being used in print
statement
► sum(5, 10) > 20 #The returned value being used in a relational
expression
Function Returning Some Value 42

(Non Void Function)


► Functions returning a value are also known as fruitful
functions
► The return statement ends a function execution even if it
1 is in the middle of the function.
2 5
4

6
What Happened?
3
8
7
Functions Not Returning Any 43

Value (Void Function)


► Note:
► A void function some time called non-fruitful functions.
► It returns a legal empty value of Python. Ie: None.

Example of void function Example of void function

def greet (): def greet1 (name):


print(“Welcom”) print(“Welcome to India”)
Code1 Vs Code2 44

The void functions does not return a value but they return a legal empty
value of Python.
4 Possible Combinations of 45

Functions

1 Non-void function Non-void function


2
without any with some
arguments arguments

3 Void function without Void function with 4


any arguments some arguments
4 Possible Combinations of 46

Functions

def greet2 ():


1 def sum (a,b,c): 2
print(“I love Python”)
print(“Sum is:”,a+b+c)
return
return

def greet (): def greet1 (name):


3 print(“Success”) 4
print(“Hello”, name)
4 Possible Combinations of 47
Functions
Function Returns Multiple Values 48

► 1. The return statement inside a function body should be of the form given
below.
► Syntax: return <value1, value2, value3,……>
► 2. Function call statement can be Type 1 or Type 2
Scope of Variable 49

► Scope of a variable is the portion of a program where the variable


is recognized.
► Parameters and variables defined inside a function is not visible
from outside. Hence, they have a local scope.

► There are two types of scope for variables:


1. Local Scope
2. Global Scope
Local Scope 50

► Variable used inside the function.


► It cannot be accessed outside the function.
► In this scope, the lifetime of variables inside a function is as long
as the function executes.
► They are destroyed once we return from the function. Hence, a
function does not remember the value of a variable from its
previous calls.
Global Scope 51

► Variable declared in the main program(i.e outside the function)


and can be accessed inside as well as outside the function (i.e
anywhere in the program).
► In this scope, Lifetime of a variable is the period throughout
which the variable exists in the memory(till the program ends).
Scope example1 52

► Line 1 : def encountered #stat 1, 2 ignored


► Line 4: def encountered #stat 3, 4 ignored
► Execution of main program start from #stat 4.1
► Creates global variable n1,n2,n3 from #stat 4, 5,
6
► average () is invoked
► Formal arguments x, y, z are created in local
#Stat environments.
4.1
► #stat 3 invoked calcsum ()
► Formal arguments a, b, c are created in local
environments.
► ….ect…
Name Resolution or LEGB Rule 53

Built-in Namespace 4

Global Namespace 3

Enclosing Namespace 2
Local Namespace
1
Case-I: variable in global scope 54

but not in local scope


Case-II 55
Case-III 56
Use of Global Variable 57

► If you want to use global variable inside local scope.

Without changing its value.


(This case no issues with ‘LEGB’)
Refer Case-I

► Use of Global Variable


Change the value but without
creating local variable

► Note: Once a variable is declared as a global in a function,


you can’t undo the statement
Use of Global Variable 58

Global variable

Result of print statement inside


state_1 (), value of global tiger is
printed (which is modified into 15)

Result of print statement inside main


program, thus the value of global
tiger is updated and printed as 15.
Passing an Immutable Type Value to 59
a Function
Passing an mutable Type Value to a 60
Function
Passing an mutable Type Value to a 61
Function
Is there any case, when we pass 62

Mutable Data type and changes does


not reflect back?

Yes
Example 1:Parameter is assigned a 63
different data type value
64
Example 2: If a parameter is
assigned a new name
65

Thank you

You might also like