Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

UNIT III CONTROL FLOW,

FUNCTIONS

Presented by,
S.DHIVYA,
Assistant Professor,
Kongunadu College of Engineering and Technology.
Operators
An operator is symbol that specifies an
operation to be performed on the operands.
Types of operator:
1. Arithmetic operator.
2. Relational Operator.
3. Logical Operator.
4. Assignment Operator.
5. Bitwise Operator.
6. Membership Operators
7. Identity Operators
Arithmetic operator
It provides some arithmetic operators which perform the
task of arithmetic operations in Python. Below some
arithmetic operators

+ , - ,* , / , %
Operator Name Example
+ Addition c=a + b
- Subtraction c=a – b
* Multiplication c=a * b
/ Division c=a / b
% Modulus c=a % b
1. Unary arithmetic:
It require one operand.
Example: +a , -b , -7
2. Binary arithmetic:
It require two operands.
Example: A+B
3. Integer arithmetic:
It require both operands are integer numbers.
Example: 10+20
4. Floating point arithmetic
It require both operands are floating point.
Example: 6.5+7.4
Example program:
a = int ( input (“Enter the a value”))
b= int ( input ( “enter the b value”))
sum = (a + b)
print("Sum of two number is :", sum)
Relational operator
These operators compare the values on either sides of them
and decide the relation among them. They are also known as
comparison operators .
Operator Name Example
< less than a<b
<= less than or equal to a <= b

> greater than a>b


>= greater than or equal to a >= b

== is equal to a == b
!= not equal to a != b
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”)
Logical operators
Python logical operator are used to combine two or
more conditions and perform the logical operations using
Logical AND, Logical OR and Logically NOT.
Logical and
Syntax:
(exp1) and (exp2)
Example:
(a>c) and (a>b)
Logical or
Syntax:
(exp1) or (exp2)
Example:
(a>b) or (a>d)
Logical NOT
29!=29
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”)
Assignment operator

Assignment operator used assign a values of a


variable.
Syntax:
variable= expression or value
Example:
a=10 # assigning value 10 to variable a
b=20
c= a+b
print(“sum of two number is”,c)
Bitwise Operator
Bitwise operator used to manipulate the
data at bit level, it operates on integers only.
it not applicable to float or real.

operator meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement
Bitwise AND (&)
Here operate with two operand bit by bit.
Truth table for & is: & 0 1

0 0 0
Bitwise OR ( |)
1 0 1
| 0 1

0 0 1

1 1 1

Bitwise exclusive OR (^)


^ 0 1
0 0 1

1 1 0
Membership Operators
Python’s membership operators test for
membership in a sequence, such as strings,
lists, or tuples. There are two membership
operators as explained below
in - Evaluates to true if it finds a variable in
the specified sequence and false otherwise.
not in - Evaluates to true if it does not finds a
variable in the specified sequence and false
otherwise
Example

>>> a=[39,24,1.5,33,67,22]
>>> 22 in a
True
>>> 5 not in a
True
>>> s1="welcome"
>>> for word in s1:
print(s1)
Output:
welcome
welcome
welcome
welcome
welcome
welcome
welcome
Identity Operators
Identity operators compare the memory locations of two
objects. There are two Identity operators explained below:
• is
• is not
Example:1
x=20
y=20
if ( x is y):
print (“same identity”)
else:
print (“different identity”)
Example 2:

x=15
y=20
if ( x is not y):
print (“different identity”)
else:
print (“same identity”)
CONDITIONALS
Decision Making and Branching
i. Sequential structure:
Instruction are executed in sequence
i=i+1
j=j+1
ii. Selection structure:
Instructions are executed based on the condition
if(x>y):
i=i+1
else:
j=j+1
iii. Iteration structure (or) loop:
Statements are repeatedly executed. This
forms program loops.
Ex: for i in range(0,5,1):
Print(“hello”)
iv. Encapsulation structure:
It includes other compound structures
Ex: for i in range(0,5,1):
if (condition):
Print(“hello”)
else:
Print(“hai”)
Conditional if statement
If is a decision making statement or control
statement. It is used to control the flow of execution,
also to test logically whether the condition is True or
False.
Syntax: condition
if (condition is true) : False
True statements True
True statement
Example:
a= int ( input ( “enter a:”))
b= int (input (“enter b:”))
if (a>b):
print(“a is big”)
Output:
enter a: 50
enter b: 10
a is big
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.
condition
Syntax: true false
if(condition) :
true statement True statement False statement

else:
false statement
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”)
Chained conditionals (or)Nested if
statement
One conditional can nested with another.
Syntax:
if(condition 1) : Condition False
1

if(condition 2) : True False statement


1
Condition
True statement 2 2

else: True False


False statement
false statement 2 true statement 2 2

else:
false statement1
Example:
a= int ( input ( “enter a:”))
b= int (input (“enter b:”))
c = int (input (“enter c:”))
if (a>b) and (a>c): output:
print(“a is big”) enter a:20
elif (b>c): enter b: 30
print(“b is big”) enter c: 40
else: c is big
print(“c is big”)
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
Types:
1. while statement(entry check loop)(top tested loop).
2. for statement.
3. Nested looping.
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: condition
False
while(condition):
……. True
body of the loop Body of the loop

…….
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
The for loop
This is another one control structure, and it is
execute set of instructions repeatedly until the
condition become false.
Syntax:
for iterating_variable in sequence:
…… no item in sequence
Item from
body of the loop sequence

…… True

execute
Statement
Example:
n=int (input(“enter the number:”))
sum=0
for i in range(0, n, 1):
sum=sum+i
print(“the sum of n number is:”, sum)

out put:
enter the number: 6
the sum of n number is : 15
Loop control statement
• Break
• Continue
• Pass
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.
Flow chart
Example:
for character in "ram":
if ( character==‘a’):
break
print(character)

Output:
r
continue

• The continue statement rejects condition


statement and print 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
Flow chart
Example:
for character in "ram” :
if ( character == ‘a’ ):
continue
print(character)
Output:
r
m
Pass statement
The pass statement is a null operation;
nothing happens when it executes. The pass is
also useful in places where your code will
eventually go .
Example :
for character in "ram“ :
if ( character == 'a‘ ):
pass
print(character)
Output:
r
a
m
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.
Return:
• It is used to return a value to the function.
Syntax:
return [expression]
Example:
def add(x,y):
c=x+y
return c
a=10
b=20
result = add(a,b)
print("addition of two number is", result)
Local / Global variable
• Local variable:
a variable which is declared inside a
function is called as local variable.
• Global variable:
a variable which is declared outside a
function is called as global variable.
Example:
a=10
def dis():
b=20
return b
print(dis())
print(a)
Output:
20
10
Parameter
Parameter -- Data sent to one function to another.
• Formal parameter -- The parameter defined as part
of the function definition
• Actual Parameter -- The actual data sent from calling
function to called function. It happens while the
function calling.
Example:
def add(x,y):
c=x+y
print(“addition of two number is", c)
return
a=10
b=20
add(a,b)
Output:
addition of two number is 30
Function Composition
It is defined as,
• we can call one function within another
function. This ability is called composition.
• In the below example, sub() is a function
which is called within add() function.
• But the arguments are passed from one
function to another function while calling it.
Example:
def sub(x,y):
s=x-y
return s
def add():
a=10
b=20
c=a+b
print("subtraction of two no is", sub(50,25))
return c
print("addition of two no is", add())
String
• A string is sequence of character enclosed with single
or double or triple quotes.
• Ex:
a=“hello”
String access using index value:
>>> a=“mickey mouse”
>>> print(a[3])
k
String methods:
A method is similar to a function, it takes arguments
and returns a value.
String operations/Methods
• join() – to concatenate two strings
>>> print(",".join(["hi","hello"]))
hi , hello
• split() – to split the strings
>>> b=“mickey mouse”
>>> print(b.split())
['mickey', 'mouse‘]
• count() – to count the number of appearance of a character
>>> print(b.count(‘m’))
2
• swapcase() – returns a copy of the string in which all the characters
are case swapped.
>>> c="HI Friends“
>>> print(c.swapcase())
hi fRIENDS
String slices
• A segment of string is called a slice. String works on
slicing operator[:]
>>> a=“mickey mouse”
>>> print(a[0:4])
mick
>>> print(a[7:10])
mou
>>> print(a[:5])
micke
>>> print(a[3:])
key mouse
Strings are immutable
• We cannot change or edit or update a string
directly. So that string is immutable.
• It is tempting to use [ ] operator on the left
side of an assignment with the intension of
changing a character in a string
>>> a=“mickey mouse”
>>> b=‘minnie’ + a[6:12]
>>> print(b)
‘minnie mouse’
Strings Comparison
• To compare two strings. It works with if and
else condition.
• Example:
word=‘PSP’
if word = = ‘PSP’:
print(“matched”)
else:
print(“not matched”)
String Module
• This module contains a number of functions
to process standard python strings.
• To import the module (string) for processing
functions of string
• Ex:
import string
• Example program for performing multiple string
functions by using string module
import string
text=“Hello World”
print(“upper is:”, string.upper(text))
print(“lower is:”, string.lower(text))
print(“after split:”, string.split(text))
print(“replace:”,string.replace(text, “hello”, “hi”)
print(“count is:”, string.count(text, “l”))
List as Array
• Python doesn’t have a native array data
structure, but it has the list, it can be used as a
multidimensional array
• Array- it is an ordered collection of elements
of a single type
• List- it is an ordered collection of any type of
elements

You might also like