PWP - Unit 2 - Notes New

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

[Type the document title]

Unit 2. Python Operators and Control Flow Statements

Basic Opeators in Python:


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 Operator:

Python language supports the following types of operators.

● Arithmetic Operators
● Comparison (Relational) Operators
● Assignment Operators
● Logical Operators
● Bitwise Operators
● Membership Operators
● Identity Operators
Let us have a look on all operators one by one.

Python Arithmetic Operators:


Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder

Prof. P.S.BRAHMANE
[Type the document title]

** Exponent Performs exponential (power) calculation on operators a**b =10 to the power
20

// Floor Division - The division of operands where the result is the 9//2 = 4 and 9.0//2.0 =
quotient in which the digits after the decimal point are removed. 4.0, -11//3 = -4,
But if one of the operands is negative, the result is floored, i.e., -11.0//3 = -4.0
rounded away from zero (towards negative infinity) −

Python Comparison Operators:


These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description Example

== If the values of two operands are equal, then the condition becomes (a == b) is not
true. true.

!= If values of two operands are not equal, then condition becomes (a != b) is true.
true.

<> If values of two operands are not equal, then condition becomes (a <> b) is true.
true. This is similar
to != operator.

> If the value of left operand is greater than the value of right (a > b) is not
operand, then condition becomes true. true.

< If the value of left operand is less than the value of right operand, (a < b) is true.
then condition becomes true.

>= If the value of left operand is greater than or equal to the value of (a >= b) is not
right operand, then condition becomes true. true.

<= If the value of left operand is less than or equal to the value of right (a <= b) is true.
operand, then condition becomes true.

Prof. P.S.BRAHMANE
[Type the document title]

Python Assignment Operators:


Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description Example

= Assigns values from right side operands to left side operand c=a+b
assigns value
of a + b into
c

+= Add AND It adds right operand to the left operand and assign the result c += a is
to left operand equivalent to
c=c+a

-= Subtract AND It subtracts right operand from the left operand and assign c -= a is
the result to left operand equivalent to
c=c-a

*= Multiply AND It multiplies right operand with the left operand and assign c *= a is
the result to left operand equivalent to
c=c*a

/= Divide AND It divides left operand with the right operand and assign the c /= a is
result to left operand equivalent to
c=c/a

%= Modulus AND It takes modulus using two operands and assign the result to c %= a is
left operand equivalent to
c=c%a

**= Exponent Performs exponential (power) calculation on operators and c **= a is


AND assign value to the left operand equivalent to
c = c ** a

Prof. P.S.BRAHMANE
[Type the document title]

//= Floor Division It performs floor division on operators and assign value to c //= a is
the left operand equivalent to
c = c // a

Python Bitwise Operators:


Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in
the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists out
the bitwise operators supported by Python language with an example each in those, we use the above
two variables (a and b) as operands −
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
[ Show Example ]

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists (a & b) (means 0000
in both operands 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means


0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but (a ^ b) = 49 (means
not both. 0011 0001)

Prof. P.S.BRAHMANE
[Type the document title]

~ Binary Ones Complement (~a ) = -61 (means


1100 0011 in 2's
It is unary and has the effect of 'flipping' bits. complement form
due to a signed
binary number.

<< Binary Left Shift The left operands value is moved left by the a << 2 = 240 (means
number of bits specified by the right operand. 1111 0000)

>> Binary Right Shift The left operands value is moved right by the a >> 2 = 15 (means
number of bits specified by the right operand. 0000 1111)

Python Logical Operators:


There are following logical operators supported by Python language. Assume variable a holds 10 and
variable b holds 20 then
[ Show Example ]

Operator Description Example

and Logical If both the operands are true then condition becomes true. (a and b) is
AND true.

or Logical OR If any of the two operands are non-zero then condition (a or b) is


becomes true. true.

not Logical NOT Used to reverse the logical state of its operand. Not(a and b)
is false.

Python Membership Operators:

Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There
are two membership operators as explained below −
[ Show Example ]

Prof. P.S.BRAHMANE
[Type the document title]

Operator Description Example

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


sequence and false otherwise. in a 1 if x is a member
of sequence y.

not in Evaluates to true if it does not finds a variable in the specified x not in y, here not in
sequence and false otherwise. results in a 1 if x is not

a member of sequence
y.

Python Identity Operators:


Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −
[ Show Example ]

Operator Description Example

is Evaluates to true if the variables on either side of the x is y, here is results in 1 if


operator point to the same object and false otherwise. id(x) equals id(y).

is not Evaluates to false if the variables on either side of the x is not y, here is
operator point to the same object and true otherwise. not results in 1 if id(x) is
not equal to id(y).

Python Operators Precedence:


The following table lists all operators from highest precedence to lowest.
[ Show Example ]

Sr.No. Operator & Description

Prof. P.S.BRAHMANE
[Type the document title]

1
**
Exponentiation (raise to the power)

2
~+-
Complement, unary plus and minus (method names for the last two are +@ and
-@)

3
* / % //
Multiply, divide, modulo and floor division

4
+-

Addition and subtraction

5
>> <<
Right and left bitwise shift

6
&
Bitwise 'AND'

7
^|
Bitwise exclusive `OR' and regular `OR'

8
<= < > >=
Comparison operators

9
<> == !=
Equality operators

10
= %= /= //= -= += *= **=
Assignment operators

Prof. P.S.BRAHMANE
[Type the document title]

11
is is not
Identity operators

12
in not in
Membership operators

13
not or and
Logical operators

Prof. P.S.BRAHMANE
[Type the document title]

Python Conditions and If statements:


Python supports the usual logical conditions from mathematics:

● Equals: a == b
● Not Equals: a != b
● Less than: a < b
● Less than or equal to: a <= b
● Greater than: a > b
● Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

Example

If statement:

a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to test
whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print
to screen that "b is greater than a".

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other
programming languages often use curly-brackets for this purpose.

Example

If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".

Prof. P.S.BRAHMANE
[Type the document title]

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we
print to screen that "a and b are equal".

Else
The else keyword catches anything which isn't caught by the preceding conditions.

Example

a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so
we go to the else condition and print to screen that "a is greater than b".

● You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")

Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.

Prof. P.S.BRAHMANE
[Type the document title]

Example

One line if statement:

if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

Example

One line if else statement:

a=2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

Example

One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And
The and keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")

Prof. P.S.BRAHMANE
[Type the document title]

Or
The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

Nested If
You can have if statements inside if statements, this is called nested if statements.

Example

x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

The pass Statement


if statements cannot be empty, but if you for some reason have an if statement with no content, put in
the pass statement to avoid getting an error.

Example

a = 33
b = 200

if b > a:
pass

Prof. P.S.BRAHMANE
[Type the document title]

Looping in python:
for loop:
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.
Iterating over a sequence is called traversal.
Syntax of for Loop

for val in sequence:

Body of for

Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the
rest of the code using indentation.

Example: Python for Loop


# Program to find the sum of all numbers stored in a list # List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum sum = 0

# iterate over the list for val in numbers:


sum = sum+val

Prof. P.S.BRAHMANE
[Type the document title]

print("The sum is", sum)

When you run the program, the output will be:

The sum is 48

Python while Loop:


Loops are used in programming to repeat a specific block of code. In this article, you will learn to
create a while loop in Python.

The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.

We generally use this loop when we don't know the number of times to iterate beforehand.

Syntax of while Loop in Python

while test_expression:

Body of while

In the while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to 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 body starts with indentation and the first unindented line marks the end.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

Prof. P.S.BRAHMANE
[Type the document title]

Flowchart of while Loop

Example: Python while Loop

# Program to add natural


# numbers up to
# sum = 1+2+3+...+n

# To take input from the user,


# n = int(input("Enter n: "))

n = 10

# initialize sum and counter


sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1 # update counter

# print the sum


print("The sum is", sum)

When you run the program, the output will be:

Prof. P.S.BRAHMANE
[Type the document title]

Enter n: 10
The sum is 55

Nested Loop in Python:


A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

Output:

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

Loop Control Statements in Python:


Sometimes, you may want to break out of normal execution in a loop.

For this, we have three keywords in Python- break, continue, and pass.

1. break statement

Prof. P.S.BRAHMANE
[Type the document title]

When you put a break statement in the body of a loop, the loop stops executing, and control shifts to the
first statement outside it.

You can put it in a for or while loop.

Example:

>>> for i in 'break':

print(i)

if i=='a': break;

Output
b
r
e
a

2. continue statement
When the program control reaches the continue statement, it skips the statements after ‘continue’.

It then shifts to the next item in the sequence and executes the block of code for it. You can use it with
both for and while loops.

Example

>>> i=0

>>> while(i<8):

i+=1

if(i==6): continue

print(i)

Output
1
2
3
4
5
7
8

If here, the iteration i+=1 succeeds the if condition, it prints to 5 and gets stuck in an infinite loop.

Prof. P.S.BRAHMANE
[Type the document title]

You can break out of an infinite loop by pressing Ctrl+C.

Example

>>> i=0

>>> while(i<8):

if(i==6): continue

print(i)

i+=1

Output
01

Traceback (most recent call last):


File “<pyshell#14>”, line 1, in <module>
while(i<8):
KeyboardInterrupt

3. pass statement
In Python, we use the pass statement to implement stubs.

When we need a particular loop, class, or function in our program, but don’t know what goes in it, we
place the pass statement in it.

It is a null statement. The interpreter does not ignore it, but it performs a no-operation (NOP).

Example

>>> for i in 'selfhelp':

pass

>>> print(i)

Output
p

To run this code, save it in a .py file, and press F5. It causes a syntax error in the shell.

Prof. P.S.BRAHMANE
[Type the document title]

Prof. P.S.BRAHMANE

You might also like