SlideShare a Scribd company logo
1 of 68
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)
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()
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.
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

Similar to Unit - 2.ppt

[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
yasir_cesc
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
Rajeshkumar Reddy
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
Saurav Kumar
 

Similar to Unit - 2.ppt (20)

arrays.ppt
arrays.pptarrays.ppt
arrays.ppt
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Preprocessor directives
Preprocessor directivesPreprocessor directives
Preprocessor directives
 
C FUNCTIONS
C FUNCTIONSC FUNCTIONS
C FUNCTIONS
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (1).pptx
 
Unit 3 (1)
Unit 3 (1)Unit 3 (1)
Unit 3 (1)
 
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDYC UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
C UNIT-2 PREPARED Y M V BRAHMANANDA REDDY
 
Notes on c++
Notes on c++Notes on c++
Notes on c++
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Presentation 2 (1).pdf
Presentation 2 (1).pdfPresentation 2 (1).pdf
Presentation 2 (1).pdf
 
Function
Function Function
Function
 
Data structure scope of variables
Data structure scope of variablesData structure scope of variables
Data structure scope of variables
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Function C programming
Function C programmingFunction C programming
Function C programming
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Function
FunctionFunction
Function
 
chapter-8-function-overloading.pdf
chapter-8-function-overloading.pdfchapter-8-function-overloading.pdf
chapter-8-function-overloading.pdf
 

More from Kongunadu College of Engineering and Technology

More from Kongunadu College of Engineering and Technology (19)

Unit V - ppt.pptx
Unit V - ppt.pptxUnit V - ppt.pptx
Unit V - ppt.pptx
 
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
C++ UNIT4.pptx
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
UNIT 4.pptx
UNIT 4.pptxUNIT 4.pptx
UNIT 4.pptx
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
UNIT 3.pptx
UNIT 3.pptxUNIT 3.pptx
UNIT 3.pptx
 
Unit - 1.ppt
Unit - 1.pptUnit - 1.ppt
Unit - 1.ppt
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
U1.ppt
U1.pptU1.ppt
U1.ppt
 
U2.ppt
U2.pptU2.ppt
U2.ppt
 
U4.ppt
U4.pptU4.ppt
U4.ppt
 
U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
U3.pptx
U3.pptxU3.pptx
U3.pptx
 

Recently uploaded

Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 

Recently uploaded (20)

BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptxBSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
BSides Seattle 2024 - Stopping Ethan Hunt From Taking Your Data.pptx
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 

Unit - 2.ppt

  • 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)
  • 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()
  • 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.
  • 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.