Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 63

Python Programming

(BCACCA3102)
Unit 2 Lecture
Shakshi K Ranawat
Unit 2
Python Operators and Control Flow statements
• Introduction to Unit
• Basic Operators: Arithmetic, Comparison/ Relational, Assignment, Logical,
Bitwise, Membership,
• Identity operators, Python Operator Precedence
• Control Flow: Conditional Statements (if, if ... else, nested if)
• Looping in python (while loop, for loop, nested loops)
• loop manipulation using continue, pass, break, else.
• Conclusion of Unit
Learning Objectives
 Understand the difference between use of “=” in Python and in
mathematics.
 Realize that “=” is used for “assignment” and not for “equality
testing”.
 Identify the various types of operators used in Python: assignment;
arithmetic; comparison; Logical; bit-wise and special operators.
 Comprehend the “order of precedence” of operators.
 Use the six “comparison” operators (, ≥, ==, !=), the two identity
operators (is, is not) and the two membership operators (in, not in).
 List and use the three logical operators (and, or, not). • List and
use the six bitwise operators (&, |, ~, ^, ≫, ≪)
Assignment
 In Python, the ‘=’ sign or token is used to “assign” values
to a variable; hence, it is called the “assignment” operator.
 For instance, x = 5 is a simple assignment operator that
assigns the value 5 on the right to the variable x on the left.
 The assignment operator “=” can be thought of as an
arrow←.
 Thus a = 5 actually means a←5.
 So you can think of the variable “a” as a “box” which
“contains” the value 5.
Reassignment in Python
 There are many compound operators (or reassignment operators) in Python,
such as a += 5 (Which means a←a+5, that is, assign to “a” value 5 more than
“a”) that adds to the variable and later assigns the same. It is equivalent to a =
a + 5.
 So when you do a = a + 5, you are actually doing a “reassignment” or an
“update” of the value of the variable “a”.
 One can think of the “re-assignment” in a = a + 5 as a two-step process:-
 Evaluate the expression on the right-hand side (RHS).
 Let the variable name on the left-hand side (LHS) refer to this new resulting
object.
 The fact that the variable (“a” here) appears on both sides does not matter.
 In a reassignment expression, such as a = a + 5, the variable ‘a’ must pre-exist.
 So, if you try to use a reassignment expression, such as a = a + 5, before
“initializing” the variable “a”, it will lead to an error.
Various Assignment Operators in Python
(Along with examples)
Common Mathemetical Operators (With
Examples)
Order of precedence of operators
 The rules for “precedence of operators” in Python are the same as in
mathematics as follows:
 Parentheses have the highest precedence. So an expression in
“parentheses” is always evaluated first.
 After “parentheses”, “exponents” have the highest precedence. Next come
multiplication and division operators, which have the same precedence.
 Finally, there are addition and subtraction operators, which also have the
same precedence.
 Operators having the same precedence are evaluated from left to right.
This evaluation of operators of the same precedence from left to right is
called “left-associative”. For instance, in an expression such as “x – y +
z”, “x- y” gets precedence over “-y+z” since both “-” and “+” have the
same precedence but the operand “-” is to the left of the operand “+”
Precedence Table:
Types of operands and result of operation
 When an operator acts on two operands, there are the following
possibilities:
 The two operands are of the same “type” and the result of the operation
is also of the same “type”. A good example is adding two integers.
 The two operands are of the same “type” but the result of the operation
is a different type. An example of this is the division of an integer by
another integer. The result is always a “float”.
 The two operands are of different types, so the result is of one of the
types of operands. An example of this is when you multiply a float with
an integer. The result is a float. Whenever an operation is done on
operands, the programmer should be aware that
 Different operations may give different types of results.
 This topic relates to “casting” which is dealt with later.
Comparison Operators
Identity Operators
Identity Operators
Membership Operators
Logical Operators
Bit-wise operators

 The following are important concepts regarding bit-wise


 operators:
• They may be unary or binary.
• They treat the operand(s) as a “string” of “binary digits”.
• They are called bitwise operators since they act “bit by bit
Implementation of opeartors
Flow and need for flow control
 The term “flow control” in Python refers to the “order” in which
the Python statements in a script are executed.
 Need:
 Normally in a script, the lines of code are executed sequentially,
that is, one after another. But in many situations, one needs to
change the “sequential execution” of statements.
 Some common situations where one may have to change the
“normal or sequential” flow can be as follows:
 Function calls .
 Conditional statements or branches (In conditional statements, a
block of code is executed depending upon a specific condition)
 Iterations or loops (In iterations, a block of code is repeatedly
Learning objectives
 Understand “flow control” in a program.
 Identify and use the various types of “conditional statements”,
that is, (i) if-elif-else(ii)if-else (iii) Nested if and (iv) while loops.
 Explain why too deep nesting may cause problems and how to
avoid/ reduce nesting.
 Use (i) break (ii) continue and (iii) pass
 Decide when to use “while” loop and when to use “for” loop.
 Appreciate the use of “range” function and its use in looping.
 Comprehend the significance of infinite loops.
 Discuss some common errors in flow control and ways to avoid
them.
Using “if”
• The “if” statement can be used in a number of
ways. Some common usages are:
• if -- elif – else
• if -- else (Without elif)
• Omitting the else clause (that is, using an ‘if’
without an ‘else’)
• Nested if -- else Statements
• How to avoid nested if (Good programming
technique
Usage of “if --elif -- else” (See the pseudo-
code below)

 The ‘if’ condition and the ‘elif’ conditions must all be boolean
expressions. So all these expressions must evaluate to either True or False.
 This evaluation of a statement to either True or False is also called
“boolean context”.
 If the condition "condition_1" is True, the statements in the block
statement_block_1 will be executed.
 In Python, it is the indentation which indicates the beginning of a “block
or body” of code.
 Further, the “first un-indented” statement indicates the end of a block of
code.
 If condition_1 evaluates to False, then condition_2 will be evaluated. If
Flow chart showing how “if --elif -- else”
works
Working of “if – else” statement
 First, it evaluates the boolean test expression. If
this expression is True, then the “if” block is
executed.
 However if the “if” boolean expression
evaluates to False, then the entire “if” block is
skipped and the entire “else” block is executed.
 Note that the “if” block has a “boolean
expression”, but the “else” block does not have
any expression.
If else implementation:
Omitting the else clause (that is, using an
‘if’ without an ‘else’
 One can use an “if” statement without an “else” block. The
scheme works as follows:
 If the “if” boolean expression evaluates to True, then the “if”
block is executed and the rest of the script is also executed.
 However, if the “if” boolean expression evaluates to False,
then the “if” block is not executed and only the “rest of the
script is executed”.
 So, in conclusion, if the “if” boolean expression is True then
both the “if” block as well as the “rest of the script” are both
executed. But if the “if” boolean expression is False then
only the “rest of the script” is executed
Omitting the else clause shown as a figure
omitting the else clause(i.e , using an if
without an else)
python if...else statement without elif
Nested if else statement...
The “while” loop works as follows:
 At first the “boolean test expression” is checked.
 If the test expression is False, the “while loop” is not entered at all and the program
moves to the next line of code after the “while loop”.
 However, if the test expression evaluates to True, then the “while loop” is entered and
one iteration of the entire “while loop” is executed.
 After completion of one iteration, the expression of the “while loop” is again tested. If
the test expression evaluates to False, then the while loop is not entered again.
However, if the “while loop” test expression again evaluates to True, then the “while
loop” is executed again. This process goes on until the test expression of the ‘while’
loop evaluates to False.
 If the “while boolean expression” does not evaluate to False ever, then you will get an
“infinite loop, that is, a loop from which the script cannot exit.
 If initially the boolean expression of the “while loop” evaluates to False, then the
“while loop” is not run even once.
 Like in all other cases, the beginning of the “while loop” is marked by a level of
indentation and the end of the “while loop” is marked by the “first un-indented” line.
Flowchart of Python while Loop
Python while loop is used to run a block code until a certain
condition is met.
The syntax of while loop is:
while condition:
# body of while loop

1.A while loop evaluates the condition


2.If the condition evaluates to True, the code inside the while loop is executed.
3.condition is evaluated again.
4.This process continues until the condition is False.
5.When condition evaluates to False, the loop stops.
Sample Example of while :
Python While loop with else
In Python, a while loop may have an optional else block.
Here, the else part is executed after the condition of the loop evaluates to False
For loop
• A ‘for’ loop is a definite loop whereas a ‘while’ loop
is an indefinite loop. A ‘while’ loop is an indefinite
loop because it simply loops till a condition becomes
False. A ‘for’ loop, on the other hand, runs as many
times as there are items in the set. The general format
of a ‘for’ loop is as follows:
For Loop
 The first word of the statement starts with the keyword
“for” which signifies the beginning of the for loop.
 Then we have the iterator variable which iterates over the
sequence and can be used within the loop to perform various
functions
 The next is the “in” keyword in Python which tells the
iterator variable to loop for elements within the sequence
 Finally, we have the sequence variable , which can be a list,
a tuple, or any other kind of iterator.
 The statements part of the loop is where you can play around
with the iterator variable and perform various function
When to use ‘while’ and when to use ‘for’ loop

 Why have two kinds of loops, that is, ‘while’ and ‘for’? Suggestions for using a ‘for’
loop:
 You are already aware of the maximum number of times that you’ll need to execute the
body of the loop.
 or else you have a collection (Such as a string, a list, dictionary, tuple etc) and you
want to go over the individual items in the collection.
 The use of ‘for’ loop is called a definite iteration because there are some definite
boundaries.
Suggestions for using a ‘while’ loop:
 If you need to repeatedly do some computations until some condition is met, and you
have no way of knowing in advance as to when this will happen, then a ‘while’ loop is
a better idea.
 A ‘while’ loop is probably not a good idea for iterating or stepping over the items in a
collection.
 A “while” loop is called indefinite iteration because you don’t know in advance what
are the boundaries and how many iterations will be required.
The function range([start], stop[, step])
 Note: • The square brackets indicate that the parameter is optional. Hence,
if you have say range(10), it means that the parameters, start and step, have
been omitted.
 The default values of these are as follows:
 • - for start it is 0 and
 • - for step it is 1
 Hence, range(10) is the same as range(0,10) and the same as range(0,10,1).
 This means, if one parameter is given it will be presumed to be ‘stop’.
 If two parameters are given they will be presumed to be ‘start’ and ‘stop’.
 With a single argument, the range gives integers from zero up to but not
including the argument’s value.
 If one gives two arguments to the range() function, then the first is taken as
the lower bound. An optional third argument can give a step; if it is used.
Range Function
The next 3 slides show 12 important points
regarding the range() function -- 1
 The range() function can at most take three arguments, which
must all be integers. These three arguments are called “start”,
“stop” and “step”. Out of these three, “start” and “step” are
optional but the “stop” argument is mandatory.
 If the “start” argument is omitted, it gets a default value of 0.
 If the “step” argument is omitted, then it will get a default value
of 1.
 So the range function can be written as:- range([start= 0], stop[,
step= 1]). The “start = 0” and “step = 1” indicate the default
values for these two arguments.
 The full form returns a list in the following format: [start, (start +
step), (start + 2 * step), ... (Upto but not including stop) ].
range() function -- 2
 If the “step” parameter has a positive value, and start < stop, then the
contents of a range x are determined by the formula x[i] = start + step*I
where i >= 0 and x[i] <stop.
 Note that the “step” can be negative also. If it is negative, then the
progression will be a decreasing progression, that is, each successive
element is smaller than its predecessor. If the “step” is negative, the
formula for determining the members of the range() function output is:-
x[i] = start + step*i. However here x[i] > stop. So if step is negative,
the last element is the smallest start + i * step greater than stop. (Will
be clear from example below)
 You can omit the parameter “step” but “step” cannot be o. If you use 0 for “stop”, it
will lead to ValueError.
range() function -- 3
 If step is positive, then one can never reach stop. So, the
range will give an empty sequence. This will be clear from
example that follows.
 Similarly, if ‘start’ < ‘stop’ is and the ‘step’ is negative, then
also one can never reach ‘stop’. So, here also the range will
give empty sequence. This will be clear from the example
 The range() function can be used to create an “arithmetic
progression”. The term “arithmetic progression” is used for
a sequence of numbers such that the difference between any
two successive elements is the same.
 The range() function is generally used in “for” loops.
Range() Implementation
For Sample program:
Nesting Python for loops
 When we have a for loop inside another for loop, it’s
called a nested for loop. There are multiple applications
of a nested for loop.
 Consider the list example above. The for loop prints out
individual words from the list. But what if we want to
print out the individual characters of each of the words
within the list instead?
 This is where a nested for loop works better. The first
loop (parent loop) will go over the words one by one.
The second loop (child loop) will loop over the
characters of each of the words.
Example of nested loop
Break statement
 The following points regarding the “break” statement are
noteworthy:
 “break” statements are used inside “loops” or “nested loops”.
 In case the “break” statement is in a loop which is not nested,
then the “break” statement terminates the loop containing the
“break” statement. So, the control of the program will pass to
the statement immediately after the body of the loop containing
the “break” statement.
 In case the “break” statement is used in “nested loops”, then
the inner loop containing the “break” statement will terminate.
Further, the control of the program flows to the loop containing
the inner loop.
Working of Python break Statement
Sample program with break
“continue” statements
 The following points regarding the “continue”
statement are noteworthy:
 The “continue” statement is useful where you
don’t want to terminate a loop but only want to
“skip” the rest of the code in a loop.
 So with the “continue” statement, the loop
does not terminate, only the “remaining
statements” are skipped.
Working of Python continue Statement
Sample Program for continue statement
Pass Statements
 Some important aspects relating to the “pass” statement are as
follows:
 The “pass” statement is basically a “null” statement, that is, nothing
happens when a “pass” statement is executed. So a “pass” statement
is a no-operation, that is, “NOP”.
 The “pass” statement is basically used in programming as a “place
holder”. A “place holder” in programming refers to a piece of code
which has not been implemented.
 Note that a “pass” statement is different from a “comment”. The
Python interpreter ignores comments entirely. However, the
interpreter does not ignore the “pass” statement. The interpreter
simply does not do anything when it comes across a “pass”
statement.
The need for a place holder like “pass”
 A question which often arises is, ‘Why does one
need a ‘place holder’ like the “pass” statement?
 The answer is that many blocks of code in Python
cannot be empty.
 For instance, if you don’t give an indented block
after say an “if” or a “while” or “def” or a “class”,
then the interpreter will throw an error.
 You cannot use a comment as an indent block.
Sample program for pass
Thank you
“Simple is better than Complex”

You might also like