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
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
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
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)
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.
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
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.
67.
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.