0% found this document useful (0 votes)
75 views50 pages

CS (XII) Ch-2 Functions Notes

Notes of Ch 2 functions, Computer Science with Python 2021-2022, class 12th

Uploaded by

Harshit Sharda
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)
75 views50 pages

CS (XII) Ch-2 Functions Notes

Notes of Ch 2 functions, Computer Science with Python 2021-2022, class 12th

Uploaded by

Harshit Sharda
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/ 50

Ch-2 Functions

Introduction
As a problem becomes complex, it becomes
difficult and cumbersome for a programmer to
keep track of the data and control statements in
the whole program.
Introduction
• Python provides the feature to divide a large
program into different smaller modules. These
modules are known as functions.

• Functions provides a systematic way of problem


solving by dividing the problem into several sub
problems.
Function Defination

•A function is a group of statements that


exists with in a program for the purpose
of performing a specific task.
There are three types of functions
1. Built-in

2. Modules

3. User Defined
Built In Functions:
• These are predefined functions that are already
available in python.

• It provides efficiency and structure to programming


language.
A) Type conversion functions: It convert
values from one type to another.
(i) int(): It takes any value and converts it into integer. It chops off the
fraction part.

(ii) Str(): It convert its argument into string.

(iii) Float(): It converts integers and strings into floating point numbers.
Today class : we will discuss
• Recap
• Different built in functions: ( Input(), Eval(),Min() and
max(),Abs(),Type(),Len(),Round(),Range())

• Modules
• Practical Demo
B) Input function
• It enables us to accept an input string from the user without evaluating
its value. It provides the most common way to gather input from the
keyboard.
• It is used to read input text from the user until it encounters a new line.
• Syntax:
name=input(‘enter a name’)
print(‘welcome’, name + “ pleasure to meet you”)
WAP to calculate the selling price of an item.
C) Eval() function
• It is used to evaluate the value of a string. It takes a string as an
argument, evaluates this string as a number, return the numeric result.
• x= eval (‘45+10’)
• print(x)
D) Min() and Max() function
• The max() function takes two or more arguments and return the largest
one.

• max(9,12,6,15)

• The min() function takes two or more arguments and return the
minimum value.

• min(7,26,0,4)
E) Abs function
• It returns the absolute value of single number. It takes
an integer or float number as a argument and always
returns a positive value.

• abs(-50) returns 50
• abs(-30.6) returns 30.6
F) Type function
• If you wish to determine the type of a variable i. e what type of value
does hold then type() function can be used.

• type(10)
• type(8.2)
• type (“hello”)
G) Len function
• It returns the length of an object

• Str=“Hello world”
• len(str)
• returns 11

• X=[1,2,3,4]
• len(x)
• Returns 4
Round() function
• The round () function is used to get the result up to a specified number
of digits.

• It rounds a given floating point number to the specified number of


digits and returns the result.
• round(n , p) where n is the number and p is the number of digits to
which n is to be rounded .n is a mandatory and p is optional argument.
• round(12.452) returns 12
• round(12.452,2) returns 12.45
I) range() function
• This function is used to define a series of numbers and is particularly
useful in for loops.
• range(5)
range(0,5)

• To show the list of numbers:


List(range(5))
Syntax: range(begin , end) or range(begin, end, step)
MODULE
 A module is a file containing Python definitions
(i.e. functions) and statements.
 Standard library of Python is extended as
module(s) to a programmer. Definitions from the
module can be used within the code of a
program. To use these modules in the program, a
programmer needs to import the module.
HOW TO IMPORT MODULE?
 There are many ways to import a module in
your program, the one's which you should
know are:
 Import
 From
Import
 It is simplest and most common way to use modules in our code.

 Its syntax is:


 import modulename1 [,modulename2, ---------]
 Example
 >>> import math
 To use/ access/invoke a function, you will specify the module name and
name of the
 function- separated by dot (.). This format is also known as dot notation.
 Example
 >>> value= math.sqrt (25) # dot notation
From Statement
 It is used to get a specific function in the code instead of the
complete module file. If we know beforehand which function(s),
we will be needing, then we may use from. For modules having
large no. of functions, it is recommended to use from instead of
import.
Its syntax is:
>>> from modulename import functionname [, functionname…..]
>>>from modulename import * ( Import everything from the file)
Example
 >>> from math import sqrt
 value = sqrt (25)
Random Module
It is used for generating random numbers. It can be used in following
situations:
• Lottery scratch card.
• Login forms
• Computer games etc.
Import random
• Various functions associated with this module are:

• Randrange(): It generates integer numbers between lower and upper


argument. By default , lower argument is 0 and upper argument is 1.

• Import random
• Random.randange(30)
• Random(): It generates a random number from 0 to 1 such as 0.56438.
It takes no arguments.

• randint (): It accepts two parameters a and b and returns number.


random . randint(a,b)
• Uniform(): It returns a random floating point number between two
numbers.
• random . uniform(x , y)
• Choice(): It is used for making a random selection from a sequence
like list, tuple, string etc.
• random . choice(sequence)

• shuffle(): It is used to shuffle or swap the contents of a list.

Shuffle(list)
Programs
• To select a random subject from a list of subjects.

• To generate random numbers from 0 to 1.

• To generate random floating point number between 10 and 15

• To generate a number between 0 and 9.


• To perform binary search using randint()
• To explain uniform,choice and shuffle.
USER DEFINED FUNCTIONS
 To define a function keyword def is used
 After the keyword comes an identifier i.e. name
of the function, followed by parenthesized list of
parameters and the colon which ends up the line.
 Next follows the block of statement(s) that are
the part of function.
EXAMPLE

def sayHello ( ): # Header


print “Hello World!”
 Example-
def area (radius):
a = 3.14*radius**2
return a
Function call
>>> print area (5)
PROGRAMS
 Write a python function to compute area of a triangle.
 Write a program to find factorial of a given number.
 Write a program to add or subtract two values.
 Write a program for calculator.
 Write a program to find the roots of a quadratic equation.
SCOPE OF VARIABLES
The part of the program where a variable can be used is
known as Scope of variable

Two types of scopes :

●Global Scope

●Local Scope
GLOBAL SCOPE
● With global scope, variable can be used
anywhere in the program
eg:
x=50
def test ( ):
print(“inside test x is “, x)
print(“value of x is “, x)
Output:
inside test x is 50
value of x is 50
LOCAL SCOPE
● With local scope, variable can be used only within the
function / block that it is created .
Eg:
X=50
def test ( ):
y = 20
print(‘value of x is ’, X, ‘ y is ’ , y)
print(‘value of x is ’, X, ‘ y is ‘ , y)
On executing the code we will get
Value of x is 50 y is 20

The next print statement will produce an error, because the variable y is
not accessible outside the def()
MORE ON SCOPE OF
VARIABLES
To access global variable inside the function prefix
keyword global with the variable
Eg:

x=50
def test ( ):
global x =5
y =2
print(‘value of x & y inside the function are ‘ , x , y)
Print(‘value of x outside function is ‘ ‘, )

This code will produce following output:


Value of x & y inside the function are 5 2
DEFAULT ARGUMENT
A default argument is a function parameter that has a default
value provided to it. If the user does not supply a value for this
parameter, the default value will be used. If the user does supply a
value for the default parameter, the user-supplied value is used.

Eg.
def greet (message, times=1):
print message * times

>>> greet (‘Welcome’) # function call with one argument value


>>> greet (‘Hello’, 2) # function call with both the argument values.

Output:
Welcome
HelloHello
RECURSION
 It is a function calling itself again and again.

 It is a method in which a function call itself one or more


times.
CONDITION FOR IMPLEMENTING RECURSION
 There must be a terminating condition for the problem. This
condition is called base case.
 These must be an if condition in the recursive routine which
specifies terminating condition.
 Each time a new recursive call is made, a new memory space
is allocated to each local variable.
DISADVANTAGES
 It consumes more storage space.
 It is less efficient in terms of speed and execution time.
 The computer may run out of the memory.
RECURSION VS ITERATION
 Both are inter-related concepts. Problems can be handled
equally by using both the techniques.

 When a loop is executed repeatedly , it use same memory


location but recursion allocate fresh memory space for each
recursive call.
 Any problem that can be solved through iteration can be
solved using recursion as well and vice versa.
FIBONACCI SERIES USING RECURSION
BINARY SEARCH USING RANDINT
1) Enter list 2 4 6 8 10 12 15 18 19
2) Enter search element(item) e.g. 18
3) Sort it
4) Find mid beg+end/2
5) 3 cases
6) Mid=item, item>mid, item <mid
7) Item < mid (first half, beg=0, end=mid-1)
8) Item>mid (second half, beg=mid+1, )

You might also like