2 Unit
2 Unit
The operator can be defined as a symbol which is responsible for a particular operation between two operands.
Operators are the pillars of a program on which the logic is built in a particular programming language. Python
provides a variety of operators described as follows.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands. It includes +(addition), -
(subtraction), *(multiplication), /(divide), %(reminder), //(floor division), and exponent (**).
- (Subtraction) Operand1 - It is used to subtract the second operand from the first operand. If
operand2 the first operand is less than the second operand, the value result
negative.
For example, if a = 20, b = 10 => a - b = 10
/ (divide) Operand1 / It returns the quotient after dividing the first operand by the second
operand2 operand. It always yields a floating – point result.
For example, if a = 20, b = 10 => a/b = 2.0
% (reminder) Operand1 % It returns the reminder after dividing the first operand by the second
operand2 operand. It is the result of remainder obtained by performing ’ //’
operation
For example, if a = 20, b = 10 => a%b = 0
// (Floor Operand1 // It gives the floor value of the quotient produced by dividing the two
division) operand2 operands. i.e Integer division rounded toward minus infinity.
The Result is float if any one of the or two operands is/are floating-
point type with single digit precision(i.e digit ‘0’).
The Result is integer if both the operands are integer type
(irrespective of whether they are exactly divisible or not).
== Operand1 == If the value of two operands is equal, then the condition becomes
(Equals operator) operand2 true.
!= Operand1 != If the value of two operands is not equal then the condition
(Not Equals operand2 becomes true.
Operator)
<= (Less than or Operand1 <= If the first operand is less than or equal to the second operand, then
equal operator) operand2 the condition becomes true.
>= Operand1 >= If the first operand is greater than or equal to the second operand,
(Greater than or operand2 then the condition becomes true.
equal operator)
> Operand1 > If the first operand is greater than the second operand, then the
(Greater than operand2 condition becomes true.
operator)
> Operand1 < If the first operand is less than the second operand, then the
(Less than operator) operand2 condition becomes true.
= operand = expression It assigns the the value of the right expression to the left operand.
(Assignment
Operator)
+= Operand1 += It increases the value of the left operand by the value of the right
(Addition (operand2 / operand and assign the modified value back to left operand. For
assignment expression) example, if a = 10, b = 20 => a+ = b will be equal to a = a+ b
operator) and therefore, a = 30.
-= Operand1 -= It decreases the value of the left operand by the value of the right
(Subtraction (operand2 / operand and assign the modified value back to left operand. For
assignment expression) example, if a = 20, b = 10 => a- = b will be equal to a = a- b and
operator) therefore, a = 10.
*= Operand1 *= It multiplies the value of the left operand by the value of the right
(Multiplication (operand2 / operand and assign the modified value back to left operand. For
assignment expression) example, if a = 10, b = 20 => a* = b will be equal to a = a* b
operator) and therefore, a = 200.
%= Operand1 %= It divides the value of the left operand by the value of the right
(Modulo (operand2 / operand and assign the reminder back to left operand. For
assignment expression) example, if a = 20, b = 10 => a % = b will be equal to a = a % b
operator) and therefore, a = 0.
**= Operand1 **= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b
(Exponent (operand2 / will assign 4**2 = 16 to a.
assignment expression)
operator)
>>> ++10
10
>>> --10
10
>>> ---10
-10
>>> 10++
Syntax Error: invalid syntax
Bitwise operator
The bitwise operators perform bit by bit operation on the values of the two operands. The arguments to bitwise
operators can be integer type or Boolean type otherwise it gives syntax error. The result of bitwise operation is
always an integer type.
For example,
1. if a = 7;
2. b = 6;
3. then, binary (a) = 0111
4. binary (b) = 0011
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000
Operator Syntax Description
& (binary Op1 & op2 If both the bits at the same place in two operands are 1, then 1 is
and) copied to the result. Otherwise, 0 is copied.
| (binary Op1 | op2 The resulting bit will be 0 if both the bits are zero otherwise the
or) resulting bit will be 1.
^ (binary Op1 ^ op2 The resulting bit will be 1 if both the bits are different otherwise the
xor) resulting bit will be 0.
~ ~op1 It calculates the negation of each bit of the operand, i.e., if the bit is 0,
(negation) the resulting bit will be 1 and vice versa.
<< (left Op1 << op2 The left operand value is moved left by the number of bits present in
shift) the right operand.
>> (right Op1 >> op2 The left operand is moved right by the number of bits present in the
shift) right operand.
Logical Operators
The logical operators are used primarily in the expression evaluation to make a decision. Logical operators are
useful to construct compound conditions. A compound condition is a combination of more than one simple
condition. Simple conditions are evaluated to True or False first and then decision is taken to know whether the
entire compound statement is True or False. These logical operators accept arguments of all types. It takes two
arguments. Python supports the following logical operators.
and Exp1 and exp2 For both Boolean type of arguments, If both the expressions are true, then
the condition will be true else the result is false.
For Example, If a and b are the two expressions, a → true, b → true => a and
b → true.
For both non-boolean type of arguments, if exp1 evaluates to false, it returns
exp1, otherwise it returns exp2.
or Exp1 or Exp2 For both Boolean type of arguments, If either of the expressions are true,
then the condition will be true else the result is false.
For Example, If a and b are the two expressions, a → true, b → false => a or
b → true.
For both non-boolean type of arguments, if exp1 evaluates to false, it returns
exp2, otherwise it returns exp1.
not not Exp If an expression a is true then not (a) will be false and vice versa.
Membership Operators
Python membership operators are used to check the membership of value inside a Python data structure or in
sequences such as strings, tuples or dictionaries.. If the value is present in the data structure, then the resulting
value is true otherwise it returns false.
The following are Membership operators:
not in Op1 not in op2 This operator returns True if an element is not found
Here, op1 is an element to check for in the specified sequence otherwise it returns False. It
its absence in sequence represented is evaluated to be true if the first operand is not found
by op2. in the second operand (list, tuple, or dictionary).
if ( x not in list ):
print ("x is NOT present in
given list")
else:
print ("x is present in given
list")
if ( y in list ):
print ("y is present in given
list")
else:
print ("y is NOT present in
given list")
output:
x is NOT present in given
list
y is present in given list
Identity Operators
These operators compare the memory locations of two objects. The memory location of an object can be seen
using the id () inbuilt function. This function returns an integer number, called the identity number that internally
represents the memory location of an object.
is Op1 is op2 It is evaluated to be true if both the references (op1 & op2)
point to the same object.
i.e if the identity numbers of two objects are same, then it
will return True, otherwise it returns False.
is not Op1 is not op2 It is evaluated to be true if both the references (op1 & op2)
do not point to the same object.
i.e if the identity numbers of two objects are different, then it
will return True, otherwise it returns False.
Operator Description
() Parenthesis
** The exponent operator is given priority over all the others used in the expression.
<=, < ,>, >= Comparison operators (less then, less then equal to, greater then, greater then
equal to).
If-else statements
Decision making is the most important aspect of almost all the programming languages. As the name implies,
decision making allows us to run a particular block of code for a particular decision. Here, the decisions are made
on the validity of the particular conditions. Condition checking is the backbone of decision making.
Statement Description
If Statement The if statement is used to test a specific condition. If the condition is true, a block
of code (if-block) will be executed.
If - else Statement The if-else statement is similar to if statement except the fact that, it also provides
the block of the code for the false case of the condition to be checked. If the
condition provided in the if statement is false, then the else statement will be
executed.
The ElIf Statement If we want to execute some code where one of the several conditions is true,then
use the else if statement.
Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for
the block level code. Python represents block structure and nested block structure with indentation.
Indentation refers to spaces that are used in the beginning of a statement. The statements with same
indentation belong to same group/block called a suite.
The empty block -- Use the ‘pass’ no-op statement.
Generally, four spaces are given to indent the statements which are a typical amount of indentation in
python.
Indentation is the most used part of the python language since it declares the block of code. All the
statements of one block are intended at the same level indentation. We will see how the actual indentation
takes place in decision making and other stuff in python.
The if statement
The if statement is used to execute one or more statements depending on
whether a condition is true or not. The condition of if statement can be any
valid logical expression which can be either evaluated to true or false.
The syntax of the if-statement is given below.
1. if expression:
2. block of statement(s) to be executed if condition is True
Output:
enter the number?10
Number is even
Output:
Enter value for a? 10
Enter value for b? 20
Enter value for c? 30
c is largest
If the condition is true, then the if-block is executed. Otherwise, the else-block is executed.
if condition:
block of statements to be executed if condition is True
else:
block of statements to be executed if condition is False
Example 1 : Program to check whether a person is eligible to vote or not.
Output:
Output:
Example 3: The following example will output "Have a nice weekend!" if the current day is Friday, Otherwise, it will output "Have a
nice day!":.
d = "Friday"
if d == " Friday ":
print("Have a nice weekend!")
else:
print("Have a nice day")
Output:
The elif statement works like an if-else-if ladder statement in C. It must be succeeded by an if
statement.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1
Output:
Example 2
For this purpose, The programming languages provide various types of loops which are capable of
repeating some specific code several numbers of times. Consider the following diagram to understand
the working of a loop statement.
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the
program so that instead of writing the same code again and again, we can repeat the same code for a
finite number of times. For example, if we need to print the first 10 natural numbers then, instead of
using the print statement 10 times, we can print inside a loop which runs up to 10 iterations.
Advantages of loops
Loop Description
Statement
for loop The for loop is used in the case where we need to execute some part of the code until
the given condition is satisfied. The for loop is also called as a per-tested loop. It is
better to use for loop if the number of iteration is known in advance.
while The while loop is to be used in the scenario where we don't know the number of
loop iterations in advance. The block of statements is executed in the while loop until the
condition specified in the while loop is satisfied. It is also called a pre-tested loop.
do-while The do-while loop continues until a given condition satisfies. It is also called post
loop tested loop. It is used when it is necessary to execute the loop at least once (mostly
menu driven programs).
Output:
i=0 j=0
i=0 j=1
i=0 j=2
i=0 j=3
------------------------
i=1 j=0
i=1 j=1
i=1 j=2
i=1 j=3
------------------------
i=2 j=0
i=2 j=1
i=2 j=2
i=2 j=3
------------------------
Example 2: A program to display the following pattern for given number of rows?
*
**
***
****
n = int(input("Enter the number of rows you want to print?"))
i,j=0,0
for i in range(0,n):
print()
for j in range(0,i+1):
print("*",end="")
Output:
Enter the number of rows you want to print?5
*
**
***
****
*****
The syntax of the ‘else suite’ with for loop in python is given below.
for(var in sequence):
#Statement(s)
else:
#Statement(s)
In the above example, for loop is executed completely since there is no break statement in the loop.
The control comes out of the loop and hence the else block is executed.
Output:
0
1
2
3
4
for loop completely exhausted, since there is no break.
Example 2
for i in range(0,5):
print(i)
break
else:
print("for loop is exhausted")
print("The loop is broken due to break statement...came out of loop")
In the above example, the loop is broken due to break statement therefore the else statement will not
be executed. The statement present immediate next to else block will be executed.
Output:
0
The loop is broken due to break statement...came out of loop
Example 3
Output:
while expression:
Block of statement(s) to execute repeatedly until the expression evaluates to False.
Here, the statements can be a single statement or the group of statements. The expression should be
any valid python expression resulting into true or false. The true is any non-zero value.
Example 1: A Program to display numbers from 1 to 10
i=1;
while i<=10:
print(i)
i=i+1
Print(“End of … ….”)
Output:
1
2
3
4
5
6
7
8
9
10
End of … ….
Output:
Enter the number: 10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Output:
100
102
104
106
108
110
112
114
116
118
120
122
124
126
128
130
132
134
136
138
140
142
144
146
148
150
152
154
156
158
160
162
164
166
168
170
172
174
176
178
180
182
184
186
188
190
192
194
196
198
200
Any non-zero value in the while loop indicates an always-true condition whereas 0 indicates
the always-false condition. This type of approach is useful if we want our program to run
continuously in the loop without any disturbance.
Infinite loops are drawbacks in a program because when the user is caught in an infinite loop,
he/she cannot understand how to come out of the loop. So, it is always recommended to avoid
infinite loops in any program.
Example 1
while (1):
print("Hi! we are inside the infinite while loop")
Output:
Hi! we are inside the infinite while loop
(infinite times)
Example 2
var = 1
while var != 2:
i = int(input("Enter the number?"))
print ("Entered value is %d"%(i))
Output:
Enter the number?102
Entered value is 102
Enter the number?102
Entered value is 102
Enter the number?103
Entered value is 103
Enter the number?103
(infinite loop)
The syntax of the ‘else suite’ with while loop in python is given below.
While(condition):
#Statement(s)
else:
#Statement(s)
i=1;
while i<=5:
print(i)
i=i+1
else:
print("The while loop exhausted");
Output:
1
2
3
4
5
The while loop exhausted
Example 2
i=1;
while i<=5:
print(i)
i=i+1;
if(i==3):
break
else:
print("The while loop exhausted");
Output:
1
2
break statement
break statement can be used within for as well as while loops. Python Interpreter terminates the
current loop when it executes break statement and resumes execution with the statement following
the loop body, just like the traditional break statement in C.
The most common use for break is when some external condition is triggered requiring a hasty exit
from a loop.
In case of nested loops, the successful execution of ‘break statement’ causes Python interpreter to
terminate the execution of the loop having ‘break statement’ and continues with the execution of
statements of outer loop/enclosing loop.
#loop statements
break
Example 1
str = "python"
for i in str:
if i == 'o':
break
print(i)
Output:
p
y
t
h
Example 2:
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
Example 3:
# A program to print multiplication table interactively illustrating the usage of 'break statement'
while 1:
i=1
choice = input("Do you want to continue printing the table, press 'yes' or 'no'?: ")
if choice == 'yes':
n = int(input("enter the table to print: "))
while i<=10:
print("%d X %d = %d\n"%(n,i,n*i))
i = i+1
else:
break
Output:
Do you want to continue printing the table, press 'yes' or 'no'?: yes
enter the table to print: 2
2 X 1 = 2
2 X 2 = 4
2 X 3 = 6
2 X 4 = 8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
Do you want to continue printing the table, press 'yes' or 'no'?: yes
enter the table to print: 5
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50
#loop statements
continue
#the code to be skipped
Example 1
i = 0;
while i!=10:
print("%d" % i)
continue
i=i+1
Output:
infinite loop
Example 2
i=1; #initializing a local variable
#starting a loop from 1 to 10
for i in range(1,11):
if i==5:
continue
print("%d"%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.
For example, it can be used while overriding a parent class method in the subclass but don't want to give its
specific implementation in the subclass.
Pass is also used where the code will be written somewhere but not yet written in the program file.
# statements
pass
# statements
Example
list = [1,2,3,4,5]
flag = 0
for i in list:
print("Current element:",i,end=" ")
if i==3:
pass
print("\nWe are inside pass block\n")
flag = 1
if flag==1:
print("\nCame out of pass\n")
flag=0
Output:
Current element: 1 Current element: 2 Current element: 3
We are inside pass block
Example:
# A Program to illustrate the usage of 'pass statement'
# A program to retrieve only -ve numbers from the list
num = [1,2,3,-4,-5,-6,-7,8,9,10]
for i in num:
if (i>0):
pass
else:
print(i)
Output
-4
-5
-6
-7
Note:
Iterable is an object, which one can iterate over. It generates an Iterator when passed
to iter() method. Iterator is an object, which is used to iterate over an iterable object using
__next__() method. Iterators have __next__() method, which returns the next item of the
object.
Note that every iterator is also an iterable, but not every iterable is an iterator. For
example, a list is iterable but a list is not an iterator. An iterator can be created from
an iterable by using the function iter(). To make this possible, the class of an object needs
either a method __iter__, which returns an iterator, or a __getitem__ method with
sequential indexes starting with 0.