Unit2
Basic operators:
Operators are the constructs which can manipulate the value of the operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is
called operator.
Operators are special symbols that carry out arithmetic or logical computation.
The value that the operator operates on is called the operand.
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 and division.
Assume variable x holds 10 and variable y holds 20, then −
Operator Description Example
+ Addition Adds values on either side of the x +y = 30
operator.
- Subtraction Subtracts right hand operand from left x – y = -10
hand operand.
Unit2
* Multiplication Multiplies values on either side of the x *y = 200
operator
/ Division Divides left hand operand by right hand y /x = 2
operand
% Modulus Divides left hand operand by right hand b % a = 0
operand and returns remainder
** Exponent Performs exponential (power) x**y =10 to the power 20
calculation on operators
// Floor Division - The division of 9//2 = 4 and 9.0//2.0 = 4.0, -
operands where the result is the 11//3 = -4, -11.0//3 = -4.0
quotient in which the digits after the
decimal point are removed. But if one
of the operands is negative, the result is
floored, i.e., rounded away from zero
(towards negative infinity) −
Example 1: Arithmetic operators in Python
1. x = 15
2. y = 4
3.
4. # Output: x + y = 19
5. print('x + y =',x+y)
6. print (‘x**y’,x*y)
7. # Output: x - y = 11
8. print('x - y =',x-y)
9.
10.# Output: x * y = 60
Unit2
[Link]('x * y =',x*y)
12.
13.# Output: x / y = 3.75
[Link]('x / y =',x/y)
15.
16.# Output: x // y = 3
[Link]('x // y =',x//y)
18.
19.# Output: x ** y = 50625
[Link]('x ** y =',x**y)
When you run the program, the output will be:
x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625
Comparison operators
Comparison operators are used to compare values. It either
returns True or False according to the condition. These operators compare the
values on either sides of them and decide the relation among them. They are also
called Relational operators.
Operator Meaning Example
> Greater that - True if left operand is greater than the right x>y
< Less that - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
Unit2
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater than
>= or equal to the right x >= y
Less than or equal to - True if left operand is less than or
<= equal to the right x <= y
Comparison on operators in Python
Example 2: Comparison operators in Python
1. x = 10
2. y = 12
3.
4. # Output: x > y is False
5. print('x > y is',x>y)
6.
7. # Output: x < y is True
8. print('x < y is',x<y)
9.
10.# Output: x == y is False
[Link]('x == y is',x==y)
12.
13.# Output: x != y is True
[Link]('x != y is',x!=y)
15.
16.# Output: x >= y is False
[Link]('x >= y is',x>=y)
18.
19.# Output: x <= y is True
[Link]('x <= y is',x<=y)
Python Assignment Operators
Unit2
Assignment operators are used to assign values to the variables.
Assignment operators are used in Python to assign values to variables.
a = 10 is a simple assignment operator that assigns the value 10 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.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
= Assigns values from right side c = a + b assigns value of a
operands to left side operand + b into c
+= It adds right operand to the left
c += a is equivalent to c = c
operand and assign the result to
+a
left operand
-= It subtracts right operand from
c -= a is equivalent to c = c -
the left operand and assign the
a
result to left operand
*= It multiplies right operand with
c *= a is equivalent to c = c
the left operand and assign the
*a
result to left operand
/= It divides left operand with the c /= a is equivalent to c = c /
right operand and assign the ac /= a is equivalent to c = c
Unit2
result to left operand /a
%= It takes modulus using two
c %= a is equivalent to c = c
operands and assign the result to
%a
left operand
**= Performs exponential (power)
c **= a is equivalent to c =
calculation on operators and
c ** a
assign value to the left operand
//= It performs floor division on
c //= a is equivalent to c = c
operators and assign value to the
// a
left operand
Logical operators
Logical operators are the and, or, not operators.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
Logical operators in Python
Example 3: Logical Operators in Python
Unit2
1. x = True
2. y = False
3.
4. # Output: x and y is False
5. print('x and y is',x and y)
6.
7. # Output: x or y is True
8. print('x or y is',x or y)
9.
10.# Output: not x is False
[Link]('not x is',not x)
[Link] operators: Bitwise operators acts on bits and performs bit by bit
operation.
Bitwise operator works on bits and performs bit by bit operation. Assume if a =
60; and b = 13; Now in binary format they will be as follows −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
OPERATOR DESCRIPTION SYNTAX
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
Unit2
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
# Examples of Bitwise operators
a = 10
b=4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation
print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
Output:
0
14
-11
14
Unit2
2
40
Python Identity Operators
is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal does not
imply that they are identical.
Operator Description Example
is Evaluates to true if the variables on either side of the x is y,
operator point to the same object and false otherwise. here is results
in 1 if id(x)
equals id(y).
is not Evaluates to false if the variables on either side of the x is not y,
operator point to the same object and true otherwise. here is
not results in
1 if id(x) is
not equal to
id(y).
Examples of Identity operators
a1 = 3
b1 = 3
a2 = 'GeeksforGeeks'
b2 = 'GeeksforGeeks'
a3 = [1,2,3]
b3 = [1,2,3]
Unit2
print(a1 is not b1)
print(a2 is b2)
# Output is False, since lists are mutable.
print(a3 is b3)
Output:
False
True
False
The following table lists all operators from highest precedence to lowest.
Operator Description
** Exponentiation (raise to the power)
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'td>
^| Bitwise exclusive `OR' and regular `OR'
Unit2
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += Assignment operators
*= **=
is is not Identity operators
in not in Membership operators
not or and Logical operators
Operator precedence affects how an expression is evaluated.
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.
Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom.
Example
#!/usr/bin/python
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
Unit2
print "Value of ((a + b) * c) / d is ", e
e = (a + b) * (c / d); # (30) * (15/5)
print "Value of (a + b) * (c / d) is ", e
e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e
When you execute the above program, it produces the following result −
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50
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.
According to the structure theorem, any computer program can be written using the
basic control structures . A control structure (or flow of control) is a block of
programming that analyses variables and chooses a direction in which to go based
on given parameters.
In simple sentence, a control structure is just a decision that the computer makes.
So, it is the basic decision-making process in programming and flow of control
determines how a computer program will respond when given certain conditions
and parameters.
There are two basic aspects of computer programming: data and instructions . To
work with data, you need to understand variables and data types; to work with
instructions, you need to understand control structures and statements. Flow of
control through any given program is implemented with three basic types of
control structures: Sequential, conditional and Repetition.
Unit2
Sequential
Sequential execution is when statements are executed one after another in order.
You don't need to do anything more for this to happen.
Selection
Selection used for decisions, branching - choosing between 2 or more alternative
paths.
if
if...else
switch
Repetition
Repetition used for looping, i.e. repeating a piece of code multiple times in a row.
while loop
do..while loop
for loop
These control structures can be combined in computer programming. A sequence
may contain several loops; a loop may contain a loop nested within it, or the two
branches of a conditional may each contain sequences with loops and more
Unit2
conditionals. From the following lessons you can understand the control structures
and statements in Python language.
Conditional Statements (if, if … else,nested if)
Python Conditional Statements
Decision making is one of the most important concepts of computer
programming . It require that the developer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements
to be executed if the condition is determined to be false. Python programming
language provides following types of decision making statements.
if statements
if....else statements
if..elif..else statements
nested if statements
not operator in if statement
and operator in if statement
in operator in if statement
Python if statement syntax and flow chart :
if expression:
Statements
Unit2
In Python, if statement evaluates the test expression inside parenthesis. If test
expression is evaluated to true (nonzero) , statements inside the body of if is
executed. If test expression is evaluated to false (0) , statements inside the body of
if is skipped.
Example
x=20
y=10
if x > y :
print(" X is bigger ")
output:
X is bigger
In this program we have two variables x and y. x is assigned as the value 20 and y
is 10. In next line, the if statement evaluate the expression (x>y) is true or false. In
this case the x > y is true because x=20 and y=10, then the control goes to the body
of if block and print the message "X is bigger". If the condition is false then the
control goes outside the if block.
Python [Link] statements
The else statement is to specify a block of code to be executed, if the condition in
the if statement is false. Thus, the else clause ensures that a sequence of statements
is executed.
Syntax and flow chart :
if expression:
statements
else:
statements
Unit2
Example
x=10
y=20
if x > y :
print(" X is bigger ")
else :
print(" Y is bigger ")
output
Y is bigger
In the above code, the if stat evaluate the expression is true or false. In this case the
x > y is false, then the control goes to the body of else block , so the program will
execute the code inside else block.
if..elif..else statements
The elif is short for else if and is useful to avoid excessive indentation.
if expression:
statements
elif expression:
statements
Unit2
x=500
if x > 500 :
print(" X is greater than 500 ")
elif x < 500 :
print(" X is less than 500 ")
elif x == 500 :
print(" X is 500 ")
else :
print(" X is not a number ")
output
X is 500
In the above case Python evaluates each expression one by one and if a true
condition is found the statement(s) block under that expression will be executed. If
no true condition is found the statement(s) block under else will be executed.
Nested if statements
In some situations you have to place an if statement inside another statement.
if condition:
if condition:
statements
else:
statements
else:
Example
Unit2
mark = 72
if mark > 50:
if mark > = 80:
print ("You got A Grade !!")
elif mark > =60 and mark < 80 :
print ("You got B Grade !!")
else:
print ("You got C Grade !!")
else:
print("You failed!!")
output
You got B Grade !!
not operator in if statement
By using Not keyword we can change the meaning of the expressions, moreover
we can invert an expression.
example
mark = 100
if not (mark == 100):
print("mark is not 100")
else:
print("mark is 100")
output
mark is 100
You can write same code using "!=" operator.
Unit2
example
mark = 100
if (mark != 100):
print("mark is not 100")
else:
print("mark is 100")
output
mark is 100
and operator in if statement
The equivalent of "& & " is "and" in Python.
mark = 72
if mark > 80:
print ("You got A Grade !!")
elif mark > =60 and mark < 80 :
print ("You got B Grade !!")
elif mark > =50 and mark < 60 :
print ("You got C Grade !!")
else:
print("You failed!!")
output
You got B Grade !!
Unit2
in operator in if statement
color = ['Red','Blue','Green']
selColor = "Red"
if selColor in color:
print("Red is in the list")
else:
print("Not in the list")
output
Red is in the list
Looping in python:
Loops are one of the most important features in computer programming
languages . As the name suggests is the process that get repeated again and
again . It offer a quick and easy way to do something repeated until a certain
condition is reached. Every loop has 3 parts:
Initialization
Condition
Updation
Unit2
Python while loop Statements
In Python, while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. That means, while loop tells the
computer to do something as long as the condition is met. It consists
of condition/expression and a block of code. The condition/expression is
evaluated, and if the condition/expression is true, the code within the block is
executed. This repeats until the condition/expression becomes false.
Unit2
Syntax
while (condition) :
statement(s)
initialization;
while(condition)
//Code block to execute something
}
Unit2
For example,
x=0
while(x < =5):
print(x)
x+=1
in above example initialize the value of a variable x as 0 and set the condition x
< =5 then the condition will be held true. But if I set the condition x>=5 the
condition will become false. After checking the condition in while clause, if it
holds true, the body of the loop is executed. While executing the body of loop it
can update the statement inside while loop . After updating, the condition is
checked again. This process is repeated as long as the condition is true and once
the condition becomes false the program breaks out of the loop.
output
0
1
2
3
4
5
One-Line while Loops
As with an if statement, a Python while loop can be specified on one line. If there
are multiple statements in the loop code block that makes up the loop body , they
can be separated by semicolons (;):
example
x,y = 0,5
while (x<y): x +=1; print(x);
Unit2
output
5
is same as:
x=0
y=5
while x < y:
x +=1
print(x)
For Loop
A for loop has two sections: a header specifying the iterating conditions, and a
body which is executed once per iteration . The header often declares an explicit
loop counter or loop variable, which allows the body to know which iteration is
being executed.
Unit2
Syntax
Syntax
for item in sequence:
statements(s)
Example
directions = ['North','East','West','South']
for pole in directions:
print(pole)
Unit2
North
East
West
South
Here directions is a sequence contains a list of directions. When the for loop
executed the first item (i.e. North) is assigned to the variable "pole". After this,
the print statement will execute and the process will continue until we rich the
end of the list.
Using for loop in Python Tuple
colors = ("Red", "Blue", "Green")
for color in colors:
print(color)
output
Red
Blue
Green
Using for loop in Python Dictionary
myDict = dict()
myDict["High"] = 100
myDict["Medium"] = 50
myDict["Low"] = 0
for var in myDict:
print("%s %d" %(var, myDict[var]))
Unit2
output
High 100
Medium 50
Low 0
Using for loop in Python String
str = ("Python")
for c in str:
print(c)
output
Decrementing for loops
If you want a decrementing for loops , you need to give the range a -1 step
Example
for i in range(5,0,-1):
print (i)
5
Unit2
4
Python for loop range() function
The range function in for loop is actually a very powerful mechanism when
it comes to creating sequences of integers. It can take one, two, or three
parameters. It returns or generates a list of integers from some lower bound (zero,
by default) up to (but not including) some upper bound , possibly in increments
(steps) of some other number (one, by default). Note for Python 3 users: There are
no separate range and xrange() functions in Python 3, there is just range, which
follows the design of Python 2's xrange.
range(stop)
range(start,stop)
range(start,stop,step)
It is important to note that all parameters must be integers and can
be positive or negative .
Python range() function with one parameters
Syntax
range(stop)
stop: Generate numbers up to, but not including this number.
Example
for n in range(4):
print(n)
output
0
1
Unit2
2
3
Python range() function with two parameters
Syntax
range(start,stop)
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
Example
for n in range(5,10):
print(n)
output
5
6
7
8
9
10
The range(start,stop) generates a sequence with numbers start, start + 1, ..., stop -
1. The last number is not included.
Python range() function with three parameters
Syntax
range(start,stop,step)
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step: Difference between each number in the sequence.
Example
for n in range(0,10,3):
print(n)
output
0
Unit2
3
6
9
Here the start value is 0 and end values is 10 and step is 3. This means that the loop
start from 0 and end at 10 and the increment value is 3.
Python Range() function can define an empty sequence, like range(-10) or
range(10, 4). In this case the for-block won't be executed:
Nested for loop in Python
Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s)
example
for outer in range(1,5):
for nested in range(1,5):
res = outer*nested
print (res, end=' ')
print()
output
1234
2468
3 6 9 12
4 8 12 16
Unit2
Here the Python program first encounters the outer loop, executing its first
iteration. This first iteration triggers the nested loop, which then runs to
completion. Then the program returns back to the outer loop, completing
the second iteration and again triggering the nested loop. Again, the nested loop
runs to completion, and the program returns back to the top of the outer loop until
the sequence is complete or a break or other statement disrupts the process.
The print() function inner loop has second parameter end=' ' which appends a
space instead of default new line. Hence, the numbers will appear in one row.
Using else statement in python for loop
Unlike other popular programming languages, Python also allows developers to
use the else condition with for loops.
lst = [1,2,3,4,8]
for num in lst:
if num >5:
print ("list contains numbers greater than 5")
break
else:
print("list contains numbers less than 5");
output
list contains numbers greater than 5