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

Unit - 1 Functions

The document provides an overview of functions in Python, detailing their definition, types (library, module-defined, and user-defined), and syntax. It explains parameters, including formal, actual, and default parameters, as well as the scope and lifetime of variables. Additionally, it covers the mutability of data types and includes examples and questions for better understanding.

Uploaded by

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

Unit - 1 Functions

The document provides an overview of functions in Python, detailing their definition, types (library, module-defined, and user-defined), and syntax. It explains parameters, including formal, actual, and default parameters, as well as the scope and lifetime of variables. Additionally, it covers the mutability of data types and includes examples and questions for better understanding.

Uploaded by

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

KIRORIMAL PUBLIC SCHOOL, KHEWRA, SONEPAT

SESSION – (2020-21)
CLASS – XII
SUBJECT – COMPUTER SCIENCE (083)
CHAPTER-3 FUNCTIONS IN PYTHON

Definition: Functions are the subprograms that perform specific task. Functions are the
small modules.
A function is a subprogram that acts on data and often returns a value.

Types of Functions:
There are three types of functions in python:
Library Functions: 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.

Library Functions in Python:


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
S. No. Function Description Example
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. e3 >>>math.exp(3)
20.085536923187668

Prepared By:
Ms. Swati Chawla
PGT Computer Page 1
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.

User defined functions:


The syntax to define a function is:
def function-name ( parameters) :
#statement(s)
Where:
 Keyword def marks the start of function header.
 A function name to uniquely identify it. Function naming follows the same rules
of writing identifiers in Python.
 Parameters (arguments) through which we pass values to a function. They are
optional.
 A colon (:) to mark the end of function header.
 One or more valid python statements that make up the function body. Statements
must have same indentation level.
 An optional return statement to return a value from the function.
Example:
def display(name):
print("Hello " + name + " How are you?")

Function Parameters:
A functions has two types of parameters:
Formal Parameter: Formal parameters are written in the function prototype and
function header of the definition. Formal parameters are local variables which are
assigned values from the arguments when the function is called.
Actual Parameter: When a function is called, the values that are passed in the call are
called actual parameters. At the time of the call, each actual parameter is assigned to
the corresponding formal parameter in the function definition.
Default Parameters: Python allows function arguments to have default values. If the
function is called without the argument, the argument gets its default value.
Example :
def ADD(x, y): #Defining a function and x and y are formal parameters
z=x+y

Prepared By:
Ms. Swati Chawla
PGT Computer Page 2
print("Sum = ", z)
a=float(input("Enter first number: " ))
b=float(input("Enter second number: " ))
ADD(a,b) #Calling the function by passing actual parameters
In the above example, x and y are formal parameters. a and b are actual parameters.
Imp:
Difference between Arguments and Parameters

Arguments Parameters
Values being passed are called Values being received are called
arguments. parameters.

Arguments appear in the function call Parameters appears in Function header


statement. or function definition.
Arguments are also known as Actual Parameters are also known as Formal
Arguments and Actual Parameters. Parameters and Formal Arguments.

Example :
In the below example, a and b are parameters.
x and y are arguments.

Calling the function:


Once we have defined a function, we can call it from another function, program or even
the Python prompt. To call a function we simply type the function name with
appropriate parameters.

Prepared By:
Ms. Swati Chawla
PGT Computer Page 3
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0

The return statement:


The return statement is used to exit a function and go back to the place from where it
was called.
There are two types of functions according to return statement:
a. Function returning some value
b. Function not returning any value
a. Function returning some value :
Syntax:
return expression/value
Example-1: Function returning one value
def my_function(x):
return 5 * x
Example-2 Function returning multiple values:
def sum(a,b,c):
return a+5, b+4, c+7
S=sum(2,3,4) # S will store the returned values as a tuple
print(S)
OUTPUT: (7, 7, 11)
Example-3: Storing the returned values separately:
def sum(a,b,c):
return a+5, b+4, c+7
s1, s2, s3=sum(2, 3, 4) # storing the values separately
print(s1, s2, s3)
OUTPUT:
7 7 11
b. Function not returning any value : The function that performs some operations but
does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
OUTPUT: Hello
None

Prepared By:
Ms. Swati Chawla
PGT Computer Page 4
TYPES OF PARAMETERS

1. Positional Parameters
• Positional arguments are arguments passed to a function in correct positional
order. If we change their order, then the result will be changed. If we change
the number of arguments passed, then it shall result in an error.
• When the functions call statement must match the number and order of
arguments as defined in the function definition this is called positional
argument matching.

E.g. Here we have defined a function demo() with two parameters name and age,
which means this function can accept two arguments while we are calling it.
def demo(name,age):
print(name + " is " + age + " years old")
demo("Mohan",20) # calling the function

2. Default Parameters
• Default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument.
• If you are not passing any value, then only default values will be considered.
• Non default arguments cannot follow default arguments.
• In a function header, any parameter cannot have a default value unless
all parameters appearing on its right have their default values.

def demo(name, age = "30"):


"""
This function displays the
name and age of a person

If age is not provided,


it's default value 30 would
be displayed.
"""

print(name + " is " + age + " years old")

demo("Steve")
demo("Lucy", "20")
demo("Bucky", "40")

Prepared By:
Ms. Swati Chawla
PGT Computer Page 5
Output:

Scope and Lifetime of variables:


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:
i) Local Scope
ii) Global Scope
Local Scope: 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: Variable can be accessed outside the function. In this scope, Lifetime of
a variable is the period throughout which the variable exits in the memory.

Example:
def my_func():
x = 10 #Local Variable
print("Value inside function:",x)
x = 20 #Global Variable
my_func()
print("Value outside function:",x)

OUTPUT:
Value inside function: 10
Value outside function: 20

Here, we can see that the value of x is 20 initially. Even though the function
my_func()changed the value of x to 10, it did not affect the value outside the function.
This is because the variable x inside the function is different (local to the function)
from the one outside. Although they have same names, they are two different variables
with different scope.
On the other hand, variables outside of the function are visible from inside. They have
a global scope. We can read these values from inside the function but cannot change
(write) them. In order to modify the value of variables outside
the function, they must be declared as global variables using the keyword global.

Prepared By:
Ms. Swati Chawla
PGT Computer Page 6
What if you want to use the global variable inside local scope?

To understand the concept, consider the following code:


def state1( ) :
tigers=15
print(tigers)
tigers=95
print(tigers)
state1( )
print(tigers)

Output:
95 --- > Result of print( )function inside state1( ), value of local variable tigers is printed.
15
95 --- > Result of print( )function inside main program, value of global variable tigers is
printed.

Now the question arises, What if you want to use the global variable inside local scope.

To tell a function, that for a particular name do not create a local variable but use global
variable instead, we need to write:

global <variable name>

For example, in above code, if you want functions sate1( ) to work with global variable
tigers, you need to add global statement for tigers variable to it as shown below:

def state1( ) :
global tigers
tigers=15
print(tigers)
tigers=95
print(tigers)
state1( )
print(tigers)

Output:
95
15 --- > Result of print( )function inside state1( ), value of global variable tigers is printed.
15 --- > Result of print( )function inside main program, value of global variable
tigers(which is now 15) is printed.

Prepared By:
Ms. Swati Chawla
PGT Computer Page 7
Note:
If any program there are two variables with same name one is local and one is global
to use the global variable in a function we have to use the global keyword with
variable name.
IMP.
Difference between Local Variable and Local variable
Local Variable Global Variable
It is a variable which is declared within a It is a variable which is declared outside
function or within a block. all the functions.
It is accessible only within a It is accessible throughout the program.
function/block, in which it is declared.

For example in the following code, x, xCubed are global variables and n and cn are
local variables.

def cube(n):
cn = n*n*n
return cn
x = 10
xCubed = cube (x)
print(x, “cubed is”, xCubed)

Passing ARRAYS /LISTS to Function


Arrays in basic Python, are actually list that can contain mixed data types. However,
lists are better than arrays, as they may hold elements of several data types where as in
case of arrays, the element should be of same data type only and hence lists are much
more flexible and faster than arrays. A list can be passed as an argument to a function
similar to passing normal variable as an argument to a function.

Prepared By:
Ms. Swati Chawla
PGT Computer Page 8
MUTTABLE AND IMMUTABLE PROPERTIES OF DATA OBJECTS
Depending upon the mutability or immutability of the data type, a variable behaves
differently.
That is, if a variable is referring to an immutable type that any change in its value will
also change the memory address it is referring to but, if a variable is referring to
mutable type, and then any change in the value of mutable type will not change the
memory address of the variable.
When you pass values through arguments and parameters to a function,
mutability/immutability also plays an important role there.
Example: 1
Passing an Immutable Type value to a function.
def myFunc1(a):
print("\tInside myFunc1()")
print("\tValue received in 'a' as",a)
a=a+2
print("\tValue of 'a' now changes to",a)
print("\treturning from myFunc1()")

num=3
print("Calling myFunc1()by passing 'num' with values",num)
myFunc1(num)
print("Back from myFunc1(). Value of 'num' is",num)

Prepared By:
Ms. Swati Chawla
PGT Computer Page 9
Output

Calling myFunc1()by passing 'num' with values 3 The value got


Inside myFunc1() changed from 3 to 5
Value received in 'a' as 3 inside a function but
Value of 'a' now changes to 5 not got reflected
outside the function.
returning from myFunc1()
Back from myFunc1(). Value of 'num' is 3
As you can see that the function my myFunc1( ) received the passed value in
parameter and then change the value of a by performing some operation on it. Inside
myFunc1( ), the value of a got changed but after returning from myFunc1( ), the
original passed variable name remains unchanged.

Example: 2
Passing a Mutable Type value to a function – Making Changes in place
def myFunc2(myList):
print("\n\tInside CALLED Function now ")
print("\tList received :",myList)
myList[0]+=2
print("\tList within called function, after changes:",myList)
print("\treturning from myFunc1()")

List1=[1]
print("List before function call:",List1)
myFunc2(List1)
print("List before function call:",List1)

Output
List before function call: [1]

Inside CALLED Function now


List received : [1]
List within called function, after changes: [3]
returning from myFunc1() The value got changed
List before function call: [3] from [1] to [3] inside
function and change got
reflected back also.

Prepared By:
Ms. Swati Chawla
PGT Computer Page 10
Very Short Answer Type Questions (1-Mark)
Q1. What is default parameter?
Ans: A parameter having default value in the function header is known as a default
parameter.
Q2. Can a function return multiple values in python?
Ans: YES.
Short Answer Type Questions (2-Marks)
Q1. Rewrite the correct code after removing the errors: -
def SI(p,t=2,r):
return (p*r*t)/100
Ans: -
def SI(p, r, t=2):
return(p*r*t)/100
Q2. Consider the following function headers. Identify the correct statement: -
1) def correct(a=1,b=2,c):
2) def correct(a=1,b,c=3):
3) def correct(a=1,b=2,c=3):
4) def correct(a=1,b,c):
Ans: - 3) def correct(a=1,b=2,c=3)
Q3.What will be the output of the following code?
a=1
def f():
a=10
print(a)
Ans: The code will print 1 to the console.
Q 4. What is the difference between Actual and Formal parameters?
Q 5. What is the difference between Local and Global variables?

Important Questions from this chapter.


1 Theoretical Question ( 1 or 2 marks)
1 Error Finding Question ( 2 marks)
1 or 2 Output based Questions.(1 or 2 or 3 marks)
Write a function definition of any computational based problem.
(2 or 3 marks)

Prepared By:
Ms. Swati Chawla
PGT Computer Page 11

You might also like