0% found this document useful (0 votes)
55 views64 pages

Unit Ii - Python Operators and Control Flow Statements

This document discusses Python operators and control flow statements. It describes different types of operators in Python like arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. It provides examples of using each operator type and explains operator precedence. The document also introduces control flow in Python, which is regulated using conditional statements, loops, and functions to control the order of code execution.
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)
55 views64 pages

Unit Ii - Python Operators and Control Flow Statements

This document discusses Python operators and control flow statements. It describes different types of operators in Python like arithmetic, assignment, comparison, logical, identity, membership, and bitwise operators. It provides examples of using each operator type and explains operator precedence. The document also introduces control flow in Python, which is regulated using conditional statements, loops, and functions to control the order of code execution.
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/ 64

UNIT II

PYTHON OPERATORS AND CONTROL FLOW


STATEMENTS 10M
BASIC OPERATORS
🞆Operators are special symbols in Python that carry out
arithmetic or logical computation.
🞆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
1. ARITHMETIC OPERATORS
ARITHMETIC OPERATORS ARE USED TO PERFORM MATHEMATICAL OPERATIONS LIKE ADDITION, SUBTRACTION,
MULTIPLICATION, ETC.

Operator Meaning Example


Add two operands or unary
+ x+y +2
plus

Subtract right operand from


- x–y -2
the left or unary minus

* Multiply two operands x*y

Divide left operand by the


/ right one (always results x/y
into float)

Modulus - remainder of the


% division of left operand by x % y (remainder of x/y)
the right

Floor division - division that


results into whole number
// x // y
adjusted to the left in the
number line

Exponent - left operand


** x**y (x to the power y)
raised to the power of right
EXAMPLE : ARITHMETIC OPERATORS IN
PYTHON
x = 15
y=4

# Output: x + y = 19
print('x + y =',x+y)

# Output: x - y = 11
print('x - y =',x-y)

# Output: x * y = 60
print('x * y =',x*y)

# Output: x / y = 3.75
print('x / y =',x/y)

# Output: x // y = 3
print('x // y =',x//y)

# Output: x ** y = 50625
print('x ** y =',x**y)
2. ASSIGNMENT OPERATORS
ASSIGNMENT OPERATORS ARE USED IN PYTHON TO ASSIGN VALUES TO VARIABLES.
A = 5 IS A SIMPLE ASSIGNMENT OPERATOR THAT ASSIGNS THE VALUE 5 ON THE RIGHT TO THE
VARIABLE A ON THE LEFT.
THERE ARE VARIOUS COMPOUND OPERATORS IN PYTHON LIKE A += 5 THAT ADDS TO THE
VARIABLE AND LATER ASSIGNS THE SAME. IT IS EQUIVALENT TO A = A + 5

Operator Example Equivalent to


= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
3. COMPARISON /RELATIONAL OPERATORS
COMPARISON OPERATORS ARE USED TO COMPARE VALUES. IT RETURNS
EITHER TRUE OR FALSE ACCORDING TO THE CONDITION.

Operator Meaning Example


Greater than - True if left
> operand is greater than the x>y
right

Less than - True if left operand


< x<y
is less than the right

Equal to - True if both operands


== x == y
are equal

Not equal to - True if operands


!= x != y
are not equal

Greater than or equal to - True


>= if left operand is greater than or x >= y
equal to the right

Less than or equal to - True if


<= left operand is less than or x <= y
equal to the right
EXAMPLE : COMPARISON OPERATORS IN PYTHON

x = 10
y = 12

# Output: x > y is False


print('x > y is‘,x>y)

# Output: x < y is True


print('x < y is‘,x<y)

# Output: x == y is False
print('x == y is‘,x==y)

# Output: x != y is True
print('x != y is‘,x!=y)

# Output: x >= y is False


print('x >= y is',x>=y)

# Output: x <= y is True


print('x <= y is‘,x<=y)
4. LOGICAL OPERATORS
THE LOGICAL OPERATORS ARE USED PRIMARILY IN THE EXPRESSION EVALUATION TO MAKE A DECISION

Operator Meaning Example

True if both the


and x and y
operands are true

True if either of the


or x or y
operands is true

True if operand is
false
not not x
(complements the
operand)
EXAMPLE : LOGICAL OPERATORS
IN PYTHON

x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',not x)
5. IDENTITY OPERATORS
IS AND IS NOT ARE THE IDENTITY OPERATORS IN PYTHON. THEY ARE USED TO CHECK IF TWO VALUES (OR VARIABLES) ARE
LOCATED ON THE SAME PART OF THE MEMORY. TWO VARIABLES THAT ARE EQUAL DOES NOT IMPLY THAT THEY ARE IDENTICAL.

Operator Meaning Example

True if the operands


is are identical (refer x is True
to the same object)

True if the operands


are not identical (do
is not x is not True
not refer to the
same object)
EXAMPLE : IDENTITY OPERATORS
IN PYTHON
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'

# Output: False
print(x1 is not y1)

# Output: True
print(x2 is y2)
6.MEMBERSHIP OPERATORS
IN AND NOT IN ARE THE MEMBERSHIP OPERATORS IN PYTHON.
THEY ARE USED TO TEST WHETHER A VALUE OR VARIABLE IS
FOUND IN A SEQUENCE
(STRING, LIST, TUPLE, SET AND DICTIONARY).
IN A DICTIONARY WE CAN ONLY TEST FOR PRESENCE OF KEY,
NOT THE VALUE.

Operator Meaning Example

True if
value/variable is
in 5 in x
found in the
sequence

True if
value/variable is not
not in 5 not in x
found in the
sequence
EXAMPLE : MEMBERSHIP
OPERATORS IN PYTHON
x = 'Hello world'
y = {1:'a',2:'b'}

# Output: True
print('H' in x)

# Output: True
print('hello' not in x)

# Output: True
print(1 in y)

# Output: False
print('a' in y)
7. BITWISE OPERATORS
BITWISE OPERATORS ACT ON OPERANDS AS IF THEY WERE
STRINGS OF BINARY DIGITS. THEY OPERATE BIT BY BIT, HENCE
THE NAME.
FOR EXAMPLE, 2 IS 10 IN BINARY AND 7 IS 111.
IN THE TABLE BELOW: LET X = 10 (0000 1010 IN BINARY) AND Y =
4 (0000 0100 IN BINARY)

Operator Meaning Example

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)


PYTHON OPERATOR PRECEDENCE
🞆Operator Precedence: This is used in an expression with
more than one operator with different precedence to determine
which operation to perform first.
🞆Example: Solve
10 + 20 * 30
10 + 20 * 30 is calculated as 10 + (20 * 30) and not as (10 + 20)
* 30
OPERATOR ASSOCIATIVITY:
🞆 If an expression contains two or more operators with the
same precedence then Operator Associativity is used to
determine. It can either be Left to Right or from Right
to Left.
🞆Example: ‘*’ and ‘/’ have the same precedence and their
associativity is Left to Right, so the expression “100 / 10
* 10” is treated as “(100 / 10) * 10”.
THE OPERATOR PRECEDENCE IN PYTHON IS LISTED IN THE
FOLLOWING TABLE. IT IS IN DESCENDING ORDER (UPPER GROUP
HAS HIGHER PRECEDENCE THAN THE LOWER ONES).
CONTROL FLOW:-

🞆A program’s control flow 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.
🞆Python has three types of control structures:
⚫ Sequential - default mode
⚫ Selection - used for decisions and branching
⚫ Repetition - used for looping, i.e., repeating a piece of code
multiple times.
1. SEQUENTIAL
🞆Sequential statements are a set of statements whose
execution process happens in a sequence.
🞆The problem with sequential statements is that if the logic
has broken in any one of the lines, then the complete source
code execution will break.
⚫ #This is a Sequential statement

a=20
b=10
c=a-b
print("Subtraction is : ",c)
2. SELECTION/DECISION CONTROL STATEMENTS/CONDITIONAL STATEMENTS

🞆The selection statement allows a program to test several


conditions and execute instructions based on which condition
is true.
🞆Some Decision Control Statements are:
• Simple if
• if-else
• nested if
• if-elif-else
IF STATEMENT:
🞆Decision making is required when we want to execute a
code only if a certain condition is satisfied.
🞆Python if Statement Syntax
if testexpression:

statement(s)
🞆Python if Statement Flowchart
EXAMPLE OF IF
#wap to check number is even or odd using IF
n = 10
if n % 2 == 0:
print("n is an even number")

🞆Output
n is an even number
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

if test expression:

Body of if

else:
Body of else
PYTHON IF..ELSE FLOWCHART
EXAMPLE OF IF-ELSE
n=5
if n % 2 == 0:
print("n is even")
else:
print("n is odd")

🞆Output
n is odd
PYTHON 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
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
FLOWCHART OF IF...ELIF...ELSE
EXAMPLE OF IF..ELIF..ELSE

x = 15
y = 12
if x == y:
print("Both are Equal")
elif x > y:
print("x is greater than y")
else:
print("x is smaller than y")
NESTED IF STATEMENTS

🞆We can have a if...elif...else statement inside another


if...elif...else statement. This is called nesting in
computer programming.
🞆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 ...ELSE
if test expression:
if test expression:
Statements
else :
Statements
else :
statements
EXAMPLE OF NESTED IF
#WAP TO FIND ENETERED NUMBER IS POSITIVE
NEGATIVE OR ZERO
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
3. REPETITION/LOOPING
🞆A repetition statement is used to repeat a group(block)
of programming instructions.
🞆The three types of loops in Python programming are:
⚫ while loop
⚫ for loop
⚫ nested loops
FOR LOOP:
🞆The for loop in Python is used to iterate the statements or a part
of the program several times.
🞆Iterating over a sequence is called traversal.
🞆It is frequently used to traverse the data structures like list,
tuple, or dictionary.
🞆Syntax of for Loop:
for val in sequence:
Body of for
🞆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 1
# Iterating string using for loop
str = "Python"
for i in str:
print(i)
🞆Output:
P
y
t
h
o
n
EXAMPLE- 2: PROGRAM TO PRINT THE TABLE
OF THE GIVEN NUMBER .
list = [1,2,3,4,5,6,7,8,9,10]
n=5
for i in list:
c = n*i
print(c)

Output:
5
10
15
20
25
30
35
40
45
50
FOR LOOP USING RANGE() FUNCTION
🞆The range() function is used to generate the sequence of the
numbers. If we pass the range(10), it will generate the numbers
from 0 to 9. The syntax of the range() function is given below.
🞆Syntax:
⚫ range(start,stop,step size)
🞆The start represents the beginning of the iteration.
🞆The stop represents that the loop will iterate till
stop-1. The range(1,5) will generate numbers 1 to 4
iterations. It is optional.
🞆The step size is used to skip the specific numbers from the
iteration. It is optional to use. By default, the step size is 1.
EXAMPLE : PROGRAM TO PRINT TABLE OF GIVEN
NUMBER.
n = int(input("Enter the number "))
for i in range(1,11):
c = n*i
print(n,"*",i,"=",c)
🞆 Output:

🞆 Enter the number 10

10 * 1 = 10
10 * 2 = 20
10 * 3 = 30
10 * 4 = 40
10 * 5 = 50
10 * 6 = 60
10 * 7 = 70
10 * 8 = 80
10 * 9 = 90
FOR LOOP WITH ELSE
🞆 A for loop can have an optional else block as well. The else part is
executed if the items in the sequence used in for loop exhausts.
🞆 break statement can be used to stop a for loop. In such case, the else part
is ignored.
🞆 Hence, a for loop's else part runs if no break occurs.

🞆 Here is an example to illustrate this.

digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
🞆 Output:
0
1
5
NESTED LOOP
🞆Python programming language allows to use one loop
inside another loop is called Nested loop.
🞆loop nesting is that you can put any type of loop inside
of any other type of loop. For example a for loop can be
inside a while loop or vice versa.
🞆Types:
⚫ Nested for loop
⚫ Nested while loop
NESTED FOR LOOP IN PYTHON
🞆Python allows us to nest any number of for loops inside
a for loop is called nested for loop.
🞆The inner loop is executed n number of times for every
iteration of the outer loop.
🞆Syntax
for iterating_var1 in sequence: #outer loop
for iterating_var2 in sequence: #inner loop
#block of statements
#Other statements
EXAMPLE- 1: NESTED FOR LOOP
# User input for number of rows
rows = int(input("Enter the rows:"))
# Outer loop will print number of rows
for i in range(1,rows+1):
# Inner loop will print number of Astrisk
for j in range(i):
print("*",end =“ '')
print(“\n”)
🞆 Output:

Enter the rows:5


*
**
***
****
*****
NESTED WHILE LOOP
🞆 Python programming language allows the use of a while loop inside
another while loop, it is known as nested while loop.
🞆 Outer loop test expression is evaluated only once.
🞆 When its return true, the flow of control jumps to the inner while
loop. the inner while loop executes to completion. However, when
the test expression is false, the flow of control comes out of
inner while loop and executes again from the outer while loop only
once. This flow of control persists until test expression of the outer
loop is false.
🞆 Thereafter, if test expression of the outer loop is false, the flow of
control skips the execution and goes to rest.

🞆 Syntax-
while expression: #outer loop
while expression: #inner loop
statement(s)
statement(s)
EXAMPLE: NESTED WHILE LOOP
🞆 #WAP to find the prime numbers from 2 to 100
i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j):
break
j=j+1
if (j > i/j) :
print (i, " is prime“)
i=i+1
print ("Good bye!“)
WHILE LOOP:

🞆The Python while loop allows a part of the code to be


executed until the given condition returns false. It is also
known as a pre-tested loop.
🞆It can be viewed as a repeating if statement. When we
don't know the number of iterations then the while loop
is most effective to use.

🞆The syntax is given below.


while expression:
statements
FLOW CHART OF WHILE LOOP
EXAMPLE-1: PROGRAM TO PRINT 1 TO 10 USING
WHILE LOOP
i=1
While(i<=10):
print(i)
i=i+1

Output:
1
2
3
4
5
6
7
8
9
10
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.
EXAMPLE: # EXAMPLE TO ILLUSTRATE THE USE
OF ELSE STATEMENT WITH THE WHILE LOOP

counter = 0
while counter < 3:
print("Inside loop")
counter = counter + 1
else:
print("Inside else")

🞆Output:
Inside loop
Inside loop
Inside loop
Inside else
LOOP MANIPULATION USING
CONTINUE, PASS, BREAK :
🞆In Python, break and continue statements can alter the
flow of a normal loop.
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 AND WHILE LOOP IS SHOWN BELOW
EXAMPLE : BREAK STATEMENT WITH FOR
LOOP
str = "python"
for i in str:
if i == 'o':
break
print(i)
🞆Output:
p
y
t
h
EXAMPLE : BREAK STATEMENT WITH WHILE LOOP
i=0
while 1:
print(i," ",end="")
i=i+1
if i == 10:
break
print("came out of while loop")
🞆Output:
0 1 2 3 4 5 6 7 8 9 came out of while loop
PYTHON CONTINUE STATEMENT

🞆The continue statement skips the remaining lines of code


inside the loop and start with the next iteration.
🞆It is mainly used for a particular condition inside the loop so
that we can skip some specific code for a particular condition.
🞆Syntax
#loop statements
continue
#the code to be skipped
FLOWCHART OF CONTINUE
THE WORKING OF CONTINUE STATEMENT
IN FOR AND WHILE LOOP IS SHOWN BELOW
EXAMPLE
i=0
while(i < 10):
i = i+1
if(i == 5):
continue
print(i)
🞆 Output:
1
2
3
4
6
7
8
9
10
PASS STATEMENT

🞆The pass statement is a null operation since nothing happens


when it is executed.
🞆It is used in the cases where a statement is syntactically needed
but we don't want to use any executable statement at its place.
🞆Syntax:
pass

🞆Example
for i in range(1,11):
if i%2==0:
pass
else:
print(“odd number:”,i)
#PROGRAM TO ADD TWO NUMBERS PROVIDED BY THE USER

# Store input numbers


num1 = input('Enter first number: ')
num2 = input('Enter second number: ')
# Add two numbers
sum = float(num1) + float(num2)
# Display the sum
print('The sum of {0} and {1} is {2}'.format(num1, num2,
sum))
🞆Output:-
Enter first number: 1.5
Enter second number: 6.3
The sum of 1.5 and 6.3 is 7.8
WAP FOR FOLLOWING PROBLEM STATEMENTS
1.Wap to check whether entered string is palindrome or not.
2. Wap to check whether entered number is palindrome or not.
3. Wap to find factorial of number. take input from user.
4. Wap to print Fibonacci series up to n terms.
5.Print the following pattern:
1 1
12 23
123 456
1234 7 8 9 10
12345 11 12 13 14 15

You might also like