KEMBAR78
UNIT-2 Python Operators and Control Flow Statements | PDF | Control Flow | Boolean Data Type
0% found this document useful (0 votes)
6 views17 pages

UNIT-2 Python Operators and Control Flow Statements

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

UNIT-2 Python Operators and Control Flow Statements

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

Chapter: 2 Python Operators and Control Flow Statements

Types of Operators:
Python language supports the following types of operators.
 Arithmetic Operators +, -, *, /, %, **, //
 Comparison (Relational) Operators = =, ! =, < >, <, >, <=, >=
 Assignment Operators =, +=, -=, *=, /=, %=, **=, //=
 Logical Operators and, or, not
 Bitwise Operators &, |, ^, ~,<<, >>
 Membership Operators in, not in
 Identity Operators is, is not

Arithmetic Operators:
Some basic arithmetic operators are +, -, *, /, %, **, and //. You can apply these
operators on numbers as well as variables to perform corresponding operations.
Operator Description Example
+ Addition Adds values on either side of the operator. a + b = 30
Subtracts right hand operand from left hand
- Subtraction a – b = -10
operand.
* Multiplication Multiplies values on either side of the operator a * b = 200
Divides left hand operand by right hand
/ Division b/a=2
operand
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs exponential (power) calculation on a**b =10 to
** Exponent
operators the power 20
The division of operands where the result is
9//2 = 4 and
// Floor Division the quotient in which the digits after the
9.0//2.0 = 4.0
decimal point are removed.
Program:
a = 21
b = 10
print ("Addition is", a + b)
print( "Subtraction is ", a - b)
print ("Multiplication is ", a * b
print( "Division is ", a / b)
print ("Modulus is ", a % b )
a=2
b=3
print ("Power value is ", a ** b)
a = 10
b=4
print ("Floor Division is ", a // b)
Output:
Addition is 31
Subtraction is 11
Multiplication is 210
Division is 2
Modulus is 1
Power value is 8
Floor Division is 2
Comparison (Relational) Operators
These operators compare the values on either sides of them and decide the relation
among them. They are also called Relational operators.
Operator Description Example
If the values of two operands are equal, then the
== (a == b) is not true.
condition becomes true.
If values of two operands are not equal, then
!= (a != b) is true.
condition becomes true.
(a <> b) is true. This
If values of two operands are not equal, then
<> is similar to !=
condition becomes true.
operator.
If the value of left operand is greater than the value
> (a > b) is not true.
of right operand, then condition becomes true.
If the value of left operand is less than the value of
< (a < b) is true.
right operand, then condition becomes true.
If the value of left operand is greater than or equal
>= to the value of right operand, then condition (a >= b) is not true.
becomes true.
If the value of left operand is less than or equal to
<= the value of right operand, then condition becomes (a <= b) is true.
true.

Example:
a=20
b=30
if a < b:
print ("b is big")
elif a > b:
print( "a is big")
else:
print ("Both are equal")

Output:
b is big
Assignment Operators

Operator Description Example


Assigns values from right side operands to c = a + b assigns
=
left side operand value of a + b into c
+= It adds right operand to the left operand and c += a is equivalent
Add AND assign the result to left operand to c = c + a
-= It subtracts right operand from the left c -= a is equivalent
Subtract AND operand and assign the result to left operand to c = c - a
*= It multiplies right operand with the left c *= a is equivalent
Multiply AND operand and assign the result to left operand to c = c * a
/= It divides left operand with the right c /= a is equivalent
Divide AND operand and assign the result to left operand to c = c / a
c %= a is
%= It takes modulus using two operands and
equivalent to c = c
Modulus AND assign the result to left operand
%a
Performs exponential (power) calculation c **= a is
**=
on operators and assign value to the left equivalent to c = c
Exponent AND
operand ** a
//= It performs floor division on operators and c //= a is equivalent
Floor Division assign value to the left operand to c = c // a
Example:
a=82
b=27
a += b
(print a )
a=25
b=12
a -= b
print(a )
a=24
b=4
a *= b
print( a )
a=4
b=6
a **= b
print (a)
Output:
109
13
96
4096
Logical Operators

Operator Description Example


And If both the operands are true then condition (a and b) is
Logical AND becomes true. true.
Or If any of the two operands are non-zero then
(a or b) is true.
Logical OR condition becomes true.
not Not (a and b) is
Used to reverse the logical state of its operand.
Logical NOT false.

Example:
a=20
b=10
c=30
if a >= b and a >= c:
print ("a is big")
elif b >= a and b >= c:
print ("b is big")
else:
print ("c is big")
Output:
c is big
Bitwise Operators
a = 0011 1100
b = 0000 1101
Operator Description Example
Operator copies a bit to the
& (a & b) = 12
result if it exists in both
Binary AND (means 0000 1100)
operands.
| It copies a bit if it exists in either (a | b) = 61
Binary OR operand. (means 0011 1101)
^ It copies the bit if it is set in one (a ^ b) = 49
Binary XOR operand but not both. (means 0011 0001)
(~a ) = -61 (means 1100 0011
~
It is unary and has the effect of in 2's complement form due to
Binary Ones
'flipping' bits. a signed binary number.
Complement

The left operands value is


<< a << 2 = 240
moved left by the number of bits
Binary Left Shift (means 1111 0000)
specified by the right operand.
The left operands value is
>> moved right by the number of a >> 2 = 15
Binary Right Shift bits specified by the right (means 0000 1111)
operand.
Membership Operators
Python‟s membership operators test for membership in a sequence, such as strings,
lists, or tuples.
Operator Description Example

Evaluates to true if it finds a variable in x in y, here in results in a 1 if


in
the specified sequence and false otherwise. x is a member of sequence y.
Evaluates to true if it does not finds a x not in y, here not in results
not in variable in the specified sequence and in a 1 if x is not a member of
false otherwise. sequence y.
Example:
a=3
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print ("available")
else:
print (" not available")
Output:
available
Identity Operators
Identity operators compare the memory locations of two objects.
Operator Description Example
Evaluates to true if the variables on
x is y, here is results in 1 if
is either side of the operator point to the
id(x) equals id(y).
same object and false otherwise.
Evaluates to false if the variables on x is not y, here is not results
is not either side of the operator point to the in 1 if id(x) is not equal to
same object and true otherwise. id(y).
Example:
a = 20
b = 20
if ( a is b ):
print ("Line 1 - a and b have same identity")
else:
(print "Line 1 - a and b do not have same identity")
if ( id(a) == id(b) ):
print ("Line 2 - a and b have same identity")
else:
print ("Line 2 - a and b do not have same identity")
Output:
Line 1 - a and b have same identity
Line 2 - a and b have same identity
Python Operators Precedence
The following table lists all operators from highest precedence to lowest.
Operator Description
() Parenthesis
** Exponentiation (raise to the power)
~ x, +x, -x Complement, unary plus and minus
* / % // Multiply, divide, modulo and floor division
+- Addition and subtraction
>> << Right and left bitwise shift
& Bitwise 'AND'
^| Bitwise exclusive `OR' and regular `OR'
<= < > >= Comparison operators
<> == != Equality operators
= %= /= //= -= += *= **= Assignment operators
is is not Identity operators
in not in Membership operators
not or and Logical operators

Expression:
An expression is a combination of variables constants and operators written according
to the syntax of Python language. In Python every expression evaluates to a value i.e., every
expression results in some value of a certain type that can be assigned to a variable. Some
examples of Python expressions are shown in the table given below.

Algebraic Expression Python Expression


axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
3x2 +2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c

Evaluation of Expressions
Expressions are evaluated using an assignment statement of the form
Variable = expression
Variable is any valid C variable name. When the statement is encountered, the
expression is evaluated first and then replaces the previous value of the variable on the left
hand side. All variables used in the expression must be assigned values before evaluation is
attempted.
Example:
a=10
b=22
c=34
x=a*b+c
y=a-b*c
z=a+b+c*c-a
print ("x=",x )
print ("y=",y)
print ("z=",z)
Output:
x= 254
y= -738
z= 1178

Decision Making:
Decision making is anticipation of conditions occurring while execution of the
program and specifying actions taken according to the conditions.
Decision structures evaluate multiple expressions which produce True or False as
outcome. You need to determine which action to take and which statements to execute if
outcome is True or False otherwise.
Following is the general form of a typical decision making structure found in most of
the programming languages:

Python programming language assumes any non-zero and non-null values as True,
and if it is either zero or null, then it is assumed as False value.

Statement Description
if statements if statement consists of a boolean expression followed by one or more
statements.
if...else statements if statement can be followed by an optional else statement, which
executes when the boolean expression is FALSE.
nested if statements You can use one if or else if statement inside another if or else if
statement(s).
The if Statement
It is similar to that of other languages. The if statement contains a logical expression
using which data is compared and a decision is made based on the result of the comparison.

Syntax:
if condition:
statements
First, the condition is tested. If the condition is True, then the statements given after
colon (:) are executed. We can write one or more statements after colon (:).

Example:
a=10
b=15
if a < b:
print (“B is big” )
print( “B value is”,b)
Output:
B is big
B value is 15
The if ... else statement
An else statement can be combined with an if statement. An else statement contains
the block of code that executes if the conditional expression in the if statement resolves to 0
or a FALSE value.
The else statement is an optional statement and there could be at most only one else
statement following if.
Syntax:
if condition:
statement(s)
else:
statement(s)
Example:
a=48
b=34
if a < b:
print( "B is big")
print( "B value is", b)
else:
print ("A is big" )
print ("A value is", a)
print ("END")

Output:
A is big
A value is 48
END
Q) Write a program for checking whether the given number is even or not.
Program:
a=int(input("Enter a value: "))
if a%2==0:
print( "a is EVEN number" )
else:
print ("a is NOT EVEN Number")

Output-1: Output-2:
Enter a value: 56 Enter a value: 27
a is EVEN Number a is NOT EVEN Number
The elif Statement
The elif statement allows you to check multiple expressions for True and execute a
block of code as soon as one of the conditions evaluates to True.
Similar to the else, the elif statement is optional. However, unlike else, for which
there can be at most one statement, there can be an arbitrary number of elif statements
following an if.
Syntax: if condition1:
statement(s)
elif condition2:
statement(s)
else:
statement(s)

Example:
a=20
b=10
c=30
if a >= b and a >= c:
print ("a is big")
elif b >= a and b >= c:
print ("b is big")
else:
print ("c is big")

Output:
c is big

Decision Loops
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you need to
execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement:
Python programming language provides following types of loops to handle looping
requirements.
Loop Type Description
Repeats a statement or group of statements while a given condition is
while loop
TRUE. It tests the condition before executing the loop body.
Executes a sequence of statements multiple times and abbreviates the
for loop
code that manages the loop variable.
nested loops You can use one or more loop inside any another while, for loop.

The while Loop


A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax
The syntax of a while loop in Python programming language is:
while expression:
statement(s)

Here, statement(s) may be a single statement or a block of statements.


The condition may be any expression, and true is any non-zero value. The loop
iterates while the condition is true. When the condition becomes false, program control
passes to the line immediately following the loop.
In Python, all the statements indented by the same number of character spaces after a
programming construct are considered to be part of a single block of code. Python uses
indentation as its method of grouping statements.
Example-1: Example-2:
i=1 i=1
while i < 4: while i < 4:
print i print i
i+=1 i+=1
print “END” print “END”

Output-1: Output-2:
1 1
END 2
2 3
END END
3
END

Q) Write a program to display factorial of a given number.


Program:
n=int(input("Enter the number: "))
f=1
while n>0:
f=f*n
n=n-1
print("Factorial is : ",f)

Output:
Enter the number: 5
Factorial is 120

The for loop:


The for loop is useful to iterate over the elements of a sequence. It means, the for loop
can be used to execute a group of statements repeatedly depending upon the number of
elements in the sequence. The for loop can work with sequence like string, list, tuple, range
etc.
The syntax of the for loop is given below:
for var in sequence:
statement (s)

The first element of the sequence is assigned to the variable written after „for‟ and
then the statements are executed. Next, the second element of the sequence is assigned to the
variable and then the statements are executed second time. In this way, for each element of
the sequence, the statements are executed once. So, the for loop is executed as many times as
there are number of elements in the sequence.

Example-1: Example-2:
for i in range(1,5): for i in range(1,5):
print (i)
print (i)
print ("END")
print ("END")
Output-1: Output-2:
1
1 2
END 3
2 END
END
3
END

Example-3: Example-4:
name= "python" for x in range(10,0,-1):
for letter in name: print (x)
print(letter)
Output-3: Output-4:
p
y
t
h
o
10 9 8 7 6 5 4 3 2 1
n

Q) Write a program to display the factorial of given number.


Program:

n=int(input("Enter the number: "))


f=1
for i in range(1,n+1):
f=f*i
print("Factorial is : ",f)

Output:
Enter the number: 5
Factorial is 120
Nested Loop:
It is possible to write one loop inside another loop. For example, we can write a for
loop inside a while loop or a for loop inside another for loop. Such loops are called “nested
loops”.
Nested for loop syntax :

for iterator_var in sequence:


for iterator_var in sequence:
statements(s)
statements(s)

Example-1:
for i in range(1,6): for j in range(1,6):
print(j,end=" ")
print ("\n")

Write a program to print n prime numbers and display the sum of prime numbers.
Program:
n=input("Enter the range: ")
sum=0
for num in range(1,n+1): for i in range(2,num):
if (num % i) == 0: break
else:
print (num) sum += num
print "\nSum of prime numbers is",sum

Output:
Enter the range: 21
1 2 3 5 7 11 13 17 19
Sum of prime numbers is 78

Nested for loop syntax :

while expression:
while expression:
statement(s)
statement(s)
Example :
The following program uses a nested while loop to find the prime numbers from 2 to 100 –

i=2
while(i < 100):
j=2
while(j <= (i/j)):
if not(i%j):
break
j=j+1
if (j > i/j) :
print (i, " is prime")
i=i+1
print("Good bye!")

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements.

1) Continue Statement

Syntax : continue
It returns the control to the beginning of the loop. The continue statement is used to skip the rest
of the code inside a loop for the current iteration only. Loop does not terminate but continues on
with the next iteration.

# Prints all letters except 'e' and 's'

for letter in 'geeksforgeeks':


if letter == 'e' or letter == 's':
continue
print 'Current Letter :', letter

2) Break Statement

Syntax: break
It brings control out of the loop. The break statement terminates the loop containing it. Control of
the program flows to the statement immediately after the body of the loop.If break statement is
inside a nested loop (loop inside another loop), break will terminate the innermost loop.

for letter in 'geeksforgeeks':

# break the loop as soon it sees 'e'


# or 's'
if letter == 'e' or letter == 's':
break
print ('Current Letter :', letter )

3) Pass statement
Syntax : pass

In Python programming, pass is a null statement. The difference between


comment and pass statement in Python is that, while the interpreter ignores a comment
entirely, pass is not ignored.

We use pass statement to write empty loops. Pass is also used for empty control statement,
function and classes. We generally use it as a placeholder.

Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
the future. They cannot have an empty body. The interpreter would complain. So, we use
the pass statement to construct a body that does nothing.

Example 1:
for letter in 'geeksforgeeks':
pass
print 'Last Letter :', letter

Example 2:
# pass is just a placeholder for
# functionality to be added later.

sequence = {'p', 'a', 's', 's'}


for val in sequence:
pass

You might also like