SlideShare ist ein Scribd-Unternehmen logo
1 von 58
CHAPTER - II
FUNCTIONS
Unit I
Programming and Computational
Thinking (PCT-II)
(80 Theory + 70 Practical)
DCSc & Engg, PGDCA,ADCA,MCA.MSc(IT),Mtech(IT),MPhil (Comp. Sci)
Department of Computer Science, Sainik School Amaravathinagar
Cell No: 9431453730
Praveen M Jigajinni
Prepared by
Courtesy CBSE
CHAPTER - II
FUNCTIONS
What is Function?
What is Function?
A function is a group of statements that is
executed when it is called from some point of the
program.
It’s a divide and conquer approach
TYPES OF FUNCTIONS
TYPES OF FUNCTIONS
Functions can be categorized into three types
1) Built in Functions.
2) Modules.
3) User - defined functions.
TYPES OF FUNCTIONS
These are predefined function in python and
are used as and when there is need by simply calling
them. For example:
int()
float()
str()
min()
max() ...etc
1) BUILT IN FUNCTIONS
TYPES OF FUNCTIONS
Module is a container of functions,
variables, constants, class in a separate file which
can be reused.
2)MODULES
i) Import statement
ii) from statement
IMPORTING MODULES
IMPORTING MODULES – import STATEMENT
i) import statement : used to import
entire module.
Syntax: import modulename
example: import math
IMPORTING MODULES – import STATEMENT
ii) from: import all functions or selected
one.
Syntax:
from module name import function name
for example:
from random import randint
3) USER DEFINED FUNCIONS
Function is a set of statements that
performs specific task.
Syntax of user defined function
def function_name(list of parameters)
................
................
Statements
def is keyword
3) USER DEFINED FUNCIONS
def sum_diff(x,y):
add=x+y
diff=x-y
return add,diff
def main():
x=9
y=3
a,b=sum_diff(x,y)
print("Sum = ",a)
print("diff = ",b)
main()
PARAMETERS AND ARGUMENTS IN FUNCTION
Parameters are the values which are
provided at the time of function definition.
Parameters
Parameter is also
called as formal
parameter or
formal argument
def sum_diff(p,q):
add=p+q
diff=p-q
return add,diff
Parameter is also
called as formal
parameter or
formal argument
PARAMETERS AND ARGUMENTS IN FUNCTION
Arguments are the values which are passed
while calling a function
def main():
x=9
y=3
a,b=sum_diff(x,y)
print("Sum = ",a)
print("diff = ",b)
main()
Arguments
Python supports following type of
arguments:
TYPES OF ARGUMENTS
1. Positional arguments
2. Default Arguments
3. Keyword Arguments
4. Variable Length Arguments
These are the arguments passed to a
function in correct positional order
1. POSITIONAL ARGUMENTS
For example:
def substract(a,b):
print(a-b)
substract()
>>substract(100,200)
-100
>>substract(150,100)
50
When a function call is made without
arguments, the function has defalut values
for it for example:
2. DEFAULT ARGUMENTS
For example:
def greet_msg(name=“Mohan”):
print(“Hello “, name)
greet_msg()
greet_msg(“Vinay”) # valid
greet_msg() #valid
When a function call is made without
arguments, the function has default values
for it for example:
2. DEFAULT ARGUMENTS
For example:
def greet_msg(name=“Mohan”,msg=“GoodMorning”):
print(name,msg)
greet_msg()
def greet_msg(name=“Mohan”,msg): # invalid
print(name,msg)
greet_msg()
if function containing many arguments,
and we wish to specify some among them, then
value for such parameter can be provided by
using the name
3. KEYWORD ARGUMENTS
For example:
def greet_msg(name,msg):
print(name,msg)
greet_msg()
#calling function
greet_msg(name=“Mohan”,msg=“Hi”): # valid
O/p -> Mohan Hi
For example:
#calling function
greet_msg(msg=“Hi”,name=“Mohan”): # valid
O/p -> Mohan Hi
3. KEYWORD ARGUMENTS
4. VARIABLE LENGTH ARGUMENTS
In some situation one needs to pass as
many as argument to a function, python
provides a way to pass number of argument
to a function, such type of arguments are
called variable length arguments.
Variable length arguments are defined
with * symbol.
For Example: (next slide)
4. VARIABLE LENGTH ARGUMENTS
For Example:
def sum(*n):
total=0
for i in n:
total+=i
print(“Sum = “, total)
sum()
# Calling function
sum() o/p sum=0
sum(10) o/p sum=10
sum(10,20,30,40) o/p sum=100
PASSING ARRAYS/LISTS TO FUNCTIONS
Arrays in basic python are lists that contain
mixed data types and can be passed as an
argument to a function.
For Example: # Arithmetic mean of list
def list_avg(lst):
l=len(lst)
sum=0
for i in lst:
sum+=i
return sum/l
def main():
print(“Input integers”)
a=input()
a=a.split()
for i in range(len(a) ):
a[i]=int(a[i])
avg=list_ave(a)
print (“Average is = “, avg)
SCOPE OF VARIABLES
Scope mean measure of access of variable
or constants in a program. Generally there are
two types of scope of variables:
i) Global (Module)
ii) Local (Function)
i) Global variables are accessed throughout the
program their scope is global
GLOBAL VARIABLES
For Example:
m=100
def add_diff(x,y):
add=x+y
diff=x-y
global m
m= m +10
print("m in add_diff function=",m)
return add,diff
def main():
x=9
y=3
a,b=add_diff(x,y)
print("Sum = ",a)
print("diff = ",b)
print("m in main function = ",m)
main()
RECURSION
A recursive function is a function that calls
itself until a “base condition” is true, and
execution stops. While false
Recursion in computer science is a method of
solving a problem where the solution depends
on solutions to smaller instances of the same
problem (as opposed to iteration). ...
Most computer programming languages
support recursion by allowing a function to
call itself from within its own code.
ADVANTAGES OF RECURSION
1. Recursive functions make the code look
clean and elegant.
2. A complex task can be broken down into
simpler sub-problems using recursion.
3. Sequence generation is easier with recursion
than using some nested iteration.
DISADVANTAGES OF RECURSION
1. Sometimes the logic behind recursion is
hard to follow through.
2. Recursive calls are expensive (inefficient)
as they take up a lot of memory and
time.
3. Recursive functions are hard to debug.
RECURSION - PROGRAM
Factorial of given number using
recursion:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
We can track the recursive function:
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-
1, "): ",res)
return res
print(factorial(5))
RECURSION - PROGRAM
factorial has been called with n = 5
factorial has been called with n = 4
factorial has been called with n = 3
factorial has been called with n = 2
factorial has been called with n = 1
intermediate result for 2 * factorial( 1 ): 2
intermediate result for 3 * factorial( 2 ): 6
intermediate result for 4 * factorial( 3 ): 24
intermediate result for 5 * factorial( 4 ): 120
120
RECURSION - PROGRAM
Fibonacci series using recursive function:
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1) + fib(n-2)
RECURSION - PROGRAM
creating the Pascal triangle using recursion:
RECURSION - PROGRAM
creating the Pascal triangle using recursion:
RECURSION - PROGRAM
#to print a pascal triangle of 'n' rows
def factorial(val):
if val==1:
return val
else:
return val*factorial(val-1)
creating the Pascal triangle using recursion:
RECURSION - PROGRAM
def combination(n,r):
if n<r or r==0 or r==n:
t=1
return int(t)
else:
t=factorial(n)/(factorial(r)*factorial(n-r))
return int(t)
creating the Pascal triangle using recursion:
RECURSION - PROGRAM
def pascal(x):
print('t'*x,end='1n')
for row in range(1,x):
gaps=x-row
for j in range(gaps,0,-1):
print('t',end='')
Contd…
creating the Pascal triangle using recursion:
RECURSION - PROGRAM
for b in range(row):
val=combination(row,b)
print(val,end='tt')
print('1')
x=int(input('Enter the no. of rows :'))
pascal(x)
Tower of Hanoi Python Program
RECURSION - PROGRAM
Tower of Hanoi is a mathematical puzzle
where we have three rods and n disks. The
objective of the puzzle is to move the entire stack
to another rod, obeying the following simple
rules:
1) Only one disk can be moved at a time.
2) Each move consists of taking the upper disk
from one of the stacks and placing it on top of
Tower of Hanoi Python Program
RECURSION - PROGRAM
another stack i.e. a disk can only be moved if it is
the uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
Tower of Hanoi Python Program
RECURSION - PROGRAM
def TowerOfHanoi(n , from_rod, to_rod, aux_rod):
if n == 1:
print ("Move disk 1 from rod",from_rod,"to
rod",to_rod )
return
TowerOfHanoi(n-1, from_rod, aux_rod, to_rod)
print( "Move disk",n,"from rod",from_rod,"to
rod",to_rod )
TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
Tower of Hanoi Python Program
RECURSION - PROGRAM
# Driver code
n = 4
TowerOfHanoi(n, 'A', 'C', 'B')
# A, C, B are the name of rods
# Python program to find the H.C.F of two input number
# define a function
def computeHCF(x, y):
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
RECURSION - PROGRAM
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter first
number:"))
b=int(input("Enter second
number:"))
GCD=gcd(a,b)
print("GCD is: ") print(GCD)
# take input from the user
# num1 = int(input("Enter first number: "))
# num2 = int(input("Enter second number: "))
print("The H.C.F. of", num1,"and", num2,"is",
computeHCF(num1, num2))
RECURSION - PROGRAM
def sum_recursive(current_number, accumulated_sum):
# Base case
# Return the final state
if current_number == 11:
return accumulated_sum
# Recursive case
# Thread the state through the recursive call
else:
return sum_recursive(current_number + 1,
accumulated_sum + current_number)
RECURSION - PROGRAM
1 Recursive Python function to find sum of
natural numbers.
2. Recursive Python function to find sum of
even numbers.
3. Recursive Python function to find sum of
odd numbers.
4. Recursive Python function to find sum of fib
series.
5. Recursive Python function to find given
number is prime or not.
RECURSION - PROGRAM
Class Test
1. Which of the following is the use of function
in python?
a) Functions are reusable pieces of programs
b) Functions don’t provide better modularity
for your application
c) you can’t also create your own functions
d) All of the mentioned
2. Which keyword is use for function?
a) Fun b) Define
c) def d) Function
Class Test
3. What is the output of the below program?
def sayHello():
print('Hello World!')
sayHello()
sayHello()
a) Hello World!
Hello World!
b) ‘Hello World!’
‘Hello World!’
c) Hello
Hello
Class Test
4. What is the output of the below program?
def printMax(a, b):
if a > b:
print(a, 'is maximum')
elif a == b:
print(a, 'is equal to', b)
else:
print(b, 'is maximum')
printMax(3, 4)
a) 3 b) 4
c) 4 is maximum d) None of the mentioned
Class Test
5. What is the output of the below program ?
x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is now', x)
a) x is now 50 b) x is now 2
c) x is now 100 d) None of the mentioned
Class Test
6. What is the output of the below program?
x = 50
def func():
global x
print('x is', x)
x = 2
print('Changed global x to', x)
func()
print('Value of x is', x)
a) x is 50
Changed global x to 2
Value of x is 50
b) x is 50
Changed global x to 2
Value of x is 2
c) x is 50
Changed global x to 50
Value of x is 50
d) None of the mentioned
Class Test
7. What is the output of below program?
def say(message, times = 1):
print(message * times)
say('Hello')
say('World', 5)
a) Hello
WorldWorldWorldWorldWorld
b) Hello
World 5
c) Hello
World,World,World,World,
World
d) Hello
HelloHelloHelloHelloHello
Class Test
8. What is the output of the below program?
def func(a, b=5, c=10):
print('a is', a, 'and b is', b, 'and c is', c)
func(3, 7)
func(25, c = 24)
func(c = 50, a = 100)
a) a is 7 and b is 3 and c is 10
a is 25 and b is 5 and c is 24
a is 5 and b is 100 and c is 50
b) a is 3 and b is 7 and c is 10
a is 5 and b is 25 and c is 24
a is 50 and b is 100 and c is 5
c) a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50
d) None of the mentioned
Class Test
9. What is the output of below program?
def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
a) 2 b) 3 c) The numbers are equal
d) None of the mentioned
Class Test
10. Which of the following is a features of DocString?
a) Provide a convenient way of associating
documentation with Python modules, functions,
classes, and methods
b) All functions should have a docstring
c) Docstrings can be accessed by the __doc__ attribute
on objects
d) All of the mentioned
Class Test
1 A
2 C
3 A
4 C
5 A
6 B
7 A
8 C
9 B
10 D
Thank You

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Pointers in C Programming
Pointers in C ProgrammingPointers in C Programming
Pointers in C Programming
 
List in Python
List in PythonList in Python
List in Python
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
 
11 Unit 1 Chapter 02 Python Fundamentals
11  Unit 1 Chapter 02 Python Fundamentals11  Unit 1 Chapter 02 Python Fundamentals
11 Unit 1 Chapter 02 Python Fundamentals
 
Data types in C
Data types in CData types in C
Data types in C
 
Data types in python
Data types in pythonData types in python
Data types in python
 
12 SQL
12 SQL12 SQL
12 SQL
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
Inline function
Inline functionInline function
Inline function
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
11 Unit 1 Problem Solving Techniques
11  Unit 1 Problem Solving Techniques11  Unit 1 Problem Solving Techniques
11 Unit 1 Problem Solving Techniques
 
Two dimensional arrays
Two dimensional arraysTwo dimensional arrays
Two dimensional arrays
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Strings
StringsStrings
Strings
 
Python functions
Python functionsPython functions
Python functions
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
 

Ähnlich wie Chapter 02 functions -class xii

Ähnlich wie Chapter 02 functions -class xii (20)

Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Pydiomatic
PydiomaticPydiomatic
Pydiomatic
 
Python idiomatico
Python idiomaticoPython idiomatico
Python idiomatico
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
functions
functionsfunctions
functions
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
 
Deep Learning and TensorFlow
Deep Learning and TensorFlowDeep Learning and TensorFlow
Deep Learning and TensorFlow
 
Python basic
Python basicPython basic
Python basic
 
2 Functions2.pptx
2 Functions2.pptx2 Functions2.pptx
2 Functions2.pptx
 
Deep Learning, Scala, and Spark
Deep Learning, Scala, and SparkDeep Learning, Scala, and Spark
Deep Learning, Scala, and Spark
 
III MCS python lab (1).pdf
III MCS python lab (1).pdfIII MCS python lab (1).pdf
III MCS python lab (1).pdf
 
6. function
6. function6. function
6. function
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Functions.docx
Functions.docxFunctions.docx
Functions.docx
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Lecture 8.pdf
Lecture 8.pdfLecture 8.pdf
Lecture 8.pdf
 
Python functions
Python functionsPython functions
Python functions
 

Mehr von Praveen M Jigajinni

Chapter 09 design and analysis of algorithms
Chapter 09  design and analysis of algorithmsChapter 09  design and analysis of algorithms
Chapter 09 design and analysis of algorithmsPraveen M Jigajinni
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructorsPraveen M Jigajinni
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programmingPraveen M Jigajinni
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with pythonPraveen M Jigajinni
 
Chapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingChapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingPraveen M Jigajinni
 
Chapter 6 algorithms and flow charts
Chapter 6  algorithms and flow chartsChapter 6  algorithms and flow charts
Chapter 6 algorithms and flow chartsPraveen M Jigajinni
 
Chapter 3 cloud computing and intro parrallel computing
Chapter 3 cloud computing and intro parrallel computingChapter 3 cloud computing and intro parrallel computing
Chapter 3 cloud computing and intro parrallel computingPraveen M Jigajinni
 

Mehr von Praveen M Jigajinni (20)

Chapter 09 design and analysis of algorithms
Chapter 09  design and analysis of algorithmsChapter 09  design and analysis of algorithms
Chapter 09 design and analysis of algorithms
 
Chapter 07 inheritance
Chapter 07 inheritanceChapter 07 inheritance
Chapter 07 inheritance
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Unit 3 MongDB
Unit 3 MongDBUnit 3 MongDB
Unit 3 MongDB
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Chapter 13 exceptional handling
Chapter 13 exceptional handlingChapter 13 exceptional handling
Chapter 13 exceptional handling
 
Chapter 10 data handling
Chapter 10 data handlingChapter 10 data handling
Chapter 10 data handling
 
Chapter 9 python fundamentals
Chapter 9 python fundamentalsChapter 9 python fundamentals
Chapter 9 python fundamentals
 
Chapter 8 getting started with python
Chapter 8 getting started with pythonChapter 8 getting started with python
Chapter 8 getting started with python
 
Chapter 7 basics of computational thinking
Chapter 7 basics of computational thinkingChapter 7 basics of computational thinking
Chapter 7 basics of computational thinking
 
Chapter 6 algorithms and flow charts
Chapter 6  algorithms and flow chartsChapter 6  algorithms and flow charts
Chapter 6 algorithms and flow charts
 
Chapter 5 boolean algebra
Chapter 5 boolean algebraChapter 5 boolean algebra
Chapter 5 boolean algebra
 
Chapter 4 number system
Chapter 4 number systemChapter 4 number system
Chapter 4 number system
 
Chapter 3 cloud computing and intro parrallel computing
Chapter 3 cloud computing and intro parrallel computingChapter 3 cloud computing and intro parrallel computing
Chapter 3 cloud computing and intro parrallel computing
 
Chapter 2 operating systems
Chapter 2 operating systemsChapter 2 operating systems
Chapter 2 operating systems
 
Chapter 1 computer fundamentals
Chapter 1 computer  fundamentalsChapter 1 computer  fundamentals
Chapter 1 computer fundamentals
 

Kürzlich hochgeladen

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 

Kürzlich hochgeladen (20)

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 

Chapter 02 functions -class xii

  • 2. Unit I Programming and Computational Thinking (PCT-II) (80 Theory + 70 Practical) DCSc & Engg, PGDCA,ADCA,MCA.MSc(IT),Mtech(IT),MPhil (Comp. Sci) Department of Computer Science, Sainik School Amaravathinagar Cell No: 9431453730 Praveen M Jigajinni Prepared by Courtesy CBSE
  • 5. What is Function? A function is a group of statements that is executed when it is called from some point of the program. It’s a divide and conquer approach
  • 7. TYPES OF FUNCTIONS Functions can be categorized into three types 1) Built in Functions. 2) Modules. 3) User - defined functions.
  • 8. TYPES OF FUNCTIONS These are predefined function in python and are used as and when there is need by simply calling them. For example: int() float() str() min() max() ...etc 1) BUILT IN FUNCTIONS
  • 9. TYPES OF FUNCTIONS Module is a container of functions, variables, constants, class in a separate file which can be reused. 2)MODULES
  • 10. i) Import statement ii) from statement IMPORTING MODULES
  • 11. IMPORTING MODULES – import STATEMENT i) import statement : used to import entire module. Syntax: import modulename example: import math
  • 12. IMPORTING MODULES – import STATEMENT ii) from: import all functions or selected one. Syntax: from module name import function name for example: from random import randint
  • 13. 3) USER DEFINED FUNCIONS Function is a set of statements that performs specific task. Syntax of user defined function def function_name(list of parameters) ................ ................ Statements def is keyword
  • 14. 3) USER DEFINED FUNCIONS def sum_diff(x,y): add=x+y diff=x-y return add,diff def main(): x=9 y=3 a,b=sum_diff(x,y) print("Sum = ",a) print("diff = ",b) main()
  • 15. PARAMETERS AND ARGUMENTS IN FUNCTION Parameters are the values which are provided at the time of function definition. Parameters Parameter is also called as formal parameter or formal argument def sum_diff(p,q): add=p+q diff=p-q return add,diff
  • 16. Parameter is also called as formal parameter or formal argument PARAMETERS AND ARGUMENTS IN FUNCTION Arguments are the values which are passed while calling a function def main(): x=9 y=3 a,b=sum_diff(x,y) print("Sum = ",a) print("diff = ",b) main() Arguments
  • 17. Python supports following type of arguments: TYPES OF ARGUMENTS 1. Positional arguments 2. Default Arguments 3. Keyword Arguments 4. Variable Length Arguments
  • 18. These are the arguments passed to a function in correct positional order 1. POSITIONAL ARGUMENTS For example: def substract(a,b): print(a-b) substract() >>substract(100,200) -100 >>substract(150,100) 50
  • 19. When a function call is made without arguments, the function has defalut values for it for example: 2. DEFAULT ARGUMENTS For example: def greet_msg(name=“Mohan”): print(“Hello “, name) greet_msg() greet_msg(“Vinay”) # valid greet_msg() #valid
  • 20. When a function call is made without arguments, the function has default values for it for example: 2. DEFAULT ARGUMENTS For example: def greet_msg(name=“Mohan”,msg=“GoodMorning”): print(name,msg) greet_msg() def greet_msg(name=“Mohan”,msg): # invalid print(name,msg) greet_msg()
  • 21. if function containing many arguments, and we wish to specify some among them, then value for such parameter can be provided by using the name 3. KEYWORD ARGUMENTS For example: def greet_msg(name,msg): print(name,msg) greet_msg() #calling function greet_msg(name=“Mohan”,msg=“Hi”): # valid O/p -> Mohan Hi
  • 22. For example: #calling function greet_msg(msg=“Hi”,name=“Mohan”): # valid O/p -> Mohan Hi 3. KEYWORD ARGUMENTS
  • 23. 4. VARIABLE LENGTH ARGUMENTS In some situation one needs to pass as many as argument to a function, python provides a way to pass number of argument to a function, such type of arguments are called variable length arguments. Variable length arguments are defined with * symbol. For Example: (next slide)
  • 24. 4. VARIABLE LENGTH ARGUMENTS For Example: def sum(*n): total=0 for i in n: total+=i print(“Sum = “, total) sum() # Calling function sum() o/p sum=0 sum(10) o/p sum=10 sum(10,20,30,40) o/p sum=100
  • 25. PASSING ARRAYS/LISTS TO FUNCTIONS Arrays in basic python are lists that contain mixed data types and can be passed as an argument to a function. For Example: # Arithmetic mean of list def list_avg(lst): l=len(lst) sum=0 for i in lst: sum+=i return sum/l def main(): print(“Input integers”) a=input() a=a.split() for i in range(len(a) ): a[i]=int(a[i]) avg=list_ave(a) print (“Average is = “, avg)
  • 26. SCOPE OF VARIABLES Scope mean measure of access of variable or constants in a program. Generally there are two types of scope of variables: i) Global (Module) ii) Local (Function) i) Global variables are accessed throughout the program their scope is global
  • 27. GLOBAL VARIABLES For Example: m=100 def add_diff(x,y): add=x+y diff=x-y global m m= m +10 print("m in add_diff function=",m) return add,diff def main(): x=9 y=3 a,b=add_diff(x,y) print("Sum = ",a) print("diff = ",b) print("m in main function = ",m) main()
  • 28. RECURSION A recursive function is a function that calls itself until a “base condition” is true, and execution stops. While false Recursion in computer science is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem (as opposed to iteration). ... Most computer programming languages support recursion by allowing a function to call itself from within its own code.
  • 29. ADVANTAGES OF RECURSION 1. Recursive functions make the code look clean and elegant. 2. A complex task can be broken down into simpler sub-problems using recursion. 3. Sequence generation is easier with recursion than using some nested iteration.
  • 30. DISADVANTAGES OF RECURSION 1. Sometimes the logic behind recursion is hard to follow through. 2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time. 3. Recursive functions are hard to debug.
  • 31. RECURSION - PROGRAM Factorial of given number using recursion: def factorial(n): if n == 1: return 1 else: return n * factorial(n-1)
  • 32. We can track the recursive function: def factorial(n): print("factorial has been called with n = " + str(n)) if n == 1: return 1 else: res = n * factorial(n-1) print("intermediate result for ", n, " * factorial(" ,n- 1, "): ",res) return res print(factorial(5)) RECURSION - PROGRAM
  • 33. factorial has been called with n = 5 factorial has been called with n = 4 factorial has been called with n = 3 factorial has been called with n = 2 factorial has been called with n = 1 intermediate result for 2 * factorial( 1 ): 2 intermediate result for 3 * factorial( 2 ): 6 intermediate result for 4 * factorial( 3 ): 24 intermediate result for 5 * factorial( 4 ): 120 120 RECURSION - PROGRAM
  • 34. Fibonacci series using recursive function: def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1) + fib(n-2) RECURSION - PROGRAM
  • 35. creating the Pascal triangle using recursion: RECURSION - PROGRAM
  • 36. creating the Pascal triangle using recursion: RECURSION - PROGRAM #to print a pascal triangle of 'n' rows def factorial(val): if val==1: return val else: return val*factorial(val-1)
  • 37. creating the Pascal triangle using recursion: RECURSION - PROGRAM def combination(n,r): if n<r or r==0 or r==n: t=1 return int(t) else: t=factorial(n)/(factorial(r)*factorial(n-r)) return int(t)
  • 38. creating the Pascal triangle using recursion: RECURSION - PROGRAM def pascal(x): print('t'*x,end='1n') for row in range(1,x): gaps=x-row for j in range(gaps,0,-1): print('t',end='') Contd…
  • 39. creating the Pascal triangle using recursion: RECURSION - PROGRAM for b in range(row): val=combination(row,b) print(val,end='tt') print('1') x=int(input('Enter the no. of rows :')) pascal(x)
  • 40. Tower of Hanoi Python Program RECURSION - PROGRAM Tower of Hanoi is a mathematical puzzle where we have three rods and n disks. The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules: 1) Only one disk can be moved at a time. 2) Each move consists of taking the upper disk from one of the stacks and placing it on top of
  • 41. Tower of Hanoi Python Program RECURSION - PROGRAM another stack i.e. a disk can only be moved if it is the uppermost disk on a stack. 3) No disk may be placed on top of a smaller disk.
  • 42. Tower of Hanoi Python Program RECURSION - PROGRAM def TowerOfHanoi(n , from_rod, to_rod, aux_rod): if n == 1: print ("Move disk 1 from rod",from_rod,"to rod",to_rod ) return TowerOfHanoi(n-1, from_rod, aux_rod, to_rod) print( "Move disk",n,"from rod",from_rod,"to rod",to_rod ) TowerOfHanoi(n-1, aux_rod, to_rod, from_rod)
  • 43. Tower of Hanoi Python Program RECURSION - PROGRAM # Driver code n = 4 TowerOfHanoi(n, 'A', 'C', 'B') # A, C, B are the name of rods
  • 44. # Python program to find the H.C.F of two input number # define a function def computeHCF(x, y): # choose the smaller number if x > y: smaller = y else: smaller = x for i in range(1, smaller+1): if((x % i == 0) and (y % i == 0)): hcf = i return hcf RECURSION - PROGRAM def gcd(a,b): if(b==0): return a else: return gcd(b,a%b) a=int(input("Enter first number:")) b=int(input("Enter second number:")) GCD=gcd(a,b) print("GCD is: ") print(GCD)
  • 45. # take input from the user # num1 = int(input("Enter first number: ")) # num2 = int(input("Enter second number: ")) print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2)) RECURSION - PROGRAM
  • 46. def sum_recursive(current_number, accumulated_sum): # Base case # Return the final state if current_number == 11: return accumulated_sum # Recursive case # Thread the state through the recursive call else: return sum_recursive(current_number + 1, accumulated_sum + current_number) RECURSION - PROGRAM
  • 47. 1 Recursive Python function to find sum of natural numbers. 2. Recursive Python function to find sum of even numbers. 3. Recursive Python function to find sum of odd numbers. 4. Recursive Python function to find sum of fib series. 5. Recursive Python function to find given number is prime or not. RECURSION - PROGRAM
  • 48. Class Test 1. Which of the following is the use of function in python? a) Functions are reusable pieces of programs b) Functions don’t provide better modularity for your application c) you can’t also create your own functions d) All of the mentioned 2. Which keyword is use for function? a) Fun b) Define c) def d) Function
  • 49. Class Test 3. What is the output of the below program? def sayHello(): print('Hello World!') sayHello() sayHello() a) Hello World! Hello World! b) ‘Hello World!’ ‘Hello World!’ c) Hello Hello
  • 50. Class Test 4. What is the output of the below program? def printMax(a, b): if a > b: print(a, 'is maximum') elif a == b: print(a, 'is equal to', b) else: print(b, 'is maximum') printMax(3, 4) a) 3 b) 4 c) 4 is maximum d) None of the mentioned
  • 51. Class Test 5. What is the output of the below program ? x = 50 def func(x): print('x is', x) x = 2 print('Changed local x to', x) func(x) print('x is now', x) a) x is now 50 b) x is now 2 c) x is now 100 d) None of the mentioned
  • 52. Class Test 6. What is the output of the below program? x = 50 def func(): global x print('x is', x) x = 2 print('Changed global x to', x) func() print('Value of x is', x) a) x is 50 Changed global x to 2 Value of x is 50 b) x is 50 Changed global x to 2 Value of x is 2 c) x is 50 Changed global x to 50 Value of x is 50 d) None of the mentioned
  • 53. Class Test 7. What is the output of below program? def say(message, times = 1): print(message * times) say('Hello') say('World', 5) a) Hello WorldWorldWorldWorldWorld b) Hello World 5 c) Hello World,World,World,World, World d) Hello HelloHelloHelloHelloHello
  • 54. Class Test 8. What is the output of the below program? def func(a, b=5, c=10): print('a is', a, 'and b is', b, 'and c is', c) func(3, 7) func(25, c = 24) func(c = 50, a = 100) a) a is 7 and b is 3 and c is 10 a is 25 and b is 5 and c is 24 a is 5 and b is 100 and c is 50 b) a is 3 and b is 7 and c is 10 a is 5 and b is 25 and c is 24 a is 50 and b is 100 and c is 5 c) a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50 d) None of the mentioned
  • 55. Class Test 9. What is the output of below program? def maximum(x, y): if x > y: return x elif x == y: return 'The numbers are equal' else: return y print(maximum(2, 3)) a) 2 b) 3 c) The numbers are equal d) None of the mentioned
  • 56. Class Test 10. Which of the following is a features of DocString? a) Provide a convenient way of associating documentation with Python modules, functions, classes, and methods b) All functions should have a docstring c) Docstrings can be accessed by the __doc__ attribute on objects d) All of the mentioned
  • 57. Class Test 1 A 2 C 3 A 4 C 5 A 6 B 7 A 8 C 9 B 10 D