SlideShare a Scribd company logo
Unit II
Control Statements and Functions
Selections: if –Two way if-else – Nested if
and Multi-way if-elif-else Statements – Logical
Operators – Conditional Expressions – Operator
Precedence and Associativity – Loops: while –
for – Nested Loops – break and continue –
Function: Definition – Calling and Returning
values – Positional and keyword arguments –
Passing arguments by reference values –
Modularizing Code – Scope of variables –
Default Arguments – Function Abstraction and
Stepwise Refinement – Recursion.
CONDITIONALS
Decision Making and Branching
‘python’ control statements
i. Sequential structure:
instruction are executed in sequence
i=i+1
j=j+1
ii. Selection structure:
if(x>y):
i=i+1
else:
J=j+1
K.ANGURAJU , AP/CSE
iii. Iteration structure (or) loop:
for i in range(0,5,1):
Print(“hello”)
iv. Encapsulation structure.
for i in range(0,5,1):
if (condition):
Print(“hello”)
else:
Print(“hai”)
K.ANGURAJU , AP/CSE
Conditional if statement
if is a decision making statement or
conditional statement . It is used to control the flow
of execution, also to test logically whether the
condition is true or false.
Syntax:
if (condition) : false
true
true statements true
condition
True statement
K.ANGURAJU , AP/CSE
Example:
a= int ( input ( “enter a value”))
b= int (input (“enter b value”))
if (a>b):
print(“a is big”)
K.ANGURAJU , AP/CSE
Alternative If else statement
It is basically two way decision making statement,
Here it check the condition if the condition is true
means it execute the true statements,
If it is false execute another set of statement.
Syntax:
if(condition) : true false
true statement
else:
false statement
condition
True statement False statement
K.ANGURAJU , AP/CSE
Example:
a= int ( input ( “enter a value”)
b= int (input (“enter b value”)
if (a>b):
print(“a is big”)
else:
print(“b is big”)
K.ANGURAJU , AP/CSE
Chained conditionals if elif else
statement
It is defined as we can write a entire if…else statement in
another if…else statement called nesting.
Syntax:
if(condition 1) :
True statement 1 true
false
elif(condition 2) :
True statement 2
else : true false
false statement 2
stop
If
Condition
1
elif
Condition
2
True statement
2
True statement
1
False statement
2
K.ANGURAJU , AP/CSE
Example:
a= int ( input ( “enter a value”)
b= int (input (“enter b value”)
c = int (input (“enter c value”)
if ((a>b) and (a>c)):
print(“a is big”)
elif (b>c):
print(“b is big”)
else:
print(“c is big”)
K.ANGURAJU , AP/CSE
Nested if else statement
if a programming having more than two
if else statement then that is called as nested
if else statement.
here based on the condition it execute
any one of the statement.
Example:
a=10
if(a==0):
print(“zero”)
elif(a>0):
print(“+ve”)
elif(a<0):
print(“-ve”)
else:
print(“invalid number “)
Iteration /Looping statement
The loop is defined as the block of statements
which are repeatedly executed for a certain number of
time.
the loop program consist of two parts , one is body
of the loop another one is control statement .
any looping statement ,would include following
steps:
1. Initialization of a condition variable
2. Test the condition .
3. Executing body of the statement based on the condition.
4. Updating condition variable /INCREMENT OR DECREMENT
Types:
1. while statement(entry check loop)(top tested loop).
2. for statement.
3. Nested looping.
K.ANGURAJU , AP/CSE
while statement(entry check loop)
The while loop is an entry controlled
loop statement , means the condition as
evaluated first , if it is true then body of the
loop is executed.
Syntax: false
while(condition):
……. true
body of the loop
…….
condition
Body of the loop
K.ANGURAJU , AP/CSE
Example:
n=int (input(“enter the number”))
i=1
sum=0;
while(i<=n):
sum=sum+i
i=i+1
print(“the sum of n number is:”, sum)
out put:
Enter the number: 5
the sum of n number is : 15
K.ANGURAJU , AP/CSE
The for loop
This is another one control structure,
and it is execute the set of instructions
repeatedly until the condition become false.
for loop executed based on the
condition with the help of range() function.
true
execute body
of the
Statement
Item from
sequence
K.ANGURAJU , AP/CSE
Syntax:
for iterating_variable in sequence/range():
……
body of the loop
Description:
for - keyword
iterating variable - user defined variable
in - membership operator
body of the loop - set of statement
Range(initial value, condition,
increment/decrement value)
K.ANGURAJU , AP/CSE
Example:
n=int (input(“enter the number”))
sum=0
for i in range(1, 6, 1):
sum=sum+i
print( “the sum of n number is:”, sum)
K.ANGURAJU , AP/CSE
Loop control statement
The loop control statement is control the
looping statement .
There are following loop control statement are:
Break
Continue
Pass
K.ANGURAJU , AP/CSE
Break statement
Break is a loop control statement .
The break statement is used to
terminate the loop
when the break statement enter inside a
loop ,then the loop is exit immediately
The break statement can be used in both
while and for loop.
K.ANGURAJU , AP/CSE
Flow chart
K.ANGURAJU , AP/CSE
Example
for character in "ram":
if ( character=='a‘):
break
print(character)
Output:
r
K.ANGURAJU , AP/CSE
The continue statement rejects all the
remaining statements in the current iteration
of the for loop and moves the control back to
the top of the loop.
When the statement continue is entered
into any python loop control automatically
passes to the beginning of the loop
K.ANGURAJU , AP/CSE
Flow chart
K.ANGURAJU , AP/CSE
Example
for character in "ram“ :
if ( character == 'a‘ ):
continue
print(character)
Output:
r
m
K.ANGURAJU , AP/CSE
Pass statement
It is one of the loop control statement .
The pass statement is a null operation ,
nothing happens when it executes. The pass is
useful in the place of where your code will
eventually go .
K.ANGURAJU , AP/CSE
Example
for character in "ram“ :
if ( character == 'a‘ ):
pass
print(character)
Output:
r
a
m
K.ANGURAJU , AP/CSE
Functions
• A function is a block of statement or
reusable code that is used to perform a
single, related action.
• By using function we can divide complex
task into manageable task .The function
also help to avoid duplication of work.
• Python gives you many built-in functions
like print(), etc. but you can also create
your own functions. These functions are
called user-defined functions.
K.ANGURAJU , AP/CSE
User defined function:
User defined function are
defined by the user , Depend upon the user
requirement user create a function.
Elements of user defined function
a. Function definition
b. Function call
K.ANGURAJU , AP/CSE
A. Defining a Function
• Function blocks begin with the keyword def
followed by the function name and
parentheses and followed by colon ( ): .
• Any input parameters or arguments may be
or may not be placed within these
parentheses .
• Inside the function definition to implement
logic of that program.
• The statement return() it will return results
to called function.
K.ANGURAJU , AP/CSE
• A return statement with no arguments is
represent as return nothing .
K.ANGURAJU , AP/CSE
Syntax & Example
Syntax:
def function name( parameters ):
local variable declaration
logic implementation
return (result)
Example:
>>>def avg( n1,n2,n3 ): #function definition
return ((n1+n2+n3)/3)
avg(10,25,16) #function call
K.ANGURAJU , AP/CSE
B . Calling a function
Once the basic structure of function is
implemented , you can execute it by calling it
from another function or directly from the
python prompt.
K.ANGURAJU , AP/CSE
Example:
def add(a,b): # function definition
c=a+b
return(c)
result = add(10, 20) # function call
print (“addition of two number is”, result)
K.ANGURAJU , AP/CSE
Parameter passing method in function
(pass by reference vs value)
1.Call by value
2. Call by reference
All the parameter (arguments) in
the python language are passed by
reference . It means if you change
parameter with in a function , the change
also reflects back in the calling function.
K.ANGURAJU , AP/CSE
Example:
#called function
def sub(a,b): # function definition
c=a+b
return(c)
# Calling the function
result = sub(10, 20) # function call
print (“addition of two number is”, result)
K.ANGURAJU , AP/CSE
Need for user defined functions
• The program becomes too large and complex.
• The task of debugging, testing and maintenance
becomes difficult.
To solve this problems:
• The program is divided into two parts and each
part may be independently coded and later
combined into a single program.
• These sub-programs are called functions and
much easier to understand, debug and test.
K.ANGURAJU , AP/CSE
Advantages
• The length of the source program can be
reduced by dividing it into smaller
functions.
• By using functions it is very easy to locate
and debug an error.
• Functions processed by top-down
programming approach.
• Functions avoid coding of repeated
programming of the similar instructions.
K.ANGURAJU , AP/CSE
Flow of Execution
• Once a function is called, it takes some data
from the calling function and return back
some value to the called function.
K.ANGURAJU , AP/CSE
• Ex : # called function
def leap(year):
if (year %4 = = 0): # function definition
print (“it is leap year”)
else:
print(“it is not a leap year”)
return()
# calling function
leap(2017) # function call
K.ANGURAJU , AP/CSE
Function argument
• Required function
• Keyword arguments
• Default arguments
K.ANGURAJU , AP/CSE
Required function /positional
Arguments
In this argument required that the
argument be passed in function call, the same
order as their respective parameters in the
function definition header.
Example:
def display(x) # function definition
print(x)
return()
display() # function call
Type error: required positional arguments
K.ANGURAJU , AP/CSE
Keyword argument:
In keyword as a arguments passing each
argument in the form of variable
name=value.
Example:
def display(name): #function definition
print (name)
return()
display(name= “Rajesh”)# function call
K.ANGURAJU , AP/CSE
Default argument
# function definition
def biodata( name , phno=‘1234567890’):
print(“ name: ”, name)
print(“ phone number: ”, phno)
return()
# function call
biodata(name=“rajesh”)
biodata(name= “rajesh” , phno=“9940805625”)
K.ANGURAJU , AP/CSE
Types of parameter:
1.Actual parameter:
2.Formal parameter:
Example:
def add(x,y):
local variable
logic implementation
a=10;b=20
add(a,b) ## function call
ANGURAJU.K AP/CSE - KNCET
Function definition: Formal parameter
def add(x , y)
{
body of the statement
……………..
……………….
return()
}
ANGURAJU.K AP/CSE - KNCET
def add(a,b): # function definition
c=a+b
return(c)
a=10,b=30
result = add(a, b) # function call
print (“addition of two number is”, result)
Function Prototype
1. Function with no argument and no return
value
2. Function with argument and with return
value
3. Function with argument and no return value
4. Function with out argument and with return
value
ANGURAJU.K AP/CSE - KNCET
Function with no argument and no
return value
Here the function call having no argument
it cannot send any values to function
definition
also the function definition cannot send result
to function call.
Syntax:
def function_name(): # function definition
body of the function
return()
function_name() # Function call
Example:
def display():
print(“welcome”)
return()
display()
Function with argument and with
return value
Here the function call having argument
it can send values to function definition
also the function definition can send result to
function call.
Syntax:
def function_name(parameter): # function
definition
body of the function
return(result)
function_name(actual parameter) # Function call
Example:
def add(x,y):
c=x+y
return(c)
add(10,20)
Function with argument and no
return value
Here the function call having argument
it can send values to function definition
but the function definition cannot send result
to function call.
Syntax:
def function_name( formal parameter):
body of the function
return()
function_name(actual parameter)
Example:
def add(x,y):
c=x+y
print(c)
return()
add(10,20)
Function with out argument and
with return value
Here the function call having no argument
it cannot send values to function definition
but the function definition can send result to
function call.
Syntax:
def function_name():
body of the function
return(result)
function_name()
Example:
def add():
x=10;y=5
c=x+y
return(c)
result=add()
print(result)
Recursion
Recursion is the process of calling the
same function itself again and again until
some condition is satisfied .
This process is used for repetitive
computation in the each action is satisfied in
terms of a previous result.
K.ANGURAJU , AP/CSE
Example:
def fact(x):
if (x==1):
return (1) #function definition
else:
return (x* fact (x-1))
num=4
print(“factorial value is”, fact(num) )
K.ANGURAJU , AP/CSE
Modularizing Code
Function can be used to reduce code and enable
code reuse. Functions can also be used to
modularize code and improve the program quality.
A module is a file containing python definitions
and statement , the file name is a module name
with suffix .py ,
whenever we want this file import it by import
keyword
The module can be later imported into a
program to reuse.
The module file should be placed in the
same directory with your other program.
The module contain more than one
function , Each function in the module must
have different name.
Example: ( program to create a module to find the
Fibonacci numbers upto 10 and addition of two
number ) mulfun.py
def fib(n):
a,b=0,1
while(b<n):
print(b , end="")
a,b=b,a+b
print()
def add(x,y):
c=x+y
print(c)
return() ANGURAJU AP/CSE
# import the saved file mulpy.py
>>> from mulfun import fib
>>> fib(10)
112358
>>> from mulfun import add
>>> add(10,20)
30
Function abstraction
Abstraction is used to hide the internal
functionality of the function from the users.
The users only interact with the basic
implementation of the function,
but inner working is hidden.
User is familiar with that "what function does"
but they don't know "how it does."
In simple words, we all use the
Smartphone
and very much familiar with its functions
such as camera, voice-recorder, call-dialing,
etc.,
but we don't know how these
operations are happening in the background.
Example: We already use the predefine
function in your program but those
implementation only implemented and known
by developer.
Stepwise refinement
When writing large program, you can
use “divide-and –conquer” Strategy also
known as stepwise refinement
• Start with the initial problem statement
• Break it into a few general steps
• Take each "step", and break it further into
more detailed steps
• Keep repeating the process on each "step",
until you get smaller code.
Top-down design
• Start with an initial problem statement.
• Define subtask at the first level.
• Divide subtasks at a higher level into more
specific tasks.
• Repeat step (3) until each subtask is trivial.
• Refine the algorithm into real code.
UNIT 2 PY.ppt - CONTROL STATEMENT IN PYTHON
Bottom-up implementation
In bottom up approach, we solve smaller
problems and integrate it as whole and
complete the solution.
Mainly used by object oriented
programming language such as C++, C#,
Python.
Redundancy is minimized by using data
encapsulation and data hiding.

More Related Content

PPTX
UNIT – 3.pptx for first year engineering
DOCX
Python unit 3 and Unit 4
PDF
Python Unit 3 - Control Flow and Functions
PPTX
module 2.pptx
PPTX
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2
PPTX
Module_2_1_Building Python Programs_Final.pptx
PDF
basic of desicion control statement in python
UNIT – 3.pptx for first year engineering
Python unit 3 and Unit 4
Python Unit 3 - Control Flow and Functions
module 2.pptx
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2
Module_2_1_Building Python Programs_Final.pptx
basic of desicion control statement in python

Similar to UNIT 2 PY.ppt - CONTROL STATEMENT IN PYTHON (20)

PPTX
Week 4.pptx computational thinking and programming
PPTX
ControlStructures.pptx5t54t54444444444444444
PPTX
Python programming –part 3
PDF
Python unit 2 M.sc cs
PPTX
control statements in python.pptx
PPTX
Control_Statements.pptx
PPTX
industry coding practice unit-2 ppt.pptx
PDF
Slide 6_Control Structures.pdf
PDF
Python - Lecture 2
PDF
2 Python Basics II meeting 2 tunghai university pdf
PPT
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPTX
Control Structures Python like conditions and loops
PPTX
FAL(2022-23)_FRESHERS_CSE1012_ETH_AP2022234000166_Reference_Material_I_15-Nov...
PDF
ppt python notes list tuple data types ope
PDF
Python Flow Control
PPTX
Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...
PPT
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
PPT
Python Programming Unit II Control Statements.ppt
PPTX
Loops in Python
Week 4.pptx computational thinking and programming
ControlStructures.pptx5t54t54444444444444444
Python programming –part 3
Python unit 2 M.sc cs
control statements in python.pptx
Control_Statements.pptx
industry coding practice unit-2 ppt.pptx
Slide 6_Control Structures.pdf
Python - Lecture 2
2 Python Basics II meeting 2 tunghai university pdf
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
Control Structures Python like conditions and loops
FAL(2022-23)_FRESHERS_CSE1012_ETH_AP2022234000166_Reference_Material_I_15-Nov...
ppt python notes list tuple data types ope
Python Flow Control
Python Programming | JNTUK | UNIT 2 | Lecture 6 & 7 | Conditional & Control S...
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
Python Programming Unit II Control Statements.ppt
Loops in Python
Ad

Recently uploaded (20)

PPTX
Lecture Notes Electrical Wiring System Components
PPTX
bas. eng. economics group 4 presentation 1.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
PPT on Performance Review to get promotions
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
DOCX
573137875-Attendance-Management-System-original
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
additive manufacturing of ss316l using mig welding
PPT
introduction to datamining and warehousing
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPT
Mechanical Engineering MATERIALS Selection
PPTX
Current and future trends in Computer Vision.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PDF
Digital Logic Computer Design lecture notes
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PPTX
UNIT 4 Total Quality Management .pptx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Lecture Notes Electrical Wiring System Components
bas. eng. economics group 4 presentation 1.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPT on Performance Review to get promotions
Automation-in-Manufacturing-Chapter-Introduction.pdf
573137875-Attendance-Management-System-original
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
R24 SURVEYING LAB MANUAL for civil enggi
additive manufacturing of ss316l using mig welding
introduction to datamining and warehousing
CYBER-CRIMES AND SECURITY A guide to understanding
Mechanical Engineering MATERIALS Selection
Current and future trends in Computer Vision.pptx
OOP with Java - Java Introduction (Basics)
Digital Logic Computer Design lecture notes
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
UNIT 4 Total Quality Management .pptx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Ad

UNIT 2 PY.ppt - CONTROL STATEMENT IN PYTHON

  • 2. Control Statements and Functions Selections: if –Two way if-else – Nested if and Multi-way if-elif-else Statements – Logical Operators – Conditional Expressions – Operator Precedence and Associativity – Loops: while – for – Nested Loops – break and continue – Function: Definition – Calling and Returning values – Positional and keyword arguments – Passing arguments by reference values – Modularizing Code – Scope of variables – Default Arguments – Function Abstraction and Stepwise Refinement – Recursion.
  • 3. CONDITIONALS Decision Making and Branching ‘python’ control statements i. Sequential structure: instruction are executed in sequence i=i+1 j=j+1 ii. Selection structure: if(x>y): i=i+1 else: J=j+1 K.ANGURAJU , AP/CSE
  • 4. iii. Iteration structure (or) loop: for i in range(0,5,1): Print(“hello”) iv. Encapsulation structure. for i in range(0,5,1): if (condition): Print(“hello”) else: Print(“hai”) K.ANGURAJU , AP/CSE
  • 5. Conditional if statement if is a decision making statement or conditional statement . It is used to control the flow of execution, also to test logically whether the condition is true or false. Syntax: if (condition) : false true true statements true condition True statement K.ANGURAJU , AP/CSE
  • 6. Example: a= int ( input ( “enter a value”)) b= int (input (“enter b value”)) if (a>b): print(“a is big”) K.ANGURAJU , AP/CSE
  • 7. Alternative If else statement It is basically two way decision making statement, Here it check the condition if the condition is true means it execute the true statements, If it is false execute another set of statement. Syntax: if(condition) : true false true statement else: false statement condition True statement False statement K.ANGURAJU , AP/CSE
  • 8. Example: a= int ( input ( “enter a value”) b= int (input (“enter b value”) if (a>b): print(“a is big”) else: print(“b is big”) K.ANGURAJU , AP/CSE
  • 9. Chained conditionals if elif else statement It is defined as we can write a entire if…else statement in another if…else statement called nesting. Syntax: if(condition 1) : True statement 1 true false elif(condition 2) : True statement 2 else : true false false statement 2 stop If Condition 1 elif Condition 2 True statement 2 True statement 1 False statement 2 K.ANGURAJU , AP/CSE
  • 10. Example: a= int ( input ( “enter a value”) b= int (input (“enter b value”) c = int (input (“enter c value”) if ((a>b) and (a>c)): print(“a is big”) elif (b>c): print(“b is big”) else: print(“c is big”) K.ANGURAJU , AP/CSE
  • 11. Nested if else statement if a programming having more than two if else statement then that is called as nested if else statement. here based on the condition it execute any one of the statement.
  • 13. Iteration /Looping statement The loop is defined as the block of statements which are repeatedly executed for a certain number of time. the loop program consist of two parts , one is body of the loop another one is control statement . any looping statement ,would include following steps: 1. Initialization of a condition variable 2. Test the condition . 3. Executing body of the statement based on the condition. 4. Updating condition variable /INCREMENT OR DECREMENT Types: 1. while statement(entry check loop)(top tested loop). 2. for statement. 3. Nested looping. K.ANGURAJU , AP/CSE
  • 14. while statement(entry check loop) The while loop is an entry controlled loop statement , means the condition as evaluated first , if it is true then body of the loop is executed. Syntax: false while(condition): ……. true body of the loop ……. condition Body of the loop K.ANGURAJU , AP/CSE
  • 15. Example: n=int (input(“enter the number”)) i=1 sum=0; while(i<=n): sum=sum+i i=i+1 print(“the sum of n number is:”, sum) out put: Enter the number: 5 the sum of n number is : 15 K.ANGURAJU , AP/CSE
  • 16. The for loop This is another one control structure, and it is execute the set of instructions repeatedly until the condition become false. for loop executed based on the condition with the help of range() function. true execute body of the Statement Item from sequence K.ANGURAJU , AP/CSE
  • 17. Syntax: for iterating_variable in sequence/range(): …… body of the loop Description: for - keyword iterating variable - user defined variable in - membership operator body of the loop - set of statement Range(initial value, condition, increment/decrement value) K.ANGURAJU , AP/CSE
  • 18. Example: n=int (input(“enter the number”)) sum=0 for i in range(1, 6, 1): sum=sum+i print( “the sum of n number is:”, sum) K.ANGURAJU , AP/CSE
  • 19. Loop control statement The loop control statement is control the looping statement . There are following loop control statement are: Break Continue Pass K.ANGURAJU , AP/CSE
  • 20. Break statement Break is a loop control statement . The break statement is used to terminate the loop when the break statement enter inside a loop ,then the loop is exit immediately The break statement can be used in both while and for loop. K.ANGURAJU , AP/CSE
  • 22. Example for character in "ram": if ( character=='a‘): break print(character) Output: r K.ANGURAJU , AP/CSE
  • 23. The continue statement rejects all the remaining statements in the current iteration of the for loop and moves the control back to the top of the loop. When the statement continue is entered into any python loop control automatically passes to the beginning of the loop K.ANGURAJU , AP/CSE
  • 25. Example for character in "ram“ : if ( character == 'a‘ ): continue print(character) Output: r m K.ANGURAJU , AP/CSE
  • 26. Pass statement It is one of the loop control statement . The pass statement is a null operation , nothing happens when it executes. The pass is useful in the place of where your code will eventually go . K.ANGURAJU , AP/CSE
  • 27. Example for character in "ram“ : if ( character == 'a‘ ): pass print(character) Output: r a m K.ANGURAJU , AP/CSE
  • 28. Functions • A function is a block of statement or reusable code that is used to perform a single, related action. • By using function we can divide complex task into manageable task .The function also help to avoid duplication of work. • Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions. K.ANGURAJU , AP/CSE
  • 29. User defined function: User defined function are defined by the user , Depend upon the user requirement user create a function. Elements of user defined function a. Function definition b. Function call K.ANGURAJU , AP/CSE
  • 30. A. Defining a Function • Function blocks begin with the keyword def followed by the function name and parentheses and followed by colon ( ): . • Any input parameters or arguments may be or may not be placed within these parentheses . • Inside the function definition to implement logic of that program. • The statement return() it will return results to called function. K.ANGURAJU , AP/CSE
  • 31. • A return statement with no arguments is represent as return nothing . K.ANGURAJU , AP/CSE
  • 32. Syntax & Example Syntax: def function name( parameters ): local variable declaration logic implementation return (result) Example: >>>def avg( n1,n2,n3 ): #function definition return ((n1+n2+n3)/3) avg(10,25,16) #function call K.ANGURAJU , AP/CSE
  • 33. B . Calling a function Once the basic structure of function is implemented , you can execute it by calling it from another function or directly from the python prompt. K.ANGURAJU , AP/CSE
  • 34. Example: def add(a,b): # function definition c=a+b return(c) result = add(10, 20) # function call print (“addition of two number is”, result) K.ANGURAJU , AP/CSE
  • 35. Parameter passing method in function (pass by reference vs value) 1.Call by value 2. Call by reference All the parameter (arguments) in the python language are passed by reference . It means if you change parameter with in a function , the change also reflects back in the calling function. K.ANGURAJU , AP/CSE
  • 36. Example: #called function def sub(a,b): # function definition c=a+b return(c) # Calling the function result = sub(10, 20) # function call print (“addition of two number is”, result) K.ANGURAJU , AP/CSE
  • 37. Need for user defined functions • The program becomes too large and complex. • The task of debugging, testing and maintenance becomes difficult. To solve this problems: • The program is divided into two parts and each part may be independently coded and later combined into a single program. • These sub-programs are called functions and much easier to understand, debug and test. K.ANGURAJU , AP/CSE
  • 38. Advantages • The length of the source program can be reduced by dividing it into smaller functions. • By using functions it is very easy to locate and debug an error. • Functions processed by top-down programming approach. • Functions avoid coding of repeated programming of the similar instructions. K.ANGURAJU , AP/CSE
  • 39. Flow of Execution • Once a function is called, it takes some data from the calling function and return back some value to the called function. K.ANGURAJU , AP/CSE
  • 40. • Ex : # called function def leap(year): if (year %4 = = 0): # function definition print (“it is leap year”) else: print(“it is not a leap year”) return() # calling function leap(2017) # function call K.ANGURAJU , AP/CSE
  • 41. Function argument • Required function • Keyword arguments • Default arguments K.ANGURAJU , AP/CSE
  • 42. Required function /positional Arguments In this argument required that the argument be passed in function call, the same order as their respective parameters in the function definition header. Example: def display(x) # function definition print(x) return() display() # function call Type error: required positional arguments K.ANGURAJU , AP/CSE
  • 43. Keyword argument: In keyword as a arguments passing each argument in the form of variable name=value. Example: def display(name): #function definition print (name) return() display(name= “Rajesh”)# function call K.ANGURAJU , AP/CSE
  • 44. Default argument # function definition def biodata( name , phno=‘1234567890’): print(“ name: ”, name) print(“ phone number: ”, phno) return() # function call biodata(name=“rajesh”) biodata(name= “rajesh” , phno=“9940805625”) K.ANGURAJU , AP/CSE
  • 45. Types of parameter: 1.Actual parameter: 2.Formal parameter: Example: def add(x,y): local variable logic implementation a=10;b=20 add(a,b) ## function call ANGURAJU.K AP/CSE - KNCET
  • 46. Function definition: Formal parameter def add(x , y) { body of the statement …………….. ………………. return() } ANGURAJU.K AP/CSE - KNCET
  • 47. def add(a,b): # function definition c=a+b return(c) a=10,b=30 result = add(a, b) # function call print (“addition of two number is”, result)
  • 48. Function Prototype 1. Function with no argument and no return value 2. Function with argument and with return value 3. Function with argument and no return value 4. Function with out argument and with return value ANGURAJU.K AP/CSE - KNCET
  • 49. Function with no argument and no return value Here the function call having no argument it cannot send any values to function definition also the function definition cannot send result to function call.
  • 50. Syntax: def function_name(): # function definition body of the function return() function_name() # Function call Example: def display(): print(“welcome”) return() display()
  • 51. Function with argument and with return value Here the function call having argument it can send values to function definition also the function definition can send result to function call.
  • 52. Syntax: def function_name(parameter): # function definition body of the function return(result) function_name(actual parameter) # Function call Example: def add(x,y): c=x+y return(c) add(10,20)
  • 53. Function with argument and no return value Here the function call having argument it can send values to function definition but the function definition cannot send result to function call.
  • 54. Syntax: def function_name( formal parameter): body of the function return() function_name(actual parameter) Example: def add(x,y): c=x+y print(c) return() add(10,20)
  • 55. Function with out argument and with return value Here the function call having no argument it cannot send values to function definition but the function definition can send result to function call.
  • 56. Syntax: def function_name(): body of the function return(result) function_name() Example: def add(): x=10;y=5 c=x+y return(c) result=add() print(result)
  • 57. Recursion Recursion is the process of calling the same function itself again and again until some condition is satisfied . This process is used for repetitive computation in the each action is satisfied in terms of a previous result. K.ANGURAJU , AP/CSE
  • 58. Example: def fact(x): if (x==1): return (1) #function definition else: return (x* fact (x-1)) num=4 print(“factorial value is”, fact(num) ) K.ANGURAJU , AP/CSE
  • 59. Modularizing Code Function can be used to reduce code and enable code reuse. Functions can also be used to modularize code and improve the program quality. A module is a file containing python definitions and statement , the file name is a module name with suffix .py , whenever we want this file import it by import keyword
  • 60. The module can be later imported into a program to reuse. The module file should be placed in the same directory with your other program. The module contain more than one function , Each function in the module must have different name.
  • 61. Example: ( program to create a module to find the Fibonacci numbers upto 10 and addition of two number ) mulfun.py def fib(n): a,b=0,1 while(b<n): print(b , end="") a,b=b,a+b print() def add(x,y): c=x+y print(c) return() ANGURAJU AP/CSE
  • 62. # import the saved file mulpy.py >>> from mulfun import fib >>> fib(10) 112358 >>> from mulfun import add >>> add(10,20) 30
  • 63. Function abstraction Abstraction is used to hide the internal functionality of the function from the users. The users only interact with the basic implementation of the function, but inner working is hidden. User is familiar with that "what function does" but they don't know "how it does."
  • 64. In simple words, we all use the Smartphone and very much familiar with its functions such as camera, voice-recorder, call-dialing, etc., but we don't know how these operations are happening in the background. Example: We already use the predefine function in your program but those implementation only implemented and known by developer.
  • 65. Stepwise refinement When writing large program, you can use “divide-and –conquer” Strategy also known as stepwise refinement • Start with the initial problem statement • Break it into a few general steps • Take each "step", and break it further into more detailed steps • Keep repeating the process on each "step", until you get smaller code.
  • 66. Top-down design • Start with an initial problem statement. • Define subtask at the first level. • Divide subtasks at a higher level into more specific tasks. • Repeat step (3) until each subtask is trivial. • Refine the algorithm into real code.
  • 68. Bottom-up implementation In bottom up approach, we solve smaller problems and integrate it as whole and complete the solution. Mainly used by object oriented programming language such as C++, C#, Python. Redundancy is minimized by using data encapsulation and data hiding.