Working with Functions in Python Class 12 Notes

Teachers and Examiners (CBSESkillEduction) collaborated to create the Working with Functions in Python Class 12 Notes. All the important Information are taken from the NCERT Textbook Computer Science (083) class 12.

Working with Functions in Python Class 12 Notes

Define functions in Python

A function is a block of code that only executes when called. You can supply parameters—data—to a function. As a result, a function may return data. You can define function using def keyword.

Syntax for defining function –

def <function name> (<parameters>) :
<statement 1>
<statement 2>
.
.
.

Flow of execution in a function call

The flow of execution refers to the order in which statements are executed during a program run. The program’s opening statement is where execution always starts. The statements are carried out one at a time, in ascending order. Although the order in which a programme runs is unaffected by function declarations, keep in mind that statements inside a function are not performed until the function is called.
Example –
Defining function
def sum(x, y) :

Calling function
sum(a,b)

Where a, b are the values being passed to the function sum().

Passing parameters in function

Information that is supplied into a function is referred to as a parameter or argument. The terms parameter and argument can both be used to refer to the same thing. The function name is followed by parenthesis that list the arguments. Simply separate each argument with a comma to add as many as you like.

Python supports three types of formal arguments/parameters
1. Positional arguments – Arguments that must be presented in the right order are known as positional arguments. When calling a function, the first positional argument must always be listed first and the second will be in second.

2. Default arguments – If no argument value is given during the function call, default values will be passed in the function.

3. Keyword arguments – When values are supplied into a function, they are known as keyword arguments . The assignment operator, =, and a parameter come before a keyword argument.

Using multiple argument types together

Python allows you to combine multiple argument types in a function call. Consider the following function call statement that is using both positional arguments and keyword arguments.

interest(5000, time = 5)

Rules for combining all three types of arguments

  • An argument list must first contain positional arguments followed by any keyword argument.
  • Keyword arguments should be taken from the required arguments preferably.
  • You cannot specify a value for an argument more than once.

Returning values from functions

Functions in Python may or may not return a value. You already known about it. There can be broadly two types of functions in python.
a. Function returning some value (non-void functions)
b. Function not returning any value (void functions)

Composition

A concept that represents a relationship is composition. Composition in general refers to using an expression as part of a larger expression; or a statement as a part of larger statement. In functions context, we can understand composition as follows –

Example

An arithmetic expression
greater((4+5), (3+4))
A logical expression
test(a or b)
A function call (function composition)
int(str(52))
int(float(“52.5”)*2)
int(str(52) + str(10))

Scope of Variable

The rules that determine which areas of the programme a specific piece of code or data item would be known as and be accessible within are known as a language’s scope rules.

There are two types of scopes in Python.

  1. Global Scope
  2. Local Scope

Global Scope – A name defined in a program’s top-level (_main) segment is said to have a global scope and be usable throughout the entire programme and all blocks contained therein.

Local Scope – Local scope describes a name that is declared in the body of a function. It can only be utilized in this function and the other blocks that are placed beneath it. The formal arguments’ names also have a local scope.

Mutable/Immutable Properties of Passed Data Objects

Type of Function

There are two types of function in python.

  1. User – Define Function
  2. Built – in – Function

The Python language includes built-in functions such as dir, len, and abs. The def keyword is used to create functions that are user specified.

Working with Functions in Python Class 12 Notes

User – Define Function

User-defined functions are the fundamental building block of any programme and are essential for modularity and code reuse because they allow programmers to write their own function with function name that the computer can use.

Creating User Defined Function

A function definition begins with def (short for define). The syntax for creating a user defined function is as follows –

Syntax – 

def function_name(parameter1, parameter2, …) :
statement_1
statement_2
statement_3
….

  • The items enclosed in “[ ]” are called parameters and they are optional. Hence, a function may or may not have parameters. Also, a function may or may not return a value.
  • Function header always ends with a colon (:).
  • Function name should be unique. Rules for naming identifiers also applies for function naming.
  • The statements outside the function indentation are not considered as part of the function.

Q. Write a user defined function to add 2 numbers and display their sum.

#Program
#Function to add two numbers
def addnum():
fnum = int(input(“Enter first number: “))
snum = int(input(“Enter second number: “))
sum = fnum + snum
print(“The sum of “,fnum,”and “,snum,”is “,sum)
#function call
addnum()

Output:
Enter first number: 5
Enter second number: 6
The sum of 5 and 6 is 11

Working with Functions in Python Class 12 Notes

Arguments and Parameters

User-defined function could potentially take values when it is called. A value received in the matching parameter specified in the function header and sent to the function as an argument is known as an argument.

Q. Write a program using a user defined function that displays sum of first n natural numbers, where n is passed as an argument.

#Program
#Program to find the sum of first n natural numbers
def sumSquares(n):
sum = 0
for i in range(1,n+1):
sum = sum + i
print(“The sum of first”,n,”natural numbers is: “,sum)
num = int(input(“Enter the value for n: “))
sumSquares(num) #function call

Q. Write a program using a user defined function myMean() to calculate the mean of floating values stored in a list.

#Program 7-6
#Function to calculate mean
def myMean(myList):
total = 0
count = 0
for i in myList:
total = total + i
count = count + 1
mean = total/count
print(“The calculated mean is:”,mean)
myList = [1.3,2.4,3.5,6.9]
myMean(myList)

Output:
The calculated mean is: 3.5250000000000004

Q. Write a program using a user defined function calcFact() to calculate and display the factorial of a number num passed as an argument.

#Program 7-7
#Function to calculate factorial
def calcFact(num):
fact = 1
for i in range(num,0,-1):
fact = fact * i
print(“Factorial of”,num,”is”,fact)
num = int(input(“Enter the number: “))
calcFact(num)

Output:
Enter the number: 5
Factorial of 5 is 120

String as Parameters

Some programmes may require the user to supply string values as an argument.

Working with Functions in Python Class 12 Notes

Q. Write a program using a user defined function that accepts the first name and lastname as arguments, concatenate them to get full name and displays the output as:

#Program
#Function to display full name
def fullname(first,last):
fullname = first + ” ” + last
print(“Hello”,fullname)
first = input(“Enter first name: “)
last = input(“Enter last name: “)
fullname(first,last)

Output:
Enter first name: Gyan
Enter last name: Vardhan
Hello Gyan Vardhan

Working with Functions in Python Class 12 Notes

Default Parameter

The argument can be given a default value in Python. When a function call doesn’t have its appropriate argument, a default value is chosen in advance and given to the parameter.

Q. Write a program that accepts numerator and denominator of a fractional number and calls a user defined function mixedFraction() when the fraction formed is not a proper fraction. The default value of denominator is 1. The function displays a mixed fraction only if the fraction formed by the parameters does not evaluate to a whole number.

#Program
#Function to display mixed fraction for an improper fraction
def mixedFraction(num,deno = 1):
     remainder = num % deno
     if remainder!= 0:
         quotient = int(num/deno)
         print(“The mixed fraction=”, quotient,”(“,remainder, “/”,deno,”)”)
     else:
         print(“The given fraction evaluates to a whole number”)
num = int(input(“Enter the numerator: “))
deno = int(input(“Enter the denominator: “))
print(“You entered:”,num,”/”,deno)
if num > deno:
     mixedFraction(num,deno)
else:
     print(“It is a proper fraction”)

Output:
Enter the numerator: 17
Enter the denominator: 2
You entered: 17 / 2
The mixed fraction = 8 ( 1 / 2 )

Working with Functions in Python Class 12 Notes

Functions Returning Value

The function’s values are returned using the return statement. A function that has finished its duty will return a value to the script or function that called it.

The return statement does the following –

  • returns the control to the calling function.
  • return value(s) or None.

Q. Write a program using user defined function calcPow() that accepts base and exponent as arguments and returns the value Baseexponent where Base and exponent are integers.

#Program
#Function to calculate and display base raised to the power exponent
def calcpow(number,power):
result = 1
for i in range(1,power+1):
result = result * number
return result
base = int(input(“Enter the value for the Base: “))
expo = int(input(“Enter the value for the Exponent: “))
answer = calcpow(base,expo)
print(base,”raised to the power”,expo,”is”,answer)

Output:
Enter the value for the Base: 5
Enter the value for the Exponent: 4
5 raised to the power 4 is 625

Flow of Execution

The first statement in a programme is where the Python interpreter begins to carry out the instructions. As they read from top to bottom, the statements are carried out one at a time.
The statements contained in a function definition are not executed by the interpreter until the function is called.

Scope of a Variable

An internal function variable can’t be accessed from the outside. There is a well defined accessibility for each variable. The scope of a variable is the area of the programme that the variable is accessible from. A variable may fall under either of the two scopes listed below:
A variable with a global scope is referred to as a global variable, whereas one with a local scope is referred to as a local variable.

Global Variable – A variable that is defined in Python outside of any function or block is referred to as a global variable. It is accessible from any functions defined afterward.

Local Variable – A local variable is one that is declared inside any function or block. Only the function or block where it is defined can access it.

Working with Functions in Python Class 12 Notes

Built-in functions

The pre-made Python functions that are widely used in programmes are known as built-in functions. Let’s examine the subsequent Python programme –

#Program to calculate square of a number
a = int(input(“Enter a number: “)
b = a * a
print(” The square of “,a ,”is”, b)

In the programme mentioned above, the built-in functions input(), int(), and print() are used. The Python interpreter already defines the set of instructions that must be followed in order to use these built-in functions.

built in functions

Commonly used built-in functions

Function
Syntax
ArgumentsReturnsExample
Output
abs(x)x may be an integer or floating point numberAbsolute value of xabs(4)
4
abs(-5.7)
5.7
divmod(x,y)x and y are integersA tuple: (quotient, remainder)divmod(7,2)
(3, 1)
divmod(7.5,2)
(3.0, 1.5)
divmod(-7,2)
(-4, 1)
max(sequence)
or
max(x,y,z,…)
x,y,z,.. may be integer or floating point numberLargest number in the sequence/ largest of two or more argumentsmax([1,2,3,4])
4
max(“Sincerity”)
‘y’ #Based on ASCII value
max(23,4,56)
56
min(sequence)
or
min(x,y,z,…)
x, y, z,.. may be integer or floating point numberSmallest number in the sequence/ smallest of two or more argumentsmin([1,2,3,4])
1
min(“Sincerity”)
‘S’
Uppercase letters have
lower ASCII values than
lowercase letters.
min(23,4,56)
4
pow(x,y[,z])x, y, z may be integer or floating point numberxy (x raised to the power y)
if z is provided, then: (xy ) % z
pow(5,2)
25.0
pow(5.3,2.2)
39.2
pow(5,2,4)
1
sum(x[,num])x is a numeric
sequence and num
is an optional
argument
Sum of all the
elements in the
sequence from left to
right.
if given parameter,
num is added to the
sum
sum([2,4,7,3])
16
sum([2,4,7,3],3)
19
sum((52,8,4,2))
66
len(x)x can be a sequence
or a dictionary
Count of elements
in x
len(“Patience”)
8
len([12,34,98])
3
len((9,45))
2 >>>len({1:”Anuj”,2:”Razia”,
3:”Gurpreet”,4:”Sandra”})
4

Working with Functions in Python Class 12 Notes

Module

The Python standard library includes a number of modules. A module is a collection of functions, whereas a function is a collection of instructions. suppose we have created some functions in a program and we want to
reuse them in another program. In that case, we can save those functions under a module and reuse them. A module is created as a python (.py) file containing a collection of function definitions.

To use a module, we need to import the module. Once we import a module, we can directly use all the functions
of that module. The syntax of import statement is as follows:

import modulename1 [,modulename2, …]

Built-in Modules

Let’s examine a few widely used modules and the functions that are contained in such modules:

Module name : math
Function
Syntax
ArgumentsReturnsExample
Output
math.ceil(x)x may be an integer or floating point numberceiling value of xmath.ceil(-9.7)
-9
math.ceil (9.7)
10
math.ceil(9)
9
math.floor(x)x may be an integer or floating point numberfloor value of xmath.floor(-4.5)
-5
math.floor(4.5)
4
math.floor(4)
4
math.fabs(x)x may be an integer or floating point numberabsolute value of xmath.fabs(6.7)
6.7
math.fabs(-6.7)
6.7
math.fabs(-4)
4.0
math.factorial(x)x is a positive integerfactorial of xmath.factorial(5)
120
math.fmod(x,y)x and y may be an
integer or floating point
number
x % y with sign of xmath.fmod(4,4.9)
4.0
math.fmod(4.9,4.9)
0.0
math.fmod(-4.9,2.5)
-2.4
math.fmod(4.9,-4.9)
0.0
math.gcd(x,y)x, y are positive integersgcd (greatest common divisor) of x and ymath.gcd(10,2)
2
math.pow(x,y)x, y may be an integer or
floating point number
xy (x raised to the power y)math.pow(3,2)
9.0
math.pow(4,2.5)
32.0
math.pow(6.5,2)
42.25
math.pow(5.5,3.2)
233.97
math.sqrt(x)x may be a positive
integer or floating point
number
square root of xmath.sqrt(144)
12.0
math.sqrt(.64)
0.8
math.sin(x)x may be an integer or
floating point number in
radians
sine of x in radiansmath.sin(0)
0
math.sin(6)
-0.279

Working with Functions in Python Class 12 Notes

Module name : random
Function
Syntax
ArgumentReturnExample
Output
random.random()No argument (void)Random Real Number (float) in the range 0.0 to 1.0random.random()
0.65333522
random.randint(x,y)x, y are integers such that x <= yRandom integer between x and yrandom.randint(3,7)
4
random.randint(-3,5)
1
random.randint(-5,-3)
-5.0
random.randrange(y)y is a positive integer signifying the stop valueRandom integer between 0 and yrandom.randrange(5)
4
random.randrange(x,y)x and y are positive integers signifying the start and stop valueRandom integer between x and yrandom.randrange(2,7)
2

Working with Functions in Python Class 12 Notes

Module name : statistics
Function SyntaxArgumentReturnExample
Output
statistics.mean(x)x is a numeric sequencearithmetic meanstatistics.mean([11,24,32,45,51])
32.6
statistics.median(x)x is a numeric sequencemedian (middle value) of xstatistics.median([11,24,32,45,51])
32
statistics.mode(x)x is a sequencemode (the most repeated value)statistics.mode([11,24,11,45,11])
11
statistics.mode((“red”,”blue”,”red”))
‘red’
error: Content is protected !!