0% found this document useful (0 votes)
29 views37 pages

PWP UNIT 2 Notes

The document provides an overview of 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 constructs including conditional statements (if, if-else, nested if) and looping mechanisms (while loop, for loop, nested loops), along with examples for each. Additionally, it covers operator precedence and loop manipulation techniques using continue, break, and pass statements.

Uploaded by

raj373249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views37 pages

PWP UNIT 2 Notes

The document provides an overview of 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 constructs including conditional statements (if, if-else, nested if) and looping mechanisms (while loop, for loop, nested loops), along with examples for each. Additionally, it covers operator precedence and loop manipulation techniques using continue, break, and pass statements.

Uploaded by

raj373249
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit:-Python operator and

control flow statements


2.1 Basic Operator:
Arithmetic, Comparision/Relational,
Assignment,
Logical, Bitwise, Membership, Identity
Operator,
Python Operator Precedence
Arithmetic Operator
Comparision /Relational operator
• In Python, comparison operators are used to compare the values of two
operands
Assignment Operator: Assignment Operators are used to assign values to
variables. This operator is used to assign the value of the right side of the
expression to the left side operand.
Operator Description
= It assigns the the value of the right expression to the left operand.
+= It increases the value of the left operand by the value of the right operand and assign the modified value
back to left operand. For example, if a = 10, b = 20 => a+
= b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assign the modified value
back to left operand. For example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.

*= It multiplies the value of the left operand by the value of the right operand and assign the modified value
back to left operand. For example, if a = 10, b = 20 => a*
= b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assign the reminder back to
left operand. For example, if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign 4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign 4//3
= 1 to a.
Logical operator
Operator Description

and If both the expression are true, then the condition will be true. If a and b are the two expressions, a →
true, b → true => a and b → true.

or If one of the expressions is true, then the condition will be true. If a and b are the two expressions, a →
true, b → false => a or b → true.

not If an expression a is true then not (a) will be false and vice versa.
Bitwise Operator
Operator Description

& (binary If both the bits at the same place in two operands are 1, then 1 is copied to the
and) result. Otherwise, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero otherwise the resulting bit will
be 1.

^ (binary xor) The resulting bit will be 1 if both the bits are different otherwise the resulting bit
will be 0.

~ (negation) It calculates the negation of each bit of the operand, i.e., if the bit is 0, the
resulting bit will be 1 and vice versa.
<< (left shift) The left operand value is moved left by the number of bits present in the right
operand.

>> (right The left operand is moved right by the number of bits present in the right
shift) operand.
Membership operator
• . Python IN Operator
• The in operator is used to check if a character/substring/element exists in a sequence
or not. Evaluate to True if it finds the specified element in a sequence otherwise False.
list1 = [1, 2, 3, 4, 5]
• str1 = "Hello World"
• dict1 = {1: "Geeks", 2:"for", 3:"geeks"}

• # checking an integer in a list


• print(2 in list1)-----------> true
• # checking a character in a string
• print('O' in str1)-------------> false
• # checking for a key in a dictionary
• print(3 in dict1)--------------> true
Python NOT IN Operator
• The ‘not in’ Python operator evaluates to true if it does not find the variable in
the specified sequence and false otherwise.
list1 = [1, 2, 3, 4, 5]
str1 = "Hello World"
dict1 = {1: "Geeks", 2:"for", 3:"geeks"}

# checking an integer in a list


print(2 not in list1) ---------> false

# checking a character in a string


print('O' not in str1) ---------> true

# checking for a key in a dictionary


print(3 not in dict1) -----------> false
Identity Operator
• The Python Identity Operators are used to compare the objects if both
the objects are actually of the same data type and share the same
memory location.
• There are different identity operators such as
1. is
2.Is not
is:-The 'is' operator evaluates to True if both the operand objects share the same memory location. The memory
location of the object can be obtained by the "id()" function. If the "id()" of both variables is same, the "is" operator
returns True.

a = [1, 2, 3, 4, 5]
b = [1, 2, 3, 4, 5]
c=a

# Comparing and printing return values


print(a is c)----------------True
print(a is b)--------------- False

# Printing IDs of a, b, and c


print("id(a) : ", id(a))----------------------id(a) : 140114091859456
print("id(b) : ", id(b))-----------------------id(b) : 140114091906944
print("id(c) : ", id(c))--------------------- id(c) : 140114091859456
is not:The 'is not' operator evaluates to True if both the operand objects do not
share the same memory location or both operands are not the same objects.

• a = [1, 2, 3, 4, 5]
• b = [1, 2, 3, 4, 5]
• c=a

• # Comparing and printing return values


• print(a is not c)------------------------false
• print(a is not b)------------------------true

• # Printing IDs of a, b, and c


• print("id(a) : ", id(a))-----------------------id(a) : 140559927442176
• print("id(b) : ", id(b))-------------------------id(b) : 140559925598080
Python Operator Precedence
• in Python, operators have different levels of precedence, which determine the
order in which they are evaluated. When multiple operators are present in an
expression, the ones with higher precedence are evaluated first. In the case of
operators with the same precedence, their associativity comes into play,
determining the order of evaluation.
precedence Operators Description Associativity
1 () Parentheses Left to right

2 ** Exponentiation Right to left

3 +x, -x, ~x Positive, negative, bitwise NOT Right to left

4 *, @, /, //, % Multiplication, matrix, division, Left to right


floor division, remainder

5 +, – Addition and subtraction Left to right

6 <<, >> Shifts Left to right

7 & Bitwise AND Left to right

8 ^ Bitwise XOR Left to right

9 | Bitwise OR Left to right

10 in, not in, is, is not, <, <=, >, >=, ! Comparisons, membership tests, Left to Right
=, == identity tests

11 not x Boolean NOT Right to left

12 and Boolean AND Left to right

13 or Boolean OR Left to right


2.2:Control flow
2.3: Conditional Statement:-if,………if-else,
……….nested-if
• Python If statements :- This construct of python program consist of one if
condition with one block of statements. When condition becomes true then
executes the block given below it.
• Syntax:
• if ( condition):
• …………………..
• …………………..
• …………………..
Example:
• Age=int(input(“Enter Age: “))
• If ( age>=18):
• Print(“You are eligible for vote”)
• If(age<0):
• Print(“You entered Negative Number”)
Python if - else statements
• Python if - else statements This construct of python program consist of one if
condition with two blocks. When condition becomes true then executes the
block given below it. If condition evaluates result as false, it will executes the
block given below else.
• Syntax:
• if ( condition):
• …………………..
• else:
• …………………..
• Example-2:
Example-2:
• Age=int(input(“Enter Age: “)) N=int(input(“Enter Number: “))
• if ( age>=18): if(n%2==0):
• print(“You are eligible for vote”) print(N,“ is Even Number”)
• else: else:
print(N,“ is Odd Number”)
• print(“You are not eligible for vote”)
Python Ladder if else statements (if-elif-else)
• Python Ladder if else statements (if-elif-else) This construct of python program consist
of more than one if condition. When first condition evaluates result as true then
executes the block given below it. If condition evaluates result as false, it transfer the
control at else part to test another condition. So, it is multi-decision making construct
• Syntax:
if ( condition-1):
…………………..
elif (condition-2):
…………………..
elif (condition-3):
…………………..
else:
…………………..
Python Nested if statements
• Python Nested if statements It is the construct where one if condition take part inside of
other if condition. This construct consist of more than one if condition. Block executes
when condition becomes false and next condition evaluates when first condition
became true. So, it is also multi-decision making construct.
• Syntax: FlowChart
• if ( condition-1):
if (condition-2):
• ……………
• ……………
else:
• else:
• ……………
• ……………
num = 10

if num > 0:
if num % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive but odd.")
else:
print("The number is not positive.")
Looping in python:(while loop, for
loop, nested loop)
Python while loop

The while loop is conditional construct that executes a block of statements again
and again till given condition remains true. Whenever condition meets result false
then loop will terminate
Syntax:
while (condition):
…………………..
Updation in control variable
..…………………
Example: Sum of 1 to 10 numbers.
num=1
sum=0
while(num<=10):
sum + = num
num + = 1
print(“The Sum of 1- 10 numbers: “,sum)
Python range( )
• Python 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 number.
• . The common format of range() is as given below:
• range ( start value, stop value, step value )
• Where all 3 parameters are of integer type
• Start value is Lower Limit
• Stop value is Upper Limit
• Step value is Increment / Decrement
Note: The Lower Limit is included but Upper Limit is not included in result.
Example
range(5) => sequence of 0,1,2,3,4
range(2,5) => sequence of 2,3,4
range(1,10,2) => sequence of 1,3,5,7,9
range(5,0,-1) => sequence of 5,4,3,2,1
range(0,-5) => sequence of [ ] blank list (default Step is +1)
range(0,-5,-1) => sequence of 0, -1, -2, -3, -4
range(-5,0,1) => sequence of -5, -4, -3, -2, -1
range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0
Python for loop
• A for loop is used for iterating over a sequence (that is either a list, a tuple,string
etc.) With for loop we can execute a set of statements, and for loop can also
execute once for each element in a list, tuple, set etc.
• Example: print 1-10 numbers Example: print 10-1 numbers
for num in range(1,11,1): for num in range(10,0,-1):
print(num, end=” “) print(num, end=” “)
Output: 1 2 3 4 5 6 7 8 9 10 Output: 10 9 8 7 6 5 4 3 2 1
• Print each element in a fruit list:
fruits = ["mango", "apple", "grapes", "cherry"]
for x in fruits:
print(x)
• output:
mango
Apple
grapes
Cherry

for x in "TIGER":
print(x)
output:
T
I
E
Nested Loops:A nested loop in Python refers to a loop
within another loop
city = ["Jaipur", "Delhi", "Mumbai"]
fruits = ["apple", "mango", "cherry"]
for x in city:
for y in fruits:
print(x, “:”,y)
• output:
• Jaipur : apple
• Jaipur : mango
• Jaipur : cherry
• Delhi : apple
• Delhi : mango
• Delhi : cherry
• Mumbai : apple
• Mumbai : mango

Loop manipulation using continue pass
break else
• Python continue Statement
• The continue statement in python is used to bring the program control to the beginning
of the loop.
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.
• The syntax of Python continue statement is given below.

• #loop statements
• continue;
• #the code to be skipped
Example 2
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

• output:
• apple
• cherry
Python break statement
• The break statement breaks the loops one by one, i.e., in the case of nested
loops, it breaks the inner loop first and then proceeds to outer loops.
• break is used to abort the current execution of the program and the control goes
to the next line after the loop.
• The break is commonly used in the cases where we need to break the loop for a
given condition.
• The syntax of the break is given below.
#loop statements
break;
Example:
• fruits = ["apple", "banana", "cherry"]
• for x in fruits:
if x == "banana":
break
print(x)

• output: apple
pass Statement (Empty Statement)
• The pass statement do nothing, but it used to complete the syntax of
programming concept. Pass is useful in the situation where user does not
requires any action but syntax requires a statement. The Python compiler
encounters pass statement then it do nothing but transfer the control in flow of
execution
num = [1, 3, 6, 33, 76, 29, 17, 60, 100, 47, 53, 88]
Odd numbers are:
print('Odd numbers are: ') 1
for i in num: 3
# check if the number is even 33
if i % 2 == 0: 29
# if even, then pass 17
pass 47
# print the odd numbers 53
else:
print (i)
else statement

• The else keyword in for loop specifies a block of code to be executed when the
loop is finished:
for x in range(4):
print(x, end=” “)
else:
print("\nFinally finished!")

• output: 0 1 2 3
• Finally finished!

You might also like