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

Functions

D d yfu f ddyfyufd f f yf hffhyf f Ff f f

Uploaded by

vsahu7281
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Functions

D d yfu f ddyfyufd f f yf hffhyf f Ff f f

Uploaded by

vsahu7281
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Class - XII (Python) (Working with Functions) Page 1 of 6

Working with Functions


Functions: A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a
function. A function can return data as a result.

Creating a Function:
In Python a function is defined using the def keyword: Ex:
def my_function():
print("Hello from a function")

Calling/Invoking a Function:
To call a function, use the function name followed by parenthesis:
Ex:
def my_function(): print("Hello Output:
from a function")
Hello from a function
my_function()

Some more function definition: def


cube(x):
res=x**3 # cube of value in x
return res # return the computed value
We can call above function in various ways:
a. cube(4)
b. num=4
cube(num)
c. num=int(input(“Enter a Number:”))
cube(num)
d. print(cube(4))
e. doubleofcube=2*cube(4)

Python function Types:


1. Built-in functions: These are pre-defined functions and are always available for use. Ex:
len(), type(), int(), input() etc.
2. Functions defined in Modules: These are pre-defined functions in particular modules and can only
be used when the corresponding modules is imported.
Ex: To use sin() function we have to import module math
3. User defined Functions: These are defined by the programmer. We can create our own functions.
Defining Functions in Python:

Syntax:
def<function name>([parameters]):
statement1
statement2
. Function body
.
Statements

Example:1 Example:2 Example:3 Example:3


def sum( ): def sum(x, y): def sum(x, y): def sum():
s=2+3 s=x+y print(s) s=x+y s=2+3
print(s) sum(2,3) return s return s
sum() rs=sum(2,3) rs=sum()
output: 5 print(rs) output: print(rs)
output: 5 5 output: 5
Class - XII (Python) (Working with Functions) Page 2 of 6
Note: Generally python function definition is given at top (before calling it).
1. No Passing Value, No return Value
2. Passing Value, No Return Value
3. Passing Value, But Return Value
4. No Passing Value, But Return Value

Structure of a Python Program: The python interpreter starts the execution of a program/script from top-
level statements. The top level statements are part of the main program.
Internally Python gives a special name to top-level statements as _main_.
The structure of a python program is generally like the one shown below:
def function1():
.
.
def function2():
.
.
def function3():
.
.
# top-level statements here
Statement1 comes in _main_
Statement2
.
.
Flow of Execution in a Function call: Flow of execution refers to the order in which statements are executed during a
program run.

An execution frame contains


1. Some internal information(used for debugging)
2. Name of the function
3. Values passed to function
4. Variables created within function
5. Information about the next instruction to be executed
Ex:
def sum(x, y):
s=x+y
return s
rs=sum(2,3)
print(rs)

output: 5
Arguments and Parameters: We can pass values to functions. For this we define variables to receive values in
function definition and we send values via a function call statement.
For ex:
def sum(x, y): #Here x & y are parameters or Formal parameter
s=x+y
print(s)
sum(2,3) # Here 2,3 are arguments or Actual parameter

output: 5
Arguments in Python can be one of the these value types:
a. Literal b. Variables c. expressions

Following are some valid function call statements:

a. sum(2, 3) #both literal arguments


b. a=2
Class - XII (Python) (Working with Functions) Page 3 of 6
sum(a, 3) #One variable and one literal
c. a=2
sum(a, a+1) #One variable and one expression argument
Passing Parameters: If a function header has three parameters named in its header then the function call should also pass three
values. Other than this, Python also provides some other ways of sending and matching arguments and parameters. Python
supports three types of formal arguments/parameters:
1. Positional arguments(Required arguments)
2. Default arguments
3. Keyword (or named) arguments
1. Positional arguments(Required arguments): When we call statements must match the number and order of
arguments as defined in the function definition, this is called the positional argument matching. Here no value can be
skipped. We cannot assign value of first argument to third parameter.

def sum(x, y, z):


s=x+y+z print(s)

sum(2, 3, 4)

2. Default arguments:
a. When we define a function, we can specify a default value for each of the last parameters. This value will be
used if the corresponding argument is left blank when calling to the function.
b. If a value for that parameter is not passed when the function is called, the default given value is used, but if a
value is specified, this default value is ignored and the passed value is used instead.
For Ex:
def sum(x, y, z=5):
s=x+y+z print(s)
sum(2, 3, 4) #here value z will be receive value 4
sum(2, 3) #here value z will be 5 default value
We cannot assign default value for middle parameter. We have to start from right most then move to left side for
assigning default values.
def sum(x, y=3, z): #Invalid Function header definition
def sum(x=2, y=3, z): #Invalid Function header definition
def sum(x, y=3, z=4): #Valid Function header definition
3. Keyword (or named) arguments: Keyword arguments are the named arguments with assigned values being passed in
the function call statement. Python offers a way of writing function calls where we can write any argument in any
order provided we name the arguments when calling the function as bellow:

Ex:1 Ex:2 Ex:3


def sum(x, y, z): def sum(x, y, z): def sum(x, y, z):
…… …… ……
……. ……. …….
sum(x=2, y=3,z=4) sum(y=2, z=3,x=4) sum(z=2, y=3,x=4)

Using multiple Argument type together: Python allows us to combine multiple argument types in a function call.
Consider the following ex:
def sum(x, y=2, z=5):
s=x+y+z
print(s)
sum(2, z=3)
In the above example first argument value(2) is representing a positional argument as it will b assigned to first parameter
on the basis of its position. The second argument (z=3) is representing keyword argument or named argument. The
above function call also skips an argument(y) for which a default value is defined in the function header.
Rules for combination all three types of arguments:
1. An argument list must first contain positional (required) arguments followed by any keyword
argument.
2. Keyword arguments should be taken from the required arguments preferably.
3. We cannot specify a value for an argument more than once.
Class - XII (Python) (Working with Functions) Page 4 of 6

For Ex:
sum(2, z=3) #valid
sum(z=3, 2) #Invalid keyword argument before positional arguments
sum(3, x=2, 3) #Invalid multiple values provided for parameter x

Returning Values from Function: Functions in Python may or may not return a value. There can be broadly two types of
functions in Python:
1. Function returning some value(non-void functions)
2. Function not returning any value (void functions)

1. Function returning some value(non-void functions): The functions that return some computed result in terms of a
value, fall in this category. The computed value is returned using return statement as per syntax:
Syntax:
return<value>
The value being returned can be one of the following:
a. A Literal b. A variable c. An expression
For example following are some valid return statements:
return 5 #return literal
return 6+5 #return expression involving literal
return a #return variable
return a**3 #return expression involving variable and literal
return a*b/c #return expression
Ex:
def sum(x, y):
s=x+y
return s
rs=sum(2,3)
print(rs)
output: 5
2. Function not returning any value (void functions): The functions that perform some action or do some work but
do not return any computed value or final value to the caller and called void functions. A void function may or may
not have a return statement. If a void function has a return statement then it takes the following form:
return
That is, keyword return without any value or expression.

Ex:
def sum( ):
s=2+3
print(s)
return # Here return is optional
sum()

output: 5

A void function(sometimes called non-fruitful functions) returns legal empty value of Python i.e None to its caller.

Ex: 1 Ex:2 Ex:3


def sum( ): def sum( ): def sum( ):
s=2+3 s=2+3 s=2+3
print(s) print(s) print(s)
return a= sum() return “Hello”
a= sum() print(a) a= sum()
print(a) print(a)
output: 5 output: 5
None None output: 5
(If Not writing return also Hello
return None)
Class - XII (Python) (Working with Functions) Page 5 of 6
Python can have following four possible combinations of functions:
a. non-void functions without any arguments
b. non-void functions with some arguments
c. void functions without any arguments
d. void functions with some arguments

Returning Multiple Values: Python allows us return more than one value from a function. To return multiple values from
a function we have to ensure following things:

Ex1:
def squared(x,y,z):
return x*x, y*y, z*z
t=squared(2,3,4) #returned value will be stored in form of tuple t=(4,9,16)
print(t) # it will print (4,9,16)
Ex2:

def squared(x,y,z):
return x*x, y*y, z*z
v1,v2,v3=squared(2,3,4) #returned value will be stored in v1,v2,v3 respectively
print(v1,v2,v3) # it will print: 4 9 16

Scope of Variables: A variable is only available from inside the region it is created. This is called scope. Python have two
types of variables scope:
1. Local Scope: A variable created inside a function belongs to the local scope of that function, and can only be used
inside that function.
For Ex:
def sum():
s=2+3 # Here ‘s’ is local variable for function sum()
print(s) #local scope of variable ‘s’ which can be used inside sum() function only
sum()
print(s) # Produces error because variable ‘s’ can not be used here, its scope is only inside
sum() function

Output:
5

2. Global Scope: A variable created in the main body of the Python code is a global variable and belongs to the
global scope. Global variables are available from within any scope, global and local.
For Ex:
x=3
def sum():
s=2+3
print(s) #local scope of variable ‘s’ which can be used inside sum() function only
print(x) #Can be used because variable ‘x’ is global variable which can be used anywhere
sum()
print(x) # Can be used because x is global variable

Output:
5
3
3
Class - XII (Python) (Working with Functions) Page 6 of 6

You might also like