Unit 2
Unit 2
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
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic Operators
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.
> 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
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.
Logical operators
Logical operators are the and, or, not operators.
| Bitwise OR x|y
~ Bitwise NOT ~x
Unit2
^ Bitwise XOR x^y
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
print(a2 is b2)
Operator Description
~+- Complement, unary plus and minus (method names for the last
two are +@ and -@)
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; # 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
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
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
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.
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
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
By using Not keyword we can change the meaning of the expressions, moreover
we can invert an expression.
example
mark = 100
else:
print("mark is 100")
output
mark is 100
You can write same code using "!=" operator.
Unit2
example
mark = 100
if (mark != 100):
else:
print("mark is 100")
output
mark is 100
mark = 72
else:
print("You failed!!")
output
color = ['Red','Blue','Green']
selColor = "Red"
if selColor in color:
else:
Looping in python:
Initialization
Condition
Updation
Unit2
Syntax
while (condition) :
statement(s)
initialization;
while(condition)
}
Unit2
For example,
x=0
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
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
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
statements(s)
Example
directions = ['North','East','West','South']
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.
print(color)
output
Red
Blue
Green
myDict = dict()
myDict["High"] = 100
myDict["Medium"] = 50
myDict["Low"] = 0
High 100
Medium 50
Low 0
str = ("Python")
for c in str:
print(c)
output
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
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)
Syntax
range(stop)
Example
for n in range(4):
print(n)
output
0
1
Unit2
2
3
Python range() function with two parameters
Syntax
range(start,stop)
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)
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:
Syntax
statements(s)
statements(s)
example
res = outer*nested
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.
lst = [1,2,3,4,8]
if num >5:
break
else: