Python Unit 2
Python Unit 2
CONTROL STRUCTURES
2.1 BOOLEAN EXPRESSIONS
2.1.1 Boolean Values
The Boolean values are True and False. The relational operators such as = = , !=, > ,
< , >= , <= and the logical operators such as and, or, not are the Boolean operators. The
statement that prints either true or false is a Boolean expression. The following examples use
the operator !=, which compares two operands and produces ‘True’ if they are not equal and
‘False’ otherwise:
>>> 5 != 5 True
>>> 5 !=6 False
So, ‘True’ and ‘False’ are special values which belong to the Boolean type; they are
not strings (case sensitive):
Python has a data type called boolean, which can take two possible values, True and
False. Most functions that answer a yes/no question (or a true/false situation) will return a
boolean answer.
An expression that evaluates to a true/false value is called a Boolean expression.
BooleanExpressions are used mostly in control structures for testing a condition is true or
false.
Example:
1. print( True and True ) # prints True
2. print( True and False ) # prints False
3. print( 3 < 4 and 10 < 12 ) # prints True
2.2 Control Structures
Iterative Control: Used for looping, i.e. repeating a piece of code multiple times in a row. In
Python, there are three types of loops:
1. While Loop
2. For Loop
2.3 IF STATEMENT
Syntax:
If test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if
the text expression is True. If the text expression is False, the statement(s) is not executed.
In Python, the body of the if statement is indicated by the indentation. Body starts with
an indentation and the first unindented line marks the end.
Flow Chart:
Example program:
# If the number is positive, we print an appropriate message
num = 3
if num > 0:
Python 2.5
Example Program:
#Program checks if the number is positive or negative and displays an appropriate
message
num =- 3
if num >= 0:
2.6 Control Structures
print("Positive Number")
else:
print("Negative Number")
Output:
Negative Number
2.4 MULTIWAY SELECTION :
2.4.1 if...elif...else Statement
Syntax :
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
It allows us to check for multiple expressions. If the condition for if is False, it checks
the condition of the next elif block and so on. If all the conditions are False, body of else is
executed. The elif is short for else if. Only one block among the several if...elif...else blocks
is executed according to the condition.
The if block can have only one else block. But it can have multiple elif blocks.
Flowchart :
Python 2.7
Example Program:
# Python program to find the largest number among the three input numbers
a = int(input(“Enter first number: “))
b = int(input(“Enter second number:))
c = int(input(“Enter third number: ))
if (a > b) and (a > c):
largest = a
elif (b > a) and b>c):
largest = b
else:
largest=c
print(“The largest number between”,a,”,”,b,”and”,c,”is”,largest)
Output:
Enter first number: 4
Enter second number: 56
Enter third number: 6
(‘The largest number between’, 4.0, ‘,’, 56.0, ‘and’, 6.0, ‘is’, 56.0)
2.4.2 Nested if statements :
We can have a if...elif...else statement inside another if...elif...else statement. This is
called nesting in computer programming. Any number of these statements can be nested
inside one another. Indentation is the only way to figure out the level of nesting.
The structure of nested conditionals is shown below.
if test expression:
Body of if
else:
if test expression:
Body of if
else:
if test expression:
2.8 Control Structures
Body of if
:
:
else:
Body of else
The following programs explain nested conditional.
# Program to compare the values of x and y
x=3
y=4
if x == y:
print ‘x and y are equal’
else:
if x < y:
print ‘x is less than y’
else:
print ‘x is greater than y’
In this program the variables x and y are assigned with values 3 and 4 respectively. In
the first If statement it checks whether x is equal to y. If it is true, then prints x and y are
equal. If it is false, it executes the else part. Here, the else part contains the if statement
( Nested if ) checks whether x is lesser than y. If it is true, then it prints x is less than y. If it is
false, then it prints x is greater than y that is the statement in else part.
2.5 INDENTATION IN PYTHON :
Indentation in Python refers to the (spaces and tabs) that are used at the beginning of a
statement. The statements with the same indentation belong to the same group called a suite.
Consider the example of a correctly indented Python code statement mentioned below.
a = input('Enter the easiest programming language: ') //statement 1
if a == 'python': //statement 2
print('Yes! You are right') //statement 3
else: //statement 4
print('Nope! You are wrong') //statement 5
Python 2.9
Statement 1 gets executed first, then it gets to statement 2. Now only if statement 2 is
correct, we would want statement 3 to get printed. Hence Statement 3 is indented with 2
spaces. Also, statement 5 should be printed, if statement 4 is true and hence this is also
indented with 2 spaces. Statement 1, 2 and 4 are main statements which need to be checked
and hence these 3 are indented with the same space.
Iteration means executing the same block of code over and over, potentially many
times. A programming structure that implements iteration is called a loop. Iteration statements
or loop statements allow us to execute a block of statements as long as the condition is true.
Loops statements are used when we need to run same code again and again, each time with a
different value.
In programming, there are two types of iteration, indefinite and definite: With
indefinite iteration, the number of times the loop is executed isn’t specified explicitly in
advance. Rather, the designated block is executed repeatedly as long as some condition is met.
With definite iteration, the number of times the designated block will be executed is
specified explicitly at the time the loop starts.
A definite loop is a loop in which the number of times it is going to execute is known
in advance before entering the loop, while an indefinite loop is executed until some condition
is satisfied and the number of times it is going to execute is not known in advance. Often,
definite loops are implemented using for loops and indefinite loops are implemented using
while loops and do-while loops. But there is no theoretical reason for not using for loops for
indefinite loops and while loops for definite loops. But indefinite loops could be neatly
organized with while loops, while definite loops could be neatly organized with for loops.
1. While Loop
2. For Loop
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.
Here, key point of the while loop is that the loop might not ever run. When the
condition is tested and the result is false, the loop body will be skipped and the first statement
after the While loop will be executed.
Flow Chart:
Python 2.11
Example Program :
count = 0
while (count < 9):
print 'The count is:', count
count = count + 1
print "Good bye!"
Output:
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!
The block here, consisting of the print and increment statements, is executed
repeatedly until count is no longer less than 9. With each iteration, the current value of the
index count is displayed and then increased by 1.
2.7.2 The Infinite While Loop
A loop becomes infinite loop if a condition never becomes FALSE. You must use
caution when using while loops because of the possibility that this condition never resolves to
a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.
An infinite loop might be useful in client/server programming where the server needs
to run continuously so that client programs can communicate with it as and when required.
Example Program:
var = 1
while var == 1 : # This constructs an infinite loop
2.12 Control Structures
3 is less than 5
4 is less than 5
5 is not less than 5
Single Statement Suites
Similar to the if statement syntax, if your while clause consists only of a single
statement, it may be placed on the same line as the while header.
Here is the syntax and example of a one-line while clause −
flag = 1
while (flag):
print 'Given flag is really true!'
print "Good bye!"
It is better not try above example because it goes into infinite loop and you need to
press CTRL+C keys to exit.
2.8 DEFINITE LOOP
2.8.1 For Loop
For loop in Python is used to iterate over items of any sequence, such as a list or a
string.
Syntax
for val in sequence:
statements
Flowchart
2.14 Control Structures
Example Program:
for I in range(1,5):
print(i)
Output :-
1
2
3
4
The range() Function:
The range() function is a built-in that is used to iterate over a sequence of numbers.
Syntax :
range(start, stop[, step])
The range() Function Parameters :
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in the sequence.
Example 1 of range() function
Python 2.15
for i in range(5):
print(i)
Output :-
0
1
2
3
4
Example 2 of range() function
for i in range(2,8):
print(i)
Output :-
2
3
4
5
6
7
Example 3 of range() function using step parameter
for i in range(2,9,2):
print(i)
Output :-
2
4
6
8
Example 4 of range() function
2.16 Control Structures
for i in range(0,-10,-2):
print(i)
Output :-
0
-2
-4
-6
-8
2.8.2 For Loop With Else :
The else is an optional block that can be used with for loop.The else block with for
loop executed only if for loops terminates normally.This means that the loop did not
encounter any break.
Example of For Loop With Else
list=[2,3,4,6,7]
for i in range(0,len(list)):
if(list[i]==5):
print('list has 5')
break
else:
print('list does not have 5')
Output :-
list does not have 5
2.8.3 Nested For Loops
When one Loop defined within another Loop is called Nested Loops.
Syntax of Nested For Loops
for val in sequence:
for val in sequence:
statements
Python 2.17
statements
Example 1 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output :-
1
22
333
4444
55555
Example 2 of Nested For Loops (Pattern Programs)
for i in range(1,6):
for j in range(5,i-1,-1):
print(i, end=" ")
print('')
Output :-
11111
2222
333
44
5
2.8.4 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.
continue statement Causes the loop to skip the rest of its body
and immediately retest its condition before
reiterating.
Break statement
The break statement is used to change or alter the flow of execution. The looping
statements iterates till the test expression is true. In some cases, the current iteration of the
loop need to be terminated. The break statement is used in this case. The break statement
terminates the loop containing it. Therefore, control of the program transfers to the statement
immediately after the body of the loop. If break statement is used inside a nested loop (loop
inside another loop), break will terminate the innermost loop.
Syntax of break Statement
break
Flowchart:
print(i)
if(i == 7):
print('break')
break
Output :-
0
1
2
3
4
5
6
7
break
Example 2 of break statement
After break statement controls goes to next line pointing after the loop body.
for i in range(10):
print(i)
if(i == 7):
print('before break')
break
print('after break') # Inside loop body, any code after the break statement will not
execute
Output :-
0
2
2.20 Control Structures
7
before break
Out of loop body
Continue Statement:
Continue Statement in Python is used to skip all the remaining statements in the
loop and move controls back to the top of the loop.
Syntax of Continue Statement
continue
Flowchart of Continue Statement
print(i)
Output :-
0
1
2
4
5
when 'i' is equal to 3 continue statement will be executed which skip the print statement.
Pass Statement:
Pass Statement in Python does nothing. You use pass statement when you create a
method that you don't want to implement, yet.
Example using Pass Statement
It makes a controller to pass by without executing any code.
def myMethod():
pass
print('hello')
Output :-
hello
Example without using pass statement
def myMethod():
print('hello')
Output :-
Traceback (most recent call last):
File "python", line 3
print('hello')
Indentation Error: expected an indented block
Difference Between Pass And Continue Statement in Python
Pass statement simply does nothing. You use pass statement when you create a method
that you don't want to implement, yet.
2.22 Control Structures
Where continue statement skip all the remaining statements in the loop and move
controls back to the top of the loop.
Example of difference between pass and continue statement
for i in 'hello':
if(i == 'e'):
print('pass executed')
pass
print(i)
print('----')
for i in 'hello':
if(i == 'e'):
print('continue executed')
continue
print(i)
Output :-
h
pass executed
e
l
l
o
----
h
continue executed
l
l
o
2.9 LISTS
In Python, a list is a collection of ordered and indexed elements of different data types.
In Python, the list and its elements are mutable. That means, the list and its elements can be
Python 2.23
modified at any time in the program. In Python, the list data type (data structure) has
implemented with a class known as a list. All the elements of a list must be enclosed in square
brackets, and each element must be separated with a comma symbol. In Python, the list
elements are organized as an array of elements of different data types. All the elements of a
list are ordered and they are indexed. Here, the index starts from '0' (zero) and ends with
'number of elements - 1'.
In Python, the list elements are also indexed with negative numbers from the last
element to the first element in the list. Here, the negative index begins with -1 at the last
element and decreased by one for each element from the last element to the first element.
A list is a data type that allows you to store various types data in it. List is a compound
data type which means you can have different-2 data types under a list, for example we can
have integer, float and string items in a same list.
2.9.1. Create a List in Python
Lets see how to create a list in Python. To create a list all you have to do is to place the
items inside a square bracket [] separated by comma ,.
# list of floats
num_list = [11.22, 9.9, 78.34, 12.0]
# list of int, float and strings
mix_list = [1.13, 2, 5, "beginnersbook", 100, "hi"]
# an empty list
nodata_list = []
As we have seen above, a list can have data items of same type or different types. This
is the reason list comes under compound data type.
2.9.2 Accessing the items of a list
Syntax to access the list items:
list_name[index]
Example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# prints 11
print(numbers[0])
# prints 300
print(numbers[5])
2.24 Control Structures
# prints 22
print(numbers[1])
Output:
11
300
22
Points to Note:
1. The index cannot be a float number.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[1.0])
Output:
TypeError: list indices must be integers or slices, not float
2. The index must be in range to avoid IndexError. The range of the index of a list having 10
elements is 0 to 9, if we go beyond 9 then we will get IndexError. However if we go
below 0 then it would not cause issue in certain cases, we will discuss that in our next
section.
For example:
# a list of numbers
numbers = [11, 22, 33, 100, 200, 300]
# error
print(numbers[6])
Output:
IndexError: list index out of range
2.9.3. Negative Index to access the list items from the end
Unlike other programming languages where negative index may cause issue, Python
allows you to use negative indexes. The idea behind this to allow you to access the list
elements starting from the end. For example an index of -1 would access the last element of
the list, -2 second last, -3 third last and so on.
Example of Negative indexes in Python
Python 2.25
# a list of strings
my_list = ["hello", "world", "hi", "bye"]
# prints "bye"
print(my_list[-1])
# prints "world"
print(my_list[-3])
# prints "hello"
print(my_list[-4])
Output:
bye
world
hello
2.9.4. How to get a sublist in Python using slicing?
We can get a sublist from a list in Python using slicing operation. Lets say we have a
list n_list having 10 elements, then we can slice this list using colon : operator. Lets take an
example to understand this:
Slicing example
# list of numbers
n_list = [1, 2, 3, 4, 5, 6, 7]
# list items from 2nd to 3rd
print(n_list[1:3])
# list items from beginning to 3rd
print(n_list[:3])
# list items from 4th to end of list
print(n_list[3:])
# Whole list
print(n_list[:])
Output:
[2, 3]
[1, 2, 3]
[4, 5, 6, 7]
2.26 Control Structures
[1, 2, 3, 4, 5, 6, 7]
2.9.5. List Operations
There are various operations that we can perform on Lists.
2.9.5.1 Addition
There are several ways you can add elements to a list.
# list of numbers
n_list = [1, 2, 3, 4]
# 1. adding item at the desired location
# adding element 100 at the fourth location
n_list.insert(3, 100)
# list: [1, 2, 3, 100, 4]
print(n_list)
# list of numbers
n_list = [1, 2, 3, 4]
# Changing the value of 3rd item
n_list[2] = 100
# list: [1, 2, 100, 4]
print(n_list)
# Changing the values of 2nd to fourth items
n_list[1:4] = [11, 22, 33]
# list: [1, 11, 22, 33]
print(n_list)
Output:
[1, 2, 100, 4]
[1, 11, 22, 33]
[1, 3, 4, 5, 6]
[1, 3, 6]
2.9.5.4 Deleting elements using remove(), pop() and clear() methods
remove(item): Removes specified item from list.
pop(index): Removes the element from the given index.
pop(): Removes the last element.
clear(): Removes all the elements from the list.
# list of chars
ch_list = ['A', 'F', 'B', 'Z', 'O', 'L']
# Deleting the element with value 'B'
ch_list.remove('B')
# list: ['A', 'F', 'Z', 'O', 'L']
print(ch_list)
# Deleting 2nd element
ch_list.pop(1)
# list: ['A', 'Z', 'O', 'L']
print(ch_list)
# Deleting all the elements
ch_list.clear()
# list: []
print(ch_list)
Output:
['A', 'F', 'Z', 'O', 'L']
['A', 'Z', 'O', 'L']
[]
Built-in List Functions & Methods :
Python includes the following list functions :
Sr.No
Function with Description
.
1 cmp(list1, list2) Compares elements of both lists.
Python 2.29
Output:
10
50
75
83
98
84
32
2.10.2 Iterate through list in Python using a for Loop
Python for loop can be used to iterate through the list directly.
Syntax:
for var_name in input_list_name:
Example:
lst =[10, 50, 75, 83, 98, 84, 32]
forx inlst:
print(x)
Output:
10
50
75
83
98
84
32
2.10.3. List Comprehension to iterate through a list in Python
Python list comprehension is an indifferent way of generating a list of elements that
possess a specific property or specification i.e. it can identify whether the input is a list, string,
tuple, etc.
Python 2.31
Syntax:
expression/statement for item in input_list]
Example:
lst = [10, 50, 75, 83, 98, 84, 32]
[print(x) for x in lst]
Output:
10
50
75
83
98
84
32
2.10.4. Iterate through list in Python with a while loop
Python while loop can also be used to iterate the list in a similar fashion as that of for
loops.
Syntax:
while(condition) :
Statement
update_expression
Example:
lst = [10, 50, 75, 83, 98, 84, 32]
x=0
# Iterating using while loop
while x < len(lst):
print(lst[x])
2.32 Control Structures
x = x+1
Output:
10
50
75
83
98
84
32
2.10.5. Python NumPy to iterate through List in Python
Python NumPy can also be used to iterate a list efficiently.
Python numpy.arrange() function creates a uniform sequence of integers.
In the above of code, lambda x:x function is provided as input to the map()
function. The lambda x:x will accept every element of the iterable and return it.
The input_list (lst) is provided as the second argument to the map() function.
So, the map() function will pass every element of lst to the lambda x:x function and
return the elements.
Output:
[10, 50, 75, 83, 98, 84, 32]