SlideShare a Scribd company logo
UNIT – 3
CONTROL FLOW,
FUNCTIONS
Conditionals: Boolean values and operators, conditional (if),
alternative (if-else), chained conditional (if-elif-else); Iteration:
state, while, for, break, continue, pass; Fruitful functions:
return values, parameters, scope: local and global, composition,
recursion; Strings: string slices, immutability, string functions
and methods, string module; Lists as arrays. Illustrative
programs: square root, gcd, exponentiation, sum the array of
numbers, linear search, binary search
BOOLEAN VALUES
 Any object can be tested for truth value, for use in an if or while condition or
as operand of the Boolean operations below.
 The following values are considered false:
 None False Zero of any numeric type, for example, 0, 0L, 0.0, 0j.
 Any empty sequence, for example, ‘’, (), [].
 Any empty mapping, for example, {}.
Boolean Operations (and, or, not)
OPERATORS
 Operators are the constructs (operator) which can manipulate the value of
operands.
 Consider the expression 4 + 5 = 9.
 Here, 4 and 5 are called operands and + is called operator.
Types of Operators
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
OPERATORS PRECEDENCE
DECISION MAKING
 The execution of the program taking action according to the conditions.
 This concept is also known as Conditional statements or Branching
statements.
 Python programming language provides following types of decision making
statements.
Types of Conditional statements
 if statements (conditional)
 if-else statements (alternative)
 if-elif-else (chained conditional)
 Nested Conditional
if statements (conditional)
Example
a=10
if ( a>9):
print(“A is Greater than 9”)
Output
A is Greater than 9
If... Else Statement
Flow chart
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
if...else Example
20
Example:
a=10
b=20
if(a>b):
print(“A is Greater than B”)
else:
print(“B is Greater than A”)
Output:
B is Greater than A
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
The Elif Else Statement
Flow chart
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Example
num = -3
if( num > 0):
print(“Positive number”)
elif (num == 0):
print(“Zero”)
else:
print(“Negative number”)
Output:
Negative number
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Nested Conditionals
Syntax:
if (condition1) :
if (condition2):
statements
else :
statements
else:
statements
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved.
Example:
num = float(input(“Enter a number: “))
if (num >= 0):
if (num == 0):
print(“Zero”)
else:
print(“Positive number”)
else:
print(“Negative number”)
Output :
Enter a number: 5
Positive number
ITERATION
 A loop statement allows us to execute a statement or group of
statements multiple times.
 Repeated execution of a set of statements is called iteration.
 Types
 while loop
 for loop
 nested loop
While Loop
 A while loop statement executes a block of statement again and again until the
condition will occur false .
 It tests the condition before executing the loop body so this technique is
known as Entry controlled loop.
While Loop
Example:
count = 0
while (count < 5):
print (“The count is:”%count)
count = count + 1
print “Good bye!”
Output
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
Good bye!
For Loop :
Executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
UNIT – 3.pptx for first year engineering
Example:
#List of numbers
number=[3,2,5,7,9,1,4,6,8]
#variable to store the sum
total=0
for item in number:
total=total+item
print(“total = %d” %total)
Output:
total= 45
Nested Loops - Python programming language allows
using one loop inside another loop.
Example program to print range values
print(“first loop values”)
for x in range(5):
print(x)
print(“second loop values”)
for x in range(3,6):
print(x)
print(“third loop values”)
for x in range(3,8,2):
print(x)
Output:
first loop values
0
1
2
3
4
second loop values
3
4
5
Third loop values
3
5
7
Iterating by Sequence Index - An alternative way of
iterating through each item is by index offset into the
sequence itself.
Example
fruits = [‘banana’, ‘apple’, ‘mango’]
for index in range(len(fruits)):
print (“Current fruit :”%
fruits[index] )
print “Good bye!”
Output
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
Unconditional Looping Statements
 i) break statement
 ii) continue statement
 iii) pass statement
Break Statement
 Terminates the loop statement and transfers execution to the statement
immediately following the loop.
 The break statement can be used in both while and for loops.
Break
Example
for letter in ‘Python’:
if ( letter == ‘h’):
break
print (“Current Letter : %s” %letter)
Output
Current Letter : P
Current Letter : y
Current Letter : t
Continue Statement
 It returns the control to the beginning of the while loop.
 The continue statement rejects all the remaining statements in the
current iteration of the loop and moves the control back to the top of the
loop.
 The continue statement can be used in both while and for loops.
Continue Statement
Example:
for val in “string” :
if(val==‘i’):
continue
print(val)
print(“the end”)
Output:
s
t
r
n
g
the end
Pass Statement
 The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to execute.
 It execute nothing.
 It is a null statement.
 Difference between a comment and pass statement in python is that,
interpreter ignores a comment entirely but not the pass statement.
 Syntax:
pass
Example
for letter in ‘Python’:
if letter == ‘h’:
pass
print ‘This is pass block’
print ‘Current Letter :’, letter
Output
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
FRUITFUL FUNCTIONS:
 Functions that return values are sometimes called fruitful
functions.
 In many other languages, a function that doesn’t return a value is
called a procedure, but we will stick here with the Python way of
also calling it a function, or if we want to stress it, a non-fruitful
function.
Return Values
 The built-in functions we have used, such as abs, pow, int, max, and
range, have produced results.
 Calling each of these functions generates a value, which we usually
assign to a variable or use as part of an expression.
 Example
 biggest = max(3, 7, 2, 5)x = abs(3 - 11) + 10
Parameters
 Parameter -- Data sent to one function from another.
 Types of parameter:
 Formal parameter -- The parameter defined as part of the function
definition.
 Example: def add(x1,x2): here x1,x2 are formal parameter
 Actual Parameter -- The actual data sent to a function. It’s found in the
function call.
 Example:add(a,b) here a,b are actual parameter
Parameter Passing Method
 Pass-by-value parameter passing
 Pass-by-Reference parameter passing
Pass-by-value parameter passing
 Pass-by-value parameter passing-- the value of the actual parameter is
copied to the formal parameter.
 In Python, scalar values are sent by-value. Lists and other objects are sent by
reference.
def processNumber(x):
x=72
return x+3
# main
y=54
res = processNumber(y)
Pass-by-Reference parameter passing
 It provide reference to the actual parameter is sent to the function.
 When we trace a program, and a list is sent, we don’t copy the list to the
actual parameter box, we draw an arrow from formal to actual.
 Example:
def processList(list):
list[1]=99
# main
aList = [5,2,9]
processList(aList)
Scope of the Variable –
Variable scope and lifetime
 Scope of a variable specifies the part of a program where a variable is
accessible .
 Lifetime of a variable specifies the time period in which the variable has valid
memory.
 Python uses LEGB Rule for Scope resolution.
Local -> Enclosed -> Global -> Built-in
LEGB Rule:
 Local can be inside a function or class method.
 Enclosed can be its enclosing function.e.g. if a function is wrapped inside
another function.
 Global refers to the uppermost level of the executing script itself and
 Built-in are special names that python reserves for itself
Variable:
 A variable can be either of global or local scope.
 A global variable is a variable declared in the main body of the source
code ,outside all functions. It will be visible through out the program.
 A local variable is declared within the body of a function or a block. It is
accessible only inside the function and gets deleted at the end of function.
Example:Variables in different scopes:
# This is a global variable
a = 0
if a == 0:
# This is still a global variable
b = 1
def my_function(c):
# this is a local variable
d = 3
print(c)
print(d)
# Now we call the function, passing the value 7 as the first and only parameter
my_function(7)
# a and b still exist
print(a)
print(b)
# c and d don’t exist anymore -- these statements will give us name errors!
print(c)
print(d)
Scope rules in function
# global scope
a=10
def func(b):
#local scope
c=a+b
return( c )
z=func(1)
print(z)
Global and local Variables in Functions
 Nonlocal Variables:
 Python3 introduced nonlocal variables as a new kind of variables.
 nonlocal variables have a lot in common with global variables.
 One difference to global variables lies in the fact that it is not possible to
change variables from the module scope, i.e. variables which are not defined
inside of a function, by using the nonlocal statement.
 Example
def f():
global x
print(x)
x = 3
f()
Output: 3
 We will change “global” to “nonlocal” in the following program:
def f():
nonlocal x
print(x)
x = 3
f()
Output:
File “example1.py”, line 2
nonlocal x
SyntaxError: no binding for nonlocal ‘x’ found
Function Composition
 It is the ability to call one function from within another function.
 It is a way of combining functions such that the result of each function is
passed as the argument of the next function.
 Example:
Distance between two points of a circle
Sqrt((x2-x1)**2 +(y2-y1)**2)
Distance between two points of a circle
import math
def distance(x1,y1,x2,y2):
result=math.sqrt(((x2-x1)**2)+((y2-y1)**2))
return result
xc=input(“enter x1 value:”))
yc=input(“enter y1 value:”))
xp=input(“enter x2 value:”))
yp=input(“enter y2 value:”))
print(distance(xc,yc,xp,yp))
Boolean functions
 Functions can return booleans, which is often convenient for hiding complicated
tests inside functions.
 They are often used in conditional statements.
 Example
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
is_divisible(6, 4)
Output: False
Recursion
 Recursion is a way of programming in which a function calls itself again
and again until a condition is true.
 A Recursion function calls itself and has a termination condition.
Advantage:
 Recursive functions make the code look clean and elegant.
 A complex task can be broken down into simpler sub-problems using
recursion.
Disadvantage:
 Sometime it is difficult to understand the logic
 It is expensive
 Hard to debug
Example:
def factorial(n):
if (n == 0):
return (1 )
else:
return (n* factorial(n-1))
n=input(“Enter a number:”)
print(“factorial= %d”%n)
Output:
Enter a number :5
Factorial=120
STRINGS
 String are sequence of character enclosing with quotes.
Python treats single quotes the same as double quotes.
 Creating strings is as simple as assigning a value to a
variable.
 Example
var1 = ‘Hello World!’
var2 = “Python Programming”
Accessing values in strings
 To access substrings, use the square brackets for slicing
along with the index or indices to obtain your substring.
 Example
var1 = ‘Hello World!’
var2 = “Python Programming”
print (“var1[0]: “, var1[0])
print (“var2[1:5]: “, var2[1:5])
Output
var1[0]: H
var2[1:5]: ytho
Updating Strings
var1 = ‘Hello World!’
Print( “Updated String :- “, var1[:6] + ‘Python’)
Output:
Updated String :- Hello Python
Escape Characters
UNIT – 3.pptx for first year engineering
String special operators
UNIT – 3.pptx for first year engineering
String formatting operator
 Example
print (“My name is %s and weight is %d kg!” % (‘Zara’, 21))
 Output
My name is Zara and weight is 21 kg!
String formatting operator
Triple Quotes
 The syntax for triple quotes consists of three consecutive single or double
quotes.
 Example:
para_str = “””this is a long string that is made up of several lines and non-
printable characters such as TAB ( t ) and they will show up that way when
displayed.NEWLINEs within the string, whether explicitly given like this
within the brackets [ n ], or just a NEWLINE withinthe variable assignment
will also show up.“””
print( para_str)
 Output:
this is a long string that is made up ofseveral lines and non-printable
characters such asTAB ( ) and they will show up that way when
displayed.NEWLINEs within the string, whether explicitly given likethis
within the brackets [
], or just a NEWLINE withinthe variable assignment will also show up.
String Slices
 The “slice” refer to sub-parts of sequences, typically
strings and lists.
 The slice s[start:end] is the elements beginning at start
and extending up to but not including end
 Example : s = “Hello”
 s[1:4] is ‘ell’
 s[1:] is ‘ello’
 s[:] is ‘Hello’
 s[1:100] is ‘ello’
 s[-1] is ‘o’
 s[-4] is ‘e’
 s[:-3] is ‘He’
 s[-3:] is ‘llo’
String are Immutable
 Strings are immutable, which means you cannot change
an existing string.
 Greeting = “Hello, world!”
 newGreeting = ‘J’ + greeting[1:]
 print(newGreeting)
 print(greeting) # same as it was
 Output
 Jello, world!
 Hello, world!
String Functions and Methods
S.NO Methods Description
1 capitalize() Capitalizes first letter of string
2 isalnum() Returns true if string has at least 1 character
and all characters are alphanumeric and false
otherwise.
3 isalpha() Returns true if string has at least 1 character
and all characters are alphabetic and false
otherwise.
4 isdigit() Returns true if string contains only digits
and false otherwise.
5 islower() Returns true if string has at least 1 cased
character and all cased characters are in
lowercase and false otherwise.
6 isupper() Returns true if string has at least one cased
character and all cased characters are in
uppercase and false otherwise.
7 len(string) Returns the length of the string
String Module
 import string
 text = “Monty Python’s Flying Circus”
 Print( “upper”, “=>”, string.upper(text) )
 print (“lower”, “=>”, string.lower(text) )
 print (“split”, “=>”, string.split(text) )
 print (“join”, “=>”, string.join(string.split(text), “+”) )
 print (“replace”, “=>”, string.replace(text, “Python”, “Java”) )
 print (“find”, “=>”, string.find(text, “Python”), string.find(text, “Java”) )
 print (“count”, “=>”, string.count(text, “n”))
LISTS AS ARRAY
 List basics
 A list in Python is just an ordered collection of items which can be of any
type.
 myList=[1,2,3,4,5,6]
Comprehensions
 A comprehension is roughly speaking just an expression that specifies a sequence
of values think of it as a compact for loop. In Python a comprehension can be used
to generate a list.
 The simplest form of a list comprehension is
 [expression for variable in list]
 Example
To create the list equivalent of a ten-element array you could write:
myList=[0 for i in range(10)]
myList[i]=something
Example:
myList=[i for i in range(10)]
sets myList to [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and
myList=[i*i for i in range(10)]
sets myList to [0, 1, 4, 9, 16, 25, 36, 49, 64, 81].
Two dimensions
for i in range(len(myArray)):
for j in range(len(myArray[i])):
print (myArray[i][j])
Illustrative Program:
GCD of a number
a=int(input(“enter the value for a:”))
b=int(input(“enter the value for b:”))
result = a%b
while result !=0:
a=b
b=result
result= a%b
print(“n GCD of given no. is %d” % (b))
 Output:
enter the value for a:12
enter the value for b:36
GCD of given no. is 12
SQUARE ROOT OF A NUMBER
print(“Square Root Program”)
num = input(“Enter a number: “)
number = float(num)
number_sqrt = number ** 0.5
Print(“Square Root of %d is %0.2f” %(number, number_sqrt))
Output:
Square Root Program
Enter a number:25
Square Root of 25 is 5.00
Sum the array of numbers
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
print(listsum([1,3,5,7,9]))
Output:
25
Linear search
i=0
j=0
count=0
list=[]
N=int(input("Enter the no. of elements"))
while i<N:
item=int(input("Enter your %d elements to the list:"%(i)))
list. append(item)
i=i+1
search=int(input("Enter the element to search:"))
while j<N:
if(search==list[j]):
count=1
j=j+1
if(count==1):
print("The element %d is present in the list"%search)
else:
print("The element %d is not present in the list"%search)
Binary search
def binary_search(sortedlist,n,x):
start = 0
end = n - 1
for i in sortedlist:
while(start <= end):
mid = int((start + end)/2)
if (x == int(sortedlist[mid])):
return mid
elif(x < int(sortedlist[mid])):
end = mid - 1
else:
start = mid + 1
return -1
n = int(input("Enter the size of the list: "))
sortedlist = []
for i in range(n):
sortedlist.append(input())
print(sortedlist)
x = int(input("Enter the number to search: "))
position = binary_search(sortedlist,n,x)
if(position != -1):
print("Entered number %d is present at
position: %d"%(x,position))
else:
print("Entered number %d is not present in
the list"%x)
Exponentiation Program
 base=int(input('Enter the base value:'))
 exp=int(input('Enter the exponent value:'))
 res=1
 for _ in range(exp):
 res=res*base
 print("n Exponentiation using loop:",res)


 # Direct method to find Exponentiation
 factor=base ** exp
 print("nFactor is:",factor)


Ad

More Related Content

Similar to UNIT – 3.pptx for first year engineering (20)

Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
jaba kumar
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
MKalpanaDevi
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
paijitk
 
Python-review1 for begineers to code.ppt
Python-review1 for begineers to code.pptPython-review1 for begineers to code.ppt
Python-review1 for begineers to code.ppt
freyjadexon608
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
snowflakebatch
 
cp Module4(1)
cp Module4(1)cp Module4(1)
cp Module4(1)
Amarjith C K
 
Python_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptxPython_Unit-1_PPT_Data Types.pptx
Python_Unit-1_PPT_Data Types.pptx
SahajShrimal1
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
2. operator
2. operator2. operator
2. operator
Shankar Gangaju
 
functions
functionsfunctions
functions
Makwana Bhavesh
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
kailashGusain3
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
RiteshKumarPradhan1
 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
PhanMinhLinhAnxM0190
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
RohitSindhu10
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
AkashdeepBhattacharj1
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
SulekhJangra
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
MikialeTesfamariam
 
Python Session - 4
Python Session - 4Python Session - 4
Python Session - 4
AnirudhaGaikwad4
 

Recently uploaded (20)

Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation RateModeling the Influence of Environmental Factors on Concrete Evaporation Rate
Modeling the Influence of Environmental Factors on Concrete Evaporation Rate
Journal of Soft Computing in Civil Engineering
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink DisplayHow to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
CircuitDigest
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Using the Artificial Neural Network to Predict the Axial Strength and Strain ...
Journal of Soft Computing in Civil Engineering
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
PawachMetharattanara
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Personal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.pptPersonal Protective Efsgfgsffquipment.ppt
Personal Protective Efsgfgsffquipment.ppt
ganjangbegu579
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdfDavid Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry - Specializes In AWS, Microservices And Python.pdf
David Boutry
 
Design of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdfDesign of Variable Depth Single-Span Post.pdf
Design of Variable Depth Single-Span Post.pdf
Kamel Farid
 
Nanometer Metal-Organic-Framework Literature Comparison
Nanometer Metal-Organic-Framework  Literature ComparisonNanometer Metal-Organic-Framework  Literature Comparison
Nanometer Metal-Organic-Framework Literature Comparison
Chris Harding
 
acid base ppt and their specific application in food
acid base ppt and their specific application in foodacid base ppt and their specific application in food
acid base ppt and their specific application in food
Fatehatun Noor
 
Construction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil EngineeringConstruction Materials (Paints) in Civil Engineering
Construction Materials (Paints) in Civil Engineering
Lavish Kashyap
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink DisplayHow to Build a Desktop Weather Station Using ESP32 and E-ink Display
How to Build a Desktop Weather Station Using ESP32 and E-ink Display
CircuitDigest
 
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdfML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
ML_Unit_VI_DEEP LEARNING_Introduction to ANN.pdf
rameshwarchintamani
 
2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt2.3 Genetically Modified Organisms (1).ppt
2.3 Genetically Modified Organisms (1).ppt
rakshaiya16
 
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
01.คุณลักษณะเฉพาะของอุปกรณ์_pagenumber.pdf
PawachMetharattanara
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjjseninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
seninarppt.pptx1bhjiikjhggghjykoirgjuyhhhjj
AjijahamadKhaji
 
Ad

UNIT – 3.pptx for first year engineering

  • 1. UNIT – 3 CONTROL FLOW, FUNCTIONS
  • 2. Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions: return values, parameters, scope: local and global, composition, recursion; Strings: string slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative programs: square root, gcd, exponentiation, sum the array of numbers, linear search, binary search
  • 3. BOOLEAN VALUES  Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below.  The following values are considered false:  None False Zero of any numeric type, for example, 0, 0L, 0.0, 0j.  Any empty sequence, for example, ‘’, (), [].  Any empty mapping, for example, {}.
  • 5. OPERATORS  Operators are the constructs (operator) which can manipulate the value of operands.  Consider the expression 4 + 5 = 9.  Here, 4 and 5 are called operands and + is called operator.
  • 6. Types of Operators  Arithmetic Operators  Comparison (Relational) Operators  Assignment Operators  Logical Operators  Bitwise Operators  Membership Operators  Identity Operators
  • 15. DECISION MAKING  The execution of the program taking action according to the conditions.  This concept is also known as Conditional statements or Branching statements.  Python programming language provides following types of decision making statements.
  • 16. Types of Conditional statements  if statements (conditional)  if-else statements (alternative)  if-elif-else (chained conditional)  Nested Conditional
  • 18. Example a=10 if ( a>9): print(“A is Greater than 9”) Output A is Greater than 9
  • 20. © Copyright 2012 by Pearson Education, Inc. All Rights Reserved. if...else Example 20 Example: a=10 b=20 if(a>b): print(“A is Greater than B”) else: print(“B is Greater than A”) Output: B is Greater than A
  • 21. © Copyright 2012 by Pearson Education, Inc. All Rights Reserved. The Elif Else Statement Flow chart
  • 22. © Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Example num = -3 if( num > 0): print(“Positive number”) elif (num == 0): print(“Zero”) else: print(“Negative number”) Output: Negative number
  • 23. © Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Nested Conditionals Syntax: if (condition1) : if (condition2): statements else : statements else: statements
  • 24. © Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Example: num = float(input(“Enter a number: “)) if (num >= 0): if (num == 0): print(“Zero”) else: print(“Positive number”) else: print(“Negative number”) Output : Enter a number: 5 Positive number
  • 25. ITERATION  A loop statement allows us to execute a statement or group of statements multiple times.  Repeated execution of a set of statements is called iteration.  Types  while loop  for loop  nested loop
  • 26. While Loop  A while loop statement executes a block of statement again and again until the condition will occur false .  It tests the condition before executing the loop body so this technique is known as Entry controlled loop.
  • 28. Example: count = 0 while (count < 5): print (“The count is:”%count) count = count + 1 print “Good bye!” Output The count is: 0 The count is: 1 The count is: 2 The count is: 3 The count is: 4 Good bye!
  • 29. For Loop : Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
  • 31. Example: #List of numbers number=[3,2,5,7,9,1,4,6,8] #variable to store the sum total=0 for item in number: total=total+item print(“total = %d” %total) Output: total= 45
  • 32. Nested Loops - Python programming language allows using one loop inside another loop.
  • 33. Example program to print range values print(“first loop values”) for x in range(5): print(x) print(“second loop values”) for x in range(3,6): print(x) print(“third loop values”) for x in range(3,8,2): print(x) Output: first loop values 0 1 2 3 4 second loop values 3 4 5 Third loop values 3 5 7
  • 34. Iterating by Sequence Index - An alternative way of iterating through each item is by index offset into the sequence itself. Example fruits = [‘banana’, ‘apple’, ‘mango’] for index in range(len(fruits)): print (“Current fruit :”% fruits[index] ) print “Good bye!” Output Current fruit : banana Current fruit : apple Current fruit : mango Good bye!
  • 35. Unconditional Looping Statements  i) break statement  ii) continue statement  iii) pass statement
  • 36. Break Statement  Terminates the loop statement and transfers execution to the statement immediately following the loop.  The break statement can be used in both while and for loops.
  • 37. Break
  • 38. Example for letter in ‘Python’: if ( letter == ‘h’): break print (“Current Letter : %s” %letter) Output Current Letter : P Current Letter : y Current Letter : t
  • 39. Continue Statement  It returns the control to the beginning of the while loop.  The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.  The continue statement can be used in both while and for loops.
  • 41. Example: for val in “string” : if(val==‘i’): continue print(val) print(“the end”) Output: s t r n g the end
  • 42. Pass Statement  The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.  It execute nothing.  It is a null statement.  Difference between a comment and pass statement in python is that, interpreter ignores a comment entirely but not the pass statement.  Syntax: pass
  • 43. Example for letter in ‘Python’: if letter == ‘h’: pass print ‘This is pass block’ print ‘Current Letter :’, letter Output Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n
  • 44. FRUITFUL FUNCTIONS:  Functions that return values are sometimes called fruitful functions.  In many other languages, a function that doesn’t return a value is called a procedure, but we will stick here with the Python way of also calling it a function, or if we want to stress it, a non-fruitful function.
  • 45. Return Values  The built-in functions we have used, such as abs, pow, int, max, and range, have produced results.  Calling each of these functions generates a value, which we usually assign to a variable or use as part of an expression.  Example  biggest = max(3, 7, 2, 5)x = abs(3 - 11) + 10
  • 46. Parameters  Parameter -- Data sent to one function from another.  Types of parameter:  Formal parameter -- The parameter defined as part of the function definition.  Example: def add(x1,x2): here x1,x2 are formal parameter  Actual Parameter -- The actual data sent to a function. It’s found in the function call.  Example:add(a,b) here a,b are actual parameter
  • 47. Parameter Passing Method  Pass-by-value parameter passing  Pass-by-Reference parameter passing
  • 48. Pass-by-value parameter passing  Pass-by-value parameter passing-- the value of the actual parameter is copied to the formal parameter.  In Python, scalar values are sent by-value. Lists and other objects are sent by reference. def processNumber(x): x=72 return x+3 # main y=54 res = processNumber(y)
  • 49. Pass-by-Reference parameter passing  It provide reference to the actual parameter is sent to the function.  When we trace a program, and a list is sent, we don’t copy the list to the actual parameter box, we draw an arrow from formal to actual.  Example: def processList(list): list[1]=99 # main aList = [5,2,9] processList(aList)
  • 50. Scope of the Variable – Variable scope and lifetime  Scope of a variable specifies the part of a program where a variable is accessible .  Lifetime of a variable specifies the time period in which the variable has valid memory.  Python uses LEGB Rule for Scope resolution. Local -> Enclosed -> Global -> Built-in
  • 51. LEGB Rule:  Local can be inside a function or class method.  Enclosed can be its enclosing function.e.g. if a function is wrapped inside another function.  Global refers to the uppermost level of the executing script itself and  Built-in are special names that python reserves for itself
  • 52. Variable:  A variable can be either of global or local scope.  A global variable is a variable declared in the main body of the source code ,outside all functions. It will be visible through out the program.  A local variable is declared within the body of a function or a block. It is accessible only inside the function and gets deleted at the end of function.
  • 53. Example:Variables in different scopes: # This is a global variable a = 0 if a == 0: # This is still a global variable b = 1 def my_function(c): # this is a local variable d = 3 print(c) print(d) # Now we call the function, passing the value 7 as the first and only parameter my_function(7) # a and b still exist print(a) print(b) # c and d don’t exist anymore -- these statements will give us name errors! print(c) print(d)
  • 54. Scope rules in function # global scope a=10 def func(b): #local scope c=a+b return( c ) z=func(1) print(z)
  • 55. Global and local Variables in Functions  Nonlocal Variables:  Python3 introduced nonlocal variables as a new kind of variables.  nonlocal variables have a lot in common with global variables.  One difference to global variables lies in the fact that it is not possible to change variables from the module scope, i.e. variables which are not defined inside of a function, by using the nonlocal statement.  Example def f(): global x print(x) x = 3 f() Output: 3
  • 56.  We will change “global” to “nonlocal” in the following program: def f(): nonlocal x print(x) x = 3 f() Output: File “example1.py”, line 2 nonlocal x SyntaxError: no binding for nonlocal ‘x’ found
  • 57. Function Composition  It is the ability to call one function from within another function.  It is a way of combining functions such that the result of each function is passed as the argument of the next function.  Example: Distance between two points of a circle Sqrt((x2-x1)**2 +(y2-y1)**2)
  • 58. Distance between two points of a circle import math def distance(x1,y1,x2,y2): result=math.sqrt(((x2-x1)**2)+((y2-y1)**2)) return result xc=input(“enter x1 value:”)) yc=input(“enter y1 value:”)) xp=input(“enter x2 value:”)) yp=input(“enter y2 value:”)) print(distance(xc,yc,xp,yp))
  • 59. Boolean functions  Functions can return booleans, which is often convenient for hiding complicated tests inside functions.  They are often used in conditional statements.  Example def is_divisible(x, y): if x % y == 0: return True else: return False is_divisible(6, 4) Output: False
  • 60. Recursion  Recursion is a way of programming in which a function calls itself again and again until a condition is true.  A Recursion function calls itself and has a termination condition. Advantage:  Recursive functions make the code look clean and elegant.  A complex task can be broken down into simpler sub-problems using recursion. Disadvantage:  Sometime it is difficult to understand the logic  It is expensive  Hard to debug
  • 61. Example: def factorial(n): if (n == 0): return (1 ) else: return (n* factorial(n-1)) n=input(“Enter a number:”) print(“factorial= %d”%n) Output: Enter a number :5 Factorial=120
  • 62. STRINGS  String are sequence of character enclosing with quotes. Python treats single quotes the same as double quotes.  Creating strings is as simple as assigning a value to a variable.  Example var1 = ‘Hello World!’ var2 = “Python Programming”
  • 63. Accessing values in strings  To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring.  Example var1 = ‘Hello World!’ var2 = “Python Programming” print (“var1[0]: “, var1[0]) print (“var2[1:5]: “, var2[1:5]) Output var1[0]: H var2[1:5]: ytho
  • 64. Updating Strings var1 = ‘Hello World!’ Print( “Updated String :- “, var1[:6] + ‘Python’) Output: Updated String :- Hello Python
  • 69. String formatting operator  Example print (“My name is %s and weight is %d kg!” % (‘Zara’, 21))  Output My name is Zara and weight is 21 kg!
  • 71. Triple Quotes  The syntax for triple quotes consists of three consecutive single or double quotes.  Example: para_str = “””this is a long string that is made up of several lines and non- printable characters such as TAB ( t ) and they will show up that way when displayed.NEWLINEs within the string, whether explicitly given like this within the brackets [ n ], or just a NEWLINE withinthe variable assignment will also show up.“”” print( para_str)  Output: this is a long string that is made up ofseveral lines and non-printable characters such asTAB ( ) and they will show up that way when displayed.NEWLINEs within the string, whether explicitly given likethis within the brackets [ ], or just a NEWLINE withinthe variable assignment will also show up.
  • 72. String Slices  The “slice” refer to sub-parts of sequences, typically strings and lists.  The slice s[start:end] is the elements beginning at start and extending up to but not including end  Example : s = “Hello”  s[1:4] is ‘ell’  s[1:] is ‘ello’  s[:] is ‘Hello’  s[1:100] is ‘ello’  s[-1] is ‘o’  s[-4] is ‘e’  s[:-3] is ‘He’  s[-3:] is ‘llo’
  • 73. String are Immutable  Strings are immutable, which means you cannot change an existing string.  Greeting = “Hello, world!”  newGreeting = ‘J’ + greeting[1:]  print(newGreeting)  print(greeting) # same as it was  Output  Jello, world!  Hello, world!
  • 74. String Functions and Methods S.NO Methods Description 1 capitalize() Capitalizes first letter of string 2 isalnum() Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. 3 isalpha() Returns true if string has at least 1 character and all characters are alphabetic and false otherwise. 4 isdigit() Returns true if string contains only digits and false otherwise. 5 islower() Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. 6 isupper() Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise. 7 len(string) Returns the length of the string
  • 75. String Module  import string  text = “Monty Python’s Flying Circus”  Print( “upper”, “=>”, string.upper(text) )  print (“lower”, “=>”, string.lower(text) )  print (“split”, “=>”, string.split(text) )  print (“join”, “=>”, string.join(string.split(text), “+”) )  print (“replace”, “=>”, string.replace(text, “Python”, “Java”) )  print (“find”, “=>”, string.find(text, “Python”), string.find(text, “Java”) )  print (“count”, “=>”, string.count(text, “n”))
  • 76. LISTS AS ARRAY  List basics  A list in Python is just an ordered collection of items which can be of any type.  myList=[1,2,3,4,5,6]
  • 77. Comprehensions  A comprehension is roughly speaking just an expression that specifies a sequence of values think of it as a compact for loop. In Python a comprehension can be used to generate a list.  The simplest form of a list comprehension is  [expression for variable in list]  Example To create the list equivalent of a ten-element array you could write: myList=[0 for i in range(10)] myList[i]=something
  • 78. Example: myList=[i for i in range(10)] sets myList to [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and myList=[i*i for i in range(10)] sets myList to [0, 1, 4, 9, 16, 25, 36, 49, 64, 81].
  • 79. Two dimensions for i in range(len(myArray)): for j in range(len(myArray[i])): print (myArray[i][j])
  • 80. Illustrative Program: GCD of a number a=int(input(“enter the value for a:”)) b=int(input(“enter the value for b:”)) result = a%b while result !=0: a=b b=result result= a%b print(“n GCD of given no. is %d” % (b))  Output: enter the value for a:12 enter the value for b:36 GCD of given no. is 12
  • 81. SQUARE ROOT OF A NUMBER print(“Square Root Program”) num = input(“Enter a number: “) number = float(num) number_sqrt = number ** 0.5 Print(“Square Root of %d is %0.2f” %(number, number_sqrt)) Output: Square Root Program Enter a number:25 Square Root of 25 is 5.00
  • 82. Sum the array of numbers def listsum(numList): if len(numList) == 1: return numList[0] else: return numList[0] + listsum(numList[1:]) print(listsum([1,3,5,7,9])) Output: 25
  • 83. Linear search i=0 j=0 count=0 list=[] N=int(input("Enter the no. of elements")) while i<N: item=int(input("Enter your %d elements to the list:"%(i))) list. append(item) i=i+1 search=int(input("Enter the element to search:")) while j<N: if(search==list[j]): count=1 j=j+1 if(count==1): print("The element %d is present in the list"%search) else: print("The element %d is not present in the list"%search)
  • 84. Binary search def binary_search(sortedlist,n,x): start = 0 end = n - 1 for i in sortedlist: while(start <= end): mid = int((start + end)/2) if (x == int(sortedlist[mid])): return mid elif(x < int(sortedlist[mid])): end = mid - 1 else: start = mid + 1 return -1 n = int(input("Enter the size of the list: ")) sortedlist = [] for i in range(n): sortedlist.append(input()) print(sortedlist) x = int(input("Enter the number to search: ")) position = binary_search(sortedlist,n,x) if(position != -1): print("Entered number %d is present at position: %d"%(x,position)) else: print("Entered number %d is not present in the list"%x)
  • 85. Exponentiation Program  base=int(input('Enter the base value:'))  exp=int(input('Enter the exponent value:'))  res=1  for _ in range(exp):  res=res*base  print("n Exponentiation using loop:",res)    # Direct method to find Exponentiation  factor=base ** exp  print("nFactor is:",factor)  
  翻译: