0% found this document useful (0 votes)
4 views103 pages

Ch No 2 Python Operator & Control Flow-1

Chapter 2 covers Python operators and control flow statements, detailing various types of operators such as arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It also explains control flow statements including conditional statements and loops, providing syntax and examples for each. The chapter emphasizes the importance of operator precedence and associativity in evaluating expressions.

Uploaded by

gamingladybug37
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
4 views103 pages

Ch No 2 Python Operator & Control Flow-1

Chapter 2 covers Python operators and control flow statements, detailing various types of operators such as arithmetic, comparison, assignment, logical, bitwise, membership, and identity operators. It also explains control flow statements including conditional statements and loops, providing syntax and examples for each. The chapter emphasizes the importance of operator precedence and associativity in evaluating expressions.

Uploaded by

gamingladybug37
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 103

Chapter No 2

Python Operators and Control Flow Statements


MARKS:10
Course outcome

► Develop a Python program to demonstrate use of Operators.


What are operators in python?

► An Operator is a set of symbols that performs pre-defined operations


on operators.
► Operators are used to perform operations on variables and values.
► The value that the operator operates on is called the operand.
► Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands
and + is called operator.
Types of Operator

Python language supports the following types of operators.


► Arithmetic Operators
► Comparison (Relational) Operators
► Assignment Operators
► Logical Operators
► Bitwise Operators
► Membership Operators
► Identity Operators
Arithmetic Operators

► Arithmetic operators are used to perform mathematical operations


like addition, subtraction, multiplication etc.
► Arithmetic operators in Python are as follow
Meaning of Arithmetic Operator
Example

Program Output

a,b=10,30
print("addition Operator +:",a+b) addition Operator +: 40
print("subtraction Operator -:",b-a) subtraction Operator -: 20
print("Multiplication Operator *=:",a*b) Multiplication Operator *=:
print("Division Operator /=:",b/a) 300
print("Modulus Operator %=:",b%a) Division Operator /=: 3.0
print("Floor Division Operator //=:",b//a) Modulus Operator %=: 0
Floor Division Operator //=:
3
Comparison (Relational) Operators

► Comparison operators are used to compare values.


► It either returns True or False according to condition.
► Comparison operators in Python are as Follow
Meaning of Comparison Operator
Example

Program Output

a,b=10,30
print("Greater Than Operator Greater Than Operator >: False
>:",a>b) Less Than Operator <: True
print("Less Than Operator Greater Than or equal to Operator
<:",a<b) >=: False
print("Greater Than or equal to Less Than Operator <=: True
Operator >=:",a>=b) Equals To Operator ==: False
print("Less Than Operator not Equals to Operator !=: True
<=:",a<=b)
print("Equals To Operator
==:",a==b)
print("not Equals to Operator !
=:",a!=b)
Assignment Operators

► Assignment operators are used to assign values to variables:


► The Assignment Operator = is used to store right side operand in the
left side operand.
► There are various compound operators in Python like a+=5 hat adds
to the variable and later assigns the same. It is equivalent to a=a+b
► Assignment operators in Python are as Follow
Meaning of Assignment Operator
Example
Program Output

a,b=10,30
a+=b
print("add AND Operator +=:",a) add AND Operator +=: 40
a-=b
print("subtract AND Operator -=:",a) subtract AND Operator -=: 10
a*=b
print("Multiply AND Operator *=:",a) Multiply AND Operator *=: 300
a/=b
print("Division AND Operator /=:",a) Division AND Operator /=:
c=2**3 10.0
print(" Exponent AND Operator **=:",c)
a//=b Exponent AND Operator **=:
print("Floor Division AND Operator 8
//=:",a)
d=30%3 Floor Division AND
print(" Modulus AND Operator **=:",d) Operator //=: 0.0
Modulus AND Operator **=: 0
Logical Operators

► Logical Operator are used to check two or more conditions.


► The Resultant of this operator is always a Boolean value.
► Logical operators are used to combine conditional statements
► Logical operators in Python are as Follow
Example

Program Output

a,b=10,30
print("Logical AND Operator and:",a>b Logical AND Operator and:
and a<b) False
print("Logical OR Operator and:",a>b or Logical OR Operator and:
a<b) True
print("Logical NOT Operator and:",not a>b Logical NOT Operator and:
) True
Bitwise Operators

► Bitwise operator works on bits and performs bit by bit operation


► Assume if a = 60; and b = 13; Now in the binary format their values
will be 0011 1100 and 0000 1101 respectively.
► a=0011 1100
b=0000 1101
a&b = 0 0 0 0 1 1 0 0
a|b = 0 0 1 1 1 1 0 1
a^b = 0 0 1 1 0 0 0 1
~a = 1100 0011
► Bitwise operators in Python are as Follow
Example

Program Output
a,b=4,2
print("Bitewise AND Operator a&b=",a&b) Bitewise AND Operator
print("Bitewise OR Operator a|b=",a|b) a&b= 0
print("Bitewise NOT Operator ~a=",~a) Bitewise OR Operator a|b=
print("Bitewise XOR Operator a^b=",a^b) 6
print("Bitewise LEFT SHIFT Operator Bitewise NOT Operator
a<<b=",a<<b) ~a= -5
print("Bitewise RIGHT Operator Bitewise XOR Operator
a>>b=",a>>b) a^b= 6
Bitewise LEFT SHIFT
Operator a<<b= 16
Bitewise RIGHT Operator
a>>b= 1
Membership Operators

► It is used to check the presence of the element or object in specified


Sequence(String , List, Tuple)
► In a dictionary we can only test for presence of key, not the value.
► Membership Operator are as Follow
Example

Program Output

list=[10,20,"AMIT",30.45]
print("10 is present in list in= ",10 in 10 is present in list in= True
list) 10 is not present in list not in=
print("10 is not present in list not in= False
",10 not in list)
Identity Operators

► Identity operators compare the memory locations of two objects.


► Identity operators are used to compare the objects, not if they are
equal, but if they are actually the same object, with the same
memory location:
► Identity Operator are as Follow
Example

Program Output

a=10
b=10
c=20
print("Does a & b point to same Does a & b point to same
memory location :is= ",a is b) memory location :is= True
print("Does a & c point to same memory Does a & c point to same
location :is not= ",a is not c) memory location :is not= True
Example
a=3
b=3.5
print(a is b)
#Output:False

a=3
b=4
print(a is b)
#Output:False
Example
a=3
b=3
print(a is b)
#Output:True

x=10
print(type(x) is int)
#Output:True

x2='Hello'
y2='Hello'
print (x2 is y2)
#Output:True
x3=[1,2,3]
y3=[1,2,3]
print (x3 is y3)
#Output:False

x3=y3
print (x3 is y3)
True
Precedence of operators

► Operator precedence affects how an expression is evaluated.


► When an expression has two or more operators, we need to identify
the correct sequence to evaluate an expression.
► To evaluate these type of expressions there is a rule of precedence in
Python. It guides the order in which operation are carried out.
► For example, x = 7 + 3 * 2 here, x is assigned 13, not 20 because
operator * has higher precedence than +, so it first multiplies 3*2 and
then adds into 7.
► The following table lists all operators from highest precedence to
lowest.
Operator Precedence

Operator Desciption
** Exponential Operator
*,/,%,// Multipln,Divison,modulus,Floor Division
+,- Addition,Sutraction
<<,>> Bitwise left shift and Right shift
& Bitwise AND
^,| Bitwise XOR & OR
<=,<,>,>= Comparison Operator
<>,==,!= Equality Operator
=,%=,/=,//=,-=,+=,*=,**= Assignment Operator
is ,not is Identity Operator
in ,not in Membership Operator
Associativity

► When two operators have the same precedence, associativity helps to


determine which the order of operations.
► Associativity is the order in which an expression is evaluated that has
multiple operator of the same precedence.
► Almost all the operators have left-to-right associativity.
► For example, multiplication and floor division have the same
precedence. Hence, if both of them are present in an expression, left
one is evaluated first
Example
Control Flow Statement

► The control flow Statement is the order in which the program's code
executes.
► The control flow of a Python program is regulated by conditional
statements, loops, and function calls.
► The Control Flow statements are as
I].Conditional statement or Decision Making Statements.
II].Loop Control Statement or Iterative Statements.
I].Conditional statement or Decision Making
Statements.

► Conditional Statement executes the block of statements based on


correctness of condition.
► If the Condition is true ,then only the block of code is executed ,else it
will skip.
► The Conditional statement or Decision Making Statements are as
Follow
if Statement
if-else statement
if- elif-else statement
nested if statement
if statement

► An if statement consists of a boolean expression followed by one or


more statements.
► If Expression is True, then only block of code is executed, else it will
skip the block.
► Syntax
Python if Statement Flowchart
Example of if statement

# if statement example

if 10 > 5:
print("10 greater than 5")

print("Program ended")
output
if-else statement

► The if-else statement evaluates test expression and will execute


body of if only when test condition is True.
► If the condition is False body of else is executed. Indentation is used
to separate the blocks.
► Syntax of if...else
Python if...else Flowchart
if else example

# if..else statement example


x=3
if x == 4:
print("Yes")
else:
print("No")
output
example
print("number is even or odd")
n=int(input("Enter the number:"))
if n%2==0:
print(n,"is even number")

else:
print(n,"is odd number")

#Output:
number is even or odd
Enter the number:5
5 is odd number
string=input("Enter string:")
if(string==string[::-1]):
print("The string is palindrome")
else:
print("The string is not palindrome")

# [::-1] means start at the end of the string and end at position 0, move with the step -1
, negative one, which means one step backwards.
output
Enter string:madam
The string is palindrome
if...elif...else Statement

► The elif is short for else if. It allows us to check for multiple
expressions.
► If the condition for if is False, it checks the condition of the next elif
block and so on.
► If all the conditions are False, body of else is executed.
► Only one block among the several if...elif...else blocks is executed
according to the condition.
► The if block can have only one else block. But it can have multiple elif
blocks.
► Syntax of if...elif...else
Flowchart of if...elif...else
example
# if-elif statement example
letter = "A"

if letter == "B":
print("letter is B")

elif letter == "C":


print("letter is C")

elif letter == "A":


print("letter is A")

else:
print("letter isn't A, B or C")
output
Nested if statements

► Nested if statements means an if statement inside another if


statement.
► In a nested if construct, you can have an if...elif...else construct
inside another if...elif...else construct.
► Any number of these statements can be nested inside one another.
Indentation is the only way to figure out the level of nesting.
► This can get confusing, so must be avoided if we can.
► Syntax of Nested if Statement
nested if example
i=int(input("Enter value for i:"))

# if condition 1
if i != 0:
# condition 1
if i > 0:
print("Positive")

# condition 2
if i < 0:
print("Negative")
else:
print("Zero")
output
II].Loop Control Statement or
Iterative Statements.
► A loop statement allows us to execute a statement or group of
statements multiple times.
► The following diagram illustrates a loop statement −
► Python provides the following Loop statement
while Loop
for Loop
Nested Loop
While loop

► The while loop in Python is used to iterate over a block of code as


long as the test expression (condition) is true.
► In while loop, test expression is checked first. The body of the loop is
entered only if the test_expression evaluates to True. After one
iteration, the test expression is checked again. This process continues
until the test_expression evaluates to False.
► In Python, the body of the while loop is determined through
indentation.
► Syntax of While Loop
Flowchart of while Loop
Example
i=1
while i < 6:
print(i)
i += 1
output
while loop with else

► Same as that of for loop, we can have an optional else block


with while loop as well.

► The else part is executed if the condition in the while loop


evaluates to False.

► The while loop can be terminated with a break statement. In


such case, the else part is ignored. Hence, a while loop's else
part runs if no break occurs and the condition is false.
► Syntax of while else loop

while test expression:


block
else:
Statement
Example

i=int(input("Enter value of i:"))


while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
For Loop

► The for loop in Python is used to iterate over a sequence (list, tuple, string)
or other iterable objects. Iterating over a sequence is called traversal.
► Syntax:

► Here, val is the variable that takes the value of the item inside the
sequence on each iteration.
► Loop continues until we reach the last item in the sequence. The body of
for loop is separated from the rest of the code using indentation.
Flowchart of for Loop
Example

numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]


sum = 0
for val in numbers:
sum = sum+val
print("The sum is", sum)
Output:
The sum is 48
Example
for i in range(1,11):
print(i)

#Output:
1
2
3
4
5
6
7
8
9
10
range() function
The range() function returns a sequence of numbers,starting from 0 by
default, and increments by 1(by default) and ends at a specified
numbers.

Syntax:range(start,end,step)
where,
start: An integer number specifying at which position to
start.Default is 0.
end:An integer number specifying at which position to
end,which is computed as end-1.This is mandatory argument to
specify.
step:An integer number specifying the increment.Default is 1.
x = range(3, 6)
for n in x:
print(n)
#Output:
3
4
5
Create a sequence of numbers from 3 to 19,
but increment by 2 instead of 1:
x = range(3, 20, 2)
for n in x:
print(n)
#Output:
3
5
7
9
11
13
15
17
19
Example
for i in range(1,11):
print(i,end=' ')

#Output:
1 2 3 4 5 6 7 8 9 10
Example
sum=0
for i in range(0,21,2):
print(i)
sum=sum+i
print("sum=",sum)
Output
#Output:
0
2
4
6
8
10
12
14
16
18
20
sum= 110
print table
n=int(input("Enter a number:"))
for i in range (1,11):
print(n,'*',i,'=',n*i)
output
Enter a number:9
9*1=9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36
9 * 5 = 45
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
9 * 10 = 90
Nested Loop

► nesting a loop means simply having a loop (let's call it outer loop)
that has inside its commands another loop
► Syntax nested for loop
nested for example

for i in range(1,5):
for j in range(1,(i+1)):
print(j,end=' ')
print()
output

1
12
123
1234
► Nested While Loop
Example nested while

i=1
while i<5:
j=1
while j<(i+1):
print(j,end=' ')
j=j+1
i=i+1
print()
output

1
12
123
1234
What is the use of break and continue in Python?

► In Python, break and continue statements can alter the flow of a


normal loop.
► Loops iterate over a block of code until test expression is false, but
sometimes we wish to terminate the current iteration or even the
whole loop without checking test expression.
► The break and continue statements are used in these cases.
Python break statement

► The break statement terminates the loop containing it.


► Control of the program flows to the statement immediately after the
body of the loop.
► If break statement is inside a nested loop (loop inside another loop),
break will terminate the innermost loop.
► Syntax of break
break
Flowchart of break
► The working of break statement in for loop and while loop is shown
below.
Example
for val in "string":
if val == "i":
break
print(val)

print("The end")
#Output:
s
t
r
The end
example break
i=0
while i<10:
i=i+1
if i==5:
break
print("i=",i)
#Output
i= 1
i= 2
i= 3
i= 4
Python continue statement

► The continue statement is used to skip the rest of the code inside a
loop for the current iteration only.
► Loop does not terminate but continues on with the next iteration.
► Syntax
continue
Flowchart of continue
► The working of continue statement in for and while loop is shown
below.
Example
for val in "string":
if val == "i":
continue
print(val)

print("The end")
Output:
s
t
r
n
g
The end
example continue
i=0
while i<10:
i=i+1
if i==5:
continue
print("i=",i)
Output:
i= 1
i= 2
i= 3
i= 4
i= 6
i= 7
i= 8
i= 9
i= 10
pass statement

► In Python programming, pass is a null statement.

► The difference between a comment and pass statement in Python is


that, while the interpreter ignores a comment entirely, pass is not
ignored.

► However, nothing happens when pass is executed. It results into no


operation (NOP).

► We generally use it as a placeholder.


► Syntax
pass

► Suppose we have a loop or a function that is not implemented yet,


but we want to implement it in the future. They cannot have an
empty body. The interpreter would complain. So, we use the pass
statement to construct a body that does nothing.
Example

sequence = {'p', 'a', 's', 's'}


for val in sequence:
pass
Output:
nil
example pass

for i in range(1,11):
if i%2==0:
pass
else:
print("odd numbers:",i)
output
odd numbers: 1
odd numbers: 3
odd numbers: 5
odd numbers: 7
odd numbers: 9
Write a program to print following
1
12
123
1234
for i in range(1,5):
for j in range(1,i+1):
print(j,end=' ')
print()
End

You might also like