Python Unit-2
Python Unit-2
Python Unit-2
OPERATORS:
Operators are the constructs 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:
Python language supports the following types of operators
1. Arithmetic Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
7. Identity Operators
Arithmetic operators:
It either returns True or False according to the condition. Assume, a=10 and b=5
Example
a=10
b=5
print("a>b=>",a>b)
print("a>b=>",a<b)
print("a==b=>",a==b)
print("a!=b=>",a!=b)
print("a>=b=>",a<=b)
print("a>=b=>",a>=b)
Output:
a>b=> True
a>b=> False
a==b=> False
a!=b=> True
a>=b=> False
a>=b=> True
Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Example
a = 21
b = 10
c=0
c=a+b
print("Line 1 - Value of c is ", c)
c += a
print("Line 2 - Value of c is ", c)
c *= a
print("Line 3 - Value of c is ", c)
c /= a
print("Line 4 - Value of c is ", c)
c= 2 c %= a
print("Line 5 - Value of c is ", c) c **= a
print("Line 6 - Value of c is ", c) c //= a
print("Line 7 - Value of c is ", c)
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52.0
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Logical Operators:
Example
a = True
b = False
print('a and b is',a and b)
print('a or b is',a or b)
print('not a is',not a)
Output
x and y is False
x or y is True
not x is False
Bitwise Operators:
A bitwise operation operates on one or more bit patterns at the level of individual Bits
Example:
Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)
Example
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
c = ~a; # -61 = 1100 0011
print "Line 4 - Value of c is ", c
c = a << 2; # 240 = 1111 0000
print "Line 5 - Value of c is ", c
c = a >> 2; # 15 = 0000 1111
print "Line 6 - Value of c is ", c
Output
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
Membership Operators:
Evaluates to find a value or a variable is in the specified sequence of string, list, tuple,
dictionary or not.
Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in operators are
used.
Example:
x=[5,3,6,4,1]
>>> 5 in x
True
>>> 5 not in x
False
Identity Operators
They are used to check if two values (or variables) are located on the same part of the
memory.
Example
x=5
y=5
x2 = 'Hello'
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
Output
False
True
OPERATOR PRECEDENCE:
Example 2:
A=2*3+4%5-3/2+6
A=6+4%5-3/2+6
A=6+4-3/2+6
A=6+4-1+6
A=10-1+6
A=9+6
A=15
Example 3:
find m=?
m=-43||8&&0||-2
m=-43||0||-2
m=1||-2
m=1
Example 4:
a=2,b=12,c=1
d=a<b>c
d=2<12>1
d=1>1
d=0
Example 5:
a=2,b=12,c=1
d=a<b>c-1
d=2<12>1-1
d=2<12>0
d=1>0
d=1
CONDITIONALS
1. Conditional if
2. Alternative if… else
3. Chained if…elif…else
4. Nested if….else
1. Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements inside if
will be executed.
Syntax:
if(condition 1):
Statement 1
Flowchart:
Example 1: Program to provide flat rs 500, if the purchase amount is greater than 2000.
purchase=eval(input(“enter your purchase amount”))
if(purchase>=2000):
purchase=purchase-500
print(“amount to pay”,purchase)
Output
enter your purchase
amount
2500
amount to pay
2000
2.alternative (if-else)
Flowchart:
Chained conditionals(if-elif-else)
Syntax:
Flowchart:
Example 1: student mark system
mark=eval(input("enter ur mark:"))
if(mark>=90):
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
Output
enter ur mark:78
grade:B
Nested conditionals
Flowchart:
Example 1:greatest of three numbers
a=eval(input(“enter the value of a”))
b=eval(input(“enter the value of b”))
c=eval(input(“enter the value of c”))
if(a>b):
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Output
enter the value of a 9
enter the value of a 1
enter the value of a 8
the greatest no is 9
Python supports a syntax for writing a restricted version of if-else statements in a single
line.
Example:
num = 2
if num >= 0:
sign = "positive"
else:
sign = "negative"
can be written in a single line as:
sign = "positive" if num >=0 else "negative"
This is suggestive of the general underlying syntax for inline if-else statements:
ITERATION/CONTROL STATEMENTS:
Python has two primitive loop commands:
while
for
While loop:
While loop statement in Python is used to repeatedly executes set of statement as long as
a given condition is true.
In while loop, test expression is checked first. The body of the loop isentered only if the
test_expression is 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.
The statements inside the while starts with indentation and the first unindented line marks
the end.
Syntax:
Flowchart
We can generate a sequence of numbers using range() function. range(10) will generate
numbers from 0 to 9 (10 numbers).
In range function have to define the start, stop and step size as range(start,stop,step size).
step size defaults to 1 if not provided.
Syntax
Flowchart:
For in sequence
The for loop in Python is used to iterate over a sequence (list, tuple, string).
Iterating over a sequence is called traversal. Loop continues until we reach the last
element in the sequence.
The body of for loop is separated from the rest of the code using indentation.
Syntax
Output
enter a number:6
the number is perfect number
Example 6:Program to print first n prime numbers
number=int(input("enter no of prime
numbers to be displayed:"))
count=1
n=2
while(count<=number):
for i in range(2,n):
if(n%i==0):
break
else:
print(n)
count=count+1
n=n+1
Output
enter no of prime numbers to be
displayed:5
2
3
5
7
11
Example 7:Program to print prime numbers in range
lower=eval(input("enter a lower range"))
upper=eval(input("enter a upper range"))
for n in range(lower,upper + 1):
if n > 1:
for i in range(2,n):
if (n % i) == 0:
break
else:
print(n)
Output:
enter a lower range50
enter a upper range100
53
59
61
67
71
73
79
83
89
97
CONTROL STATEMENTS:
break
continue
pass
BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come out of the loop
completely.
Syntax:
break
Flowchart
Example
for i in "welcome":
if(i=="c"):
break
print(i)
Output
w
e
l
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax:
continue
Flowchart
Example:
for i in "welcome":
if(i=="c"):
continue
print(i)
Output
w
e
l
o
m
e
PASS
It is used when a statement is required syntactically but you don’t want any code to
execute.
It is a null statement, nothing happens when it is executed.
Syntax:
pass
break
Example
for i in “welcome”:
if (i == “c”):
pass
print(i)
Output
w
e
l
c
o
m
e
Difference between break and continue
else statement in loops:
If else statement is used within while loop , the else part will be executed when the
condition become false.
The statements inside for loop and statements inside else will also execute.
Example
i=1
while(i<=5):
print(i)
i=i+1
else:
print("the number greater than 5")
Output
1
2
3
4
5
the number greater than 5
Looping Techniques
1. In python, looping techniques are used in different sequential holders.
2. The main purpose of using different looping techniques is to iterate over a list, set,
dictionary, or another compatible data type in a convenient and efficient manner.
4. Looping techniques are helpful for the user in situations where we need to access the
elements one at a time and there is no need to manipulate the structure and sequences of
the data.
1. Based on forms
We have some forms of loop that we can implement based on the nature of the loop and also
depends on the location of condition within the loop body.
a) Infinite loop
Infinite loop refers to the use of while loop with condition always TRUE
If there are lines below the while loop, they will be executed after the program has dealt
with the full execution or condition check of the while loop.
Example
It works like a normal while loop (considering the loop has no break statement) but with
the condition to be checked placed at its top.
# An example for while loop
count = 0
while(count <= 6):
count = count + 1
print("Hello", count)
Output
Hello1
Hello2
Hello3
Hello4
Hello5
Hello6
Just like do while loop in other programming languages like C or Java, it ensures the
statement inside the loop runs at least one time. It has the condition to check at the
bottom of the loop.
Example
while(1):
age = input("Tell me your age ")
print("Your age is :", age)
restart = input("Should I ask you again?(Y/N) ")
if restart == "N":
break
Output
Tell me your age 10
Your age is :10
Should I ask you again?(Y/N) Y
Tell me your age 20
Your age is :20
Should I ask you again?(Y/N) N
The loop with the condition to be checked is in the middle which means that
the break will be between the statements of the loop. This loop can be implemented as an
infinite loop.
Example:
while(1):
price = input("Enter integer value ")
try:
int(price)
print("Valid input")
except ValueError:
print("Invalid input!!!")
break
Output
Enter integer value 213
Valid input
Enter integer value 2324
Valid input
Enter integer value test
Invalid input!!!