Unit-10
Unit-10
10.1 INTRODUCTION
A Pythonis a general-purpose, high level programming language which is
widely used by programmers. It was created by Guido Van Rossum in 1991
and further developed by the Python Software Foundation. It was designed
with an emphasis on code readability, and its syntax allows programmers to
express their concepts in fewer lines of code. To learn how to code in any
language, it is, therefore, very important to learn its basic components. This is
what is the objective of this chapter. In this chapter, we will learn about the
basic constituents of Python starting from its identifiers, variables, operators
andalso about how to combine them to form expressions and statements. We
will also study about the data types available in Python along with the control
flow statements.
10.2 OBJECTIVES
After going through this unit, you will be able to:
Understand the basic building blocks of Python programming
Language
Understand various Data Structures
Understand usage of control flow statements
213
Identifiers can be a combination of letters in lowercase (a to z) or Data S
Cont
uppercase (A to Z) or digits (0 to 9) or an underscore (_). Names like
myIndia, other_1 and mca_course, all are valid examples. A Python
identifier can begin with an uppercase or a lowercase alphabet or (_).
An identifier cannot start with a digit but is allowed everywhere else.
1plus is invalid, but plus1 is perfectly fine.
Keywords (listed in TABLE1) cannot be used as identifiers.
One cannot use spaces and special symbols like !, @, #, $, % etc. as
identifiers.
Identifier can be of any length. (However, it is preferrd to keep it
short and meaningful).
Examples of valid identifiers are:marksPython, Course, MCA301 etc.
Keywords are a list of reserved words that have predefined meaning to the
Python interpreter.These are special vocabulary and cannot be usd by
programmers as identifiers for variables, functions, constants or with any
identifier name. Attempting to use a keyword as an identifier name will cause
an error. As Python is case sensitive, keywords must be written exactly as
given in TABLE1.
TABLE 1 :List of keywords in Python
214
Q3. All keywords in Python are in _____ Data Structures and
Control Statements
a) lower case in Python
b) UPPER CASE
c) Capitalized
d) None of the above
Print(1)
x=2
print(x)
In[]: 7 + 3
Out[]: 10
But in script, an expression all by itself doesn’t show any output altogether.
You need to explicitly print the result.
10.5 VARIABLES
Avariable is a named placeholder to hold any type of data which the program
can use to assign and modify during the course of execution. Python is a
Dynamically Typed Language. There is no need to declare a variable
explicitly by specifying whether the variable is an integer or a float or any
other type. To define a new variable in Python, we simply assign a value to a
name.
Variable names can be arbitrarily long. They can contain both letters and
numbers, but they cannot start with a number. It is legal to use uppercase
letter; but it is a good idea to begin variable names with a lowercase letter.
Variable names are case-sensitive. E.g., IGNOU and Ignou are different
variables.
The underscore character can appear in a name. it is often used in names with
multiple words, such as my_name or marks_in_maths. Variable names can
start with an underscore character, but we generally avoid doing this unless
we are writing library code for others to use.
variable_name = expression
216
The equal sign (=) also known as simple assignment operator is used to Data Structures and
Control Statements
assign values to variables. In the general format, the operand to the left of the in Python
= operator is the name of the variable and the operand to the right of the =
operator is the expression which can be a value or any code snippet that
results in a value. That value is stored in the variable on the execution of the
assignment statement. Assignment operator should not be confused with the
= used in algebra to denote equality. E.g.,
In Python, not only the value of a variable may change during program
execution but also the type of data that is assigned. You can assign an integer
value to a variable, use it as an integer for a while and then assign a string to
the variable. A new assignment overrides any previous assignments.
Q11. What error occurs when you excecute the following Python Code
snippet?
apple = mango
a) SyntaxError
b) NameError
c) ValueError
d) TypeError
10.6 OPERATORS
Operators are special symbols that represent computations like addition and
multiplication. The values the operator is applied to are called operands.
Python language supports a wide range of operators. They are:
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Bitwise Operators
220
Note :For strings, the characters in both the strings are compared one by one Data Structures and
Control Statements
based on their Unicode value. The character with the lower Unicode value is in Python
considered to be smaller.
10.7.1 Number
10.7.2 String
10.7.3 None
223
10.7.4 List Data S
Cont
10.7.5 Tuple
10.7.6 Dictionary
10.7.7 Set
10.7.1 Number
In Numbers or Numerical Data Types, we mainly have numbers. These
numbers are also of four types : Integer, Float, Complex, Boolean.
In Interactive mode:
Note :type() function can be used to check the data type of the variables
Examples:
In[]: type(i)
Out[]: int
In[]: type(c)
Out[]: complex
In[]: b = 10>7
Out[]: bool
Out[]: True
10.7.2 String
224
A string is an ordered sequence of characters. These characters may be Data Structures and
Control Statements
alphabets, digits or special characters including spaces. String values are in Python
enclosed in single quotation marks (e.g. “hello’) or in double quotation marks
(e.g., “python course”). The quotes are not a part of the string, they are used
to mark the beginning and end of the string for the interpreter. In Python,
there is no character data type, a character is a string of length one. It is
represented by str class. Few of the characteristics of strings are:
Out[]: 12
Out[]: ‘o’
Out[]: ‘d’
Out[]: ‘o Fr’
If one omits the first index (before the colon), the slice starts at the beginning
of the string and if second index is omitted, the slice goes to the end of the
string.
In[]: str1[:3]
225
Out[]: ‘hel’ Data S
Cont
In[]: str1[3:]
10.7.3 None
A none is another special data type in Python. A none is frequently used to
represent the absence of a value. For example,
Some literatures on Python consider additional data types like List, Tuple,
Set &Dictionary whereas some others consider them as the built-in data
structures. We will put them in the category of data structures and discuss
considering them in same but considering them as data types is also not
wrong.
10.7.4 List
A list is a sequence of items separated by commas and items enclosed in
square brackets [ ]. These are similar to arrays available with other
programmimg languages but unlike arrays items in the list may be of
different data types. Lists are mutable, and hence, they can be altered even
after their creation. Lists in Python are ordered and have a definite sequence
and the indexing of a list is done with 0 being the first index. Each element in
the list has its definite place in the list, which allows duplicating of elements
in the list, with each element having its own distinct place and creditability. It
is represented by list class.
In[]: list1 = [5, 3.4, ‘IGNOU’, ‘Part 3’, 45] #to create a list
Out[]: 5
Out[]: Part 3
Out[]: 45
Out[]: 'IGNOU'
10.7.5 Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the
collection of the items of different data types. The items of the tuple are
separated with a comma and enclosed in parentheses.
A tuple is a read-only data structure as we can’t modify the size and value of
the items of a tuple and it is immutable.
Out[]: 'world'
10.7.6 Dictionary
A dictionary in Python holds data items in key-value pairs of items. The
items in the dictionary are separated with the comma and enclosed in the
curly brackets{}. Dictionaries permit faster access to data. Every key is
separated from its value using a colon(:) sign. The key value pairs of a
dictionary can be accessed using the key. Keys are usually of string type and
their values can be of any data type. In order to access any value in the
dictionary, we have to specify its key in square brackets[]. 227
#Creating dictionary dict1 Data S
Cont
In[]: dict1 = {'Fruit':'Apple','Climate':'Cold','Price(Kg)':120}
Out[]:Cold
10.7.7 Set
In Python, aset is an orderd collection of data type that is iterable, mutable
and has no duplicate elements. The order of elements in a set is undefined
though it may consist of various elements. The major advantage of using a
set, as opposed to a list, is that it has a highly optimized method for checking
whether a specific element is contained in the set.
Sets can be created by using the built-in set() function with an iterable object
or a sequence by placing the sequence inside curly braces, separated by
‘comma’. A set contains only unique elements but at the time of set creation,
multiple duplicate values can also be passed. The order of elements in a set is
undefined and is unchangeable. Type of elements in a set need not be the
same, various mixed-up data type values can also be passed to the set.
In[]: set1
#displaying contents of set1
Out[]: {' ', 'A', 'B', 'C', 'G', 'H', 'I', 'M', 'N', 'O', 'T', 'U'}
In[]: set2
Q25. In which of the following data type duplicate items are not allowed?
a) list
b) set
c) dictionary
d) None of the above
10.8.1 List
A list a container data type that acts as a dynamic aray. That is to say, a list is
a sequence that can be indexed into and that can grow and shrink. A few
characteristics of lists are:
A list has a (current) length – Get the length of a lsit with len()
function.
A list has an order – the items in a list are ordered, order going from
left to right.
A list is heterogeneous –different types of objects can be inserted into
the same list.
Lists are mutable and one can extend, delete, insert or modify items in
the list.
Examples :
list_name [index]
where index should always be an integer value and indicates the item to be
selected.
Out[]: ‘mahesh’
Out[]: 15
Output would be :
231
Traceback (most recent call last): Data S
Cont
File “<stdin>”, line 1, in <module>
numlist[6]
In addition to positive index numbers, one can also access items from the list
with a negative index number, by counting backwards from the end of the
list, starting at -1. It is useful of the list is long and we want to locate an item
towards the end of a list.
Out[]: ‘vishnu’
In[]: numlist[1:3]
Out[]: [6, 7]
In[]: mixed_list[:3]
In[]: mixed_list[2:]
In[]: numlist[:]
If the first index is omitted, the slice starts at the beginning and if the second
index is omitted, the slice goes to the end. So, if both indexes are omitted, the
slice is a copy of the whole list.
In[]: a = [1, 2, 3]
In[]: b = [4, 5, 6]
In[]: a + b
Out[]: [1, 2, 3, 4, 5, 6]
In[]: a == b
Out[]: False
in and not in membership operator are used to check for the presence of an
item in the list.
In[]: 2 in a
Out[]: True
Out[]: True
The built-in-list() function is used to create a list. The syntax for list()
function is,
list([sequence])
where the sequence can be a string, tuple or list itself. If the optional
sequence is not specified then an empty list is created.
In[]: greet
In[]: str_to_list
Lists are mutable in nature as the list items can be modified after a list has
been created. Also, a list can be modified by replacing the older item with a
newer item in its place and without assigning the list to a completely new
variable.
In[]: stringlist
In[]: listofstrings
In[]: stringlist
The most common way to traverse the elements of a list is with a for loop.
print(names)
Out[]: mahesh
ramesh
suresh
vishnu
ganesh
This works well if one needs to read the elements of the list. But if one wants
to write or update the elements, one needs the indices. For this one needs to
combine the functions range and len:
234
In[]: for i in range(len(numlist)) : Data Structures and
Control Statements
in Python
numlist[i] = numlist[i] * 2
In[]: numlist
This loop traverses the list and updates each element. The command len
returns the number of elements in the list.The command range returns a list of
indices from 0 to n-1, where n is the length of the list. Each time through the
loop, the variable i gets the index of the next element. The assignment
statement in the body uses i to read the old value of the element and to assign
the new value.
Python provides methods that operate on lists. For example, append adds a
new element to the end of a list:
In[]: numlist.append(50)
In[]: numlist
In[]: numlist.extend(nlist)
In[]:numlist
Out[]: [8, 12, 14, 20, 30, 26, 50, 25, 35, 45]
In[]: numlist.sort()
In[]: numlist
Out[]: [8, 12, 14, 20, 25, 26, 30, 35, 45, 50]
pop is used to delete elements from a list if the index of the element is
known:
In[]: numlist.pop(5)
Out[]: 26
In[]: numlist
Out[]: [8, 12, 14, 20, 25, 30, 35, 45, 50]
235
pop modifies the list and returns the element that was removed. If the Data S
Cont
removed element is not required then one can use the del operator:
In[]: numlist
To remove more than one element, del can be used with a slice index
In[]: numlist
If element from the list is known which needs to be removed and not the
index, remove can be used:
In[]: numlist.remove(30)
In[]: numlist
To get a list of all the methods associated with the list, pass the list function
to dir()
In[]: dir(list)
236
index() list.index(item) The index() method searches for the Data Structures and
Control Statements
given item from the start of the list and in Python
returns its index. If the value appears
more than once, you will get the index of
the first one. If the item is not present in
the list then ValueError is thrown by this
method.
Note: Replace the word”list” mentioned in the syntax with your actual list
name in your code.
There are many built-in functions for which a list can be passed as an
argument.
Built-In Description
Functions
sum() The sum() function returns the sum of numbers in the list.
all() The all() function returns True if all the Boolean values
237
in the list are True, else returns False. Data S
Cont
sorted() The sorted() function returns a modified copy of the list
while leaving the original list untouched.
In[]: len(stringlist)
Out[]: 5
In[]: sum(numlist)
Out[]: 175
In[]: max(numlist)
Out[]: 50
In[]: min(numlist)
Out[]: 20
Out[]: True
Out[]: True
In[]: sorted_stringlist
A list inside another list is called a nested list and you can get the behavior of
nested lists in Python by storing lists within the elements of another list. The
syntax for nested lists is:
Each list inside another list is separated by a comma. One can traverse
through the items of nested lists using the for loop.
In[]: asia[0][1]
Out[]: ‘Japan’
In[]: asia[1][2]
Out[]: ‘Thailand’
Q28. If we try to access the item outside the list index, then what type of
error it may give?
a) List is not defined
b) List index out of range
c) List index out of bound
d) No error
Q30. The marks of a student on 6 subjects are stored in a list, list1 = [80, 66,
94, 87, 99, 95]. How can the students average marks be calculated?
a) print(avg(list1))
b) print(sum(list1)/len(list1))
c) print(sum(list1)/sizeof(list1))
d) print(total(list1)/len(list1))
10.8.2 Tuple
In mathematics, a tuple is a finite ordered list (sequence) of elements. A tuple
is defined as a data structure that comprises an ordered, finite sequence of
immutable, heterogeneous elements that are of fixed sizes. Often, we may
want to return more than one value from a function. Tuples solve this
problem. They can also be used to pass multiple values through one function
parameter.
241
Although it is not necessary, it is common to enclose tuples in parantheses to Data S
Cont
help us quickly identify tuples when Python code is looked at:
It is actually the comma that forms a tuple making the commas significant
and not the parentheses.
To create a tuple with a single element, one must include the final comma:
In[]: t1 = (‘a’,)
In[]: type(t1)
Out[]: tuple
In Python, the tuple type is tuple. Without the comma Python treats (‘a’) as
an expression with a string in parentheses that evaluates to a string:
In[]: t2 = (‘a’)
In[]: type(t2)
Out[]: str
One can create an empty tuple without any values. The syntax is,
tuple_name = ()
In[]: empty_tuple = ()
In[]: empty_tuple
Out[]: ()
One can store any type of type string, number, object, another variable, and
even another tuple itself. One can have a mix of different types of items in
tuples, and they need not be homogeneous.
In[]: ignou
Most list operators also work on tuples. The bracket operator indexes an
element:
In[]: t[0]
Out[]: ‘a’
242
And the slice operator selects a range of elements. Data Structures and
Control Statements
in Python
In[]: t[1:3]
But if you try to modify one of the elemnts of the tuples, one will get an
error:
We can’t modify the elements of a tuple, but can replace one tuple with
another:
In[]: t
In[]: t * 2
Out[]: (‘A’, ‘b’, ‘c’, ‘d’, ‘e’, ‘A’, ‘b’, ‘c’, ‘d’, ‘e’)
in and not in membership operator are used to check for the presence of an
item in a tuple.
Comparison operators like <, <=, >, >=, == and != are used to compare
tuples.
Python starts by comparing the first element from each sequence. If they are
equal, it goes on to the next element, and so on, until it finds elements that
differ. Subsequent elements are not considered even if they are really big.
Out[]: True
Out[]: True
The built-in tuple() function is used to create a tuple. The syntax for the
tuple() function is:
tuple([sequence])
243
where sequence can be a number, string or tuple itself. If the optional Data S
Cont
sequence is not specified, then an empty tuple is created.
In[]: t3 = tuple()
In[]: t3
Out[]: ()
If the argument is a sequence (string, list or tuple), the result of the call to
tuple is a tuple with the elements of the sequence:
In[]: t3 = tuple(‘IGNOU’)
In[]: t3
In[]: t4 = (1, 2, 3, 4)
In[]: nested_t
There are many built-in functions as listed in TABLE for which a tuple can
be passed as an argument.
In[]: len(t3)
Out[]: 5
In[]: sum(t4)
Out[]: 10
In[]: t5 = sorted(t3)
244
In[]: t5 Data Structures and
Control Statements
in Python
Out[]: [‘G’, ‘I’, ‘N’, ‘O’, ‘U’]
One of the unique syntactic features of the Python language is the ability to
have a tuple on the left side of an assignment statement. This allows one to
assign more than one variable at a time when the left side is a sequence.
In[]: x, y = m
In[]: x
Out[]: ‘good’
In[]: y
Out[]: ‘luck’
In[]: x = m[0]
In[]: y = m[1]
Stylistically, when we use a tuple on the left side of the assignment statement,
we omit the parentheses, but the following is an equally valid syntax:
In[]: (x, y) = m
Though tuples may seem similar to lists, they are often used in different
situations and for different purposes. Tuples are immutable, and
usuallycontain a heterogeneous sequence of elements that are accessed via
unpacking or indexing. Lists are mutable, and their items are accessed via
indexing. Items cannot be added, removed or replaced in a tuple.
If an item within a tuple is mutable, then you can change it. Consider the
presence of a list as an item in a tuple, then any changes to the list get
reflected on the overall items in the tuple.
In[]: univ[3].append(‘soss’)
In[]: univ
To get a list of all the methods associated with the tuple, pass the tuple
function to dir().
Note: Replace the word “tuple_name” mentioned in the syntax with your
actual tuple name in the code.
In[]: channels.count(“dd”)
Out[]: 2
In[]: channels.index(“dd”)
Out[]: 0
In[]: channels.index(“zee”)
Out[]: 3
246
In[]: channels.count(“sab”) Data Structures and
Control Statements
in Python
Out[]: 1
1. tuple_items = ()
2. total_items = int(input("Enter the total number of items: "))
3. for i in range(total_items):
4. user_input = int(input("Enter a number: "))
5. tuple_items += (user_input,)
6. print(f"Items added to tuple are {tuple_items}")
7. list_items = []
8. total_items = int(input("Enter the total number of items: "))
9. for i in range(total_items):
10. item = input("Enter an item to add: ")
11. list_items.append(item)
12. items_of_tuple = tuple(list_items)
13. print(f"Tuple items are {items_of_tuple}")
247
Data S
Cont
Items are inserted into the tuple using two methods: using continuous
concatenation += operator and by converting list items to tuple items. In the
code, tuple_itemsis of tuple type. In both the methods, the total number of
items are specified which will be inserted to the tuple beforehand. Based on
this number, the for loop is iterated using the range() function. In the first
method, the user entered items are continuously concatenated to the tuple
using += operator. Tuples are immutable and are not supposed to be changed.
During each iteration, each original_tuple is replaced by original_tuple +
(new_element), thus creating a new tuple. Notice a comma after
new_element. In the second method, a list is created. For each iteration, the
user entered value is appended to the list_variable. This list is then converted
to tuple type using tuple() function.
The contents of variables a and b are reversed. The tuple variables are on the
left side of the assignment operator and, on the right side, are the tuple
values. The number of variables on the left and the number of values on the
right has to be the same. Each value is assigned to its respective variable.
Q38. Choose the correct way to access value 20 from the following tuple
aTuple = (“Orange”, [10, 20, 30], (5, 15, 25))
a) aTuple[1:2][1]
b) aTuple[1:2](1)
c) aTuple[1:2][1]
d) aTuple[1][1]
Q42. Which of the following options will not result in an error when
performed on tuples in python where tupl = (5, 2, 7, 0, 3)?
a) tupl[1] = 2
b) tupl.append(2)
c) tupl1 = tupl + tupl
d) tupl.sort()
10.8.3 Dictionaries
In the real world, you have seen your Contact-list in your phone. It is
practically impossible to memorize the mobile number of everyone you come
across. In the Contact-list, you store the name of the person as well as his
number. This allows you to identify the mobile number based on a person’s
name. One can think of a person’s name as the key that retrives his mobile
number, which is the value associated with the key. So, dictionary can be
thought of :
The keys of the dictionary must be immutable object types and are case
sensitive. Keys can be either a string or a number. But lists can not be used as
keys. A value in the dictionary can be of any data type including string,
number, list or dictionary itself.
250
Dictionaries are constructed using curly braces {}, wherein a list of key:value Data Structures and
Control Statements
pairs get separated by commas. There is a colon(:) separating each of these in Python
keys and value pairs, where the words to the left of the colon operator are the
keys and the words to the right of the colon operator are the values.
In[]: eng2sp
In[]: eng2sp[‘two’]
Out[]: ‘dos’
The key ‘two’ always maps to the value ‘dos’ so the order of the items
doesn’t matter. If the key isn’t in the dictionary, one get an exception:
In[]: eng2sp[‘four’]
Slicing in dictionaries is not allowed since they are not ordered like lists.
There are many built-in functions for which a dictionary can be passed as an
argument. The main operations on a dictionary are storing a value with some
key and extracting the value for a given key.
Built – in Description
Functions
all() The all() function returns Boolean True value if all the
keys in the dictionary are True else retuens False.
In[]: len(eng2sp)
Out[]: 3
len() function can be used to find the number of key:value pairs in the
dictionary eng2sp. In Python, any non-zero integer value is True, and zero is
interpreted as False. With all() function, if all the keys are Boolean True
values, then the output is True else it is False.
In[]: all(dict_func)
Out[]: False
For any() function, if any one of the keys is True then it results in a True
Boolean value else False Boolean value.
In[]: any(dict_func)
Out[]: True
The sorted() function returns the sorted list of keys by default in ascending
order without modifying the original key:value pairs. For list of keys sorted
in descending order by passing the second argument as reverse = True.
In[]: sorted(eng2sp)
Out[]: True
Out[]: False
The in operator uses different algorithms for lists and dictionaries. For lists, it
uses a linear search algorithm. As a list gets longer, the search time gets
252 longer in direct proportion to the length of the list. For dictionaries, Python
uses an algorithm called a hash table, so, the in operaor takes about the same Data Structures and
Control Statements
amount of time no matter how many items there are in a dictionary. in Python
clear() dictionary_name.clear() The clear() method removes all the key:value pairs
from the dictionary.
get() dictionary_name.get(key[, The get() method returns the value associated with the
default]) specified key in the dictionary. If the key is not present
then it returns the default value. If default is not given,
it defaults to None, so that this method never raises a
KeyError.
keys() dictionary_name.keys() The keys() method returns a new view consisting of aall
the keys in the dictionary.
pop() dictionary_name.pop(key[, The pop() method removes the key from the dictionary
default]) and returns its value. If the key is not present, then it
returns the default value. If the default is not given and
the key is not in the dictionary, then it results in
KeyError.
setdefault() dictionary_name.setdefault The setdefault() method returns a value for the key
(key[, default]) present in the dictionary. If the key is not present, then
insert the key into the dictionary with a default value
and return the default value. If key is present, default
defaults to None, so that this methos never raises a
KeyError.
update() dictionary_name.update([o The update() method updates the dictionary with the
key:value pairs from other dictionary object and it
253
ther]) returns None. Data S
Cont
values() dictionary_name.values() The values() method returns a new view consi
all the values in the dictionary.
Note: Replace the word “dictionary_name” mentioned in the syntax with the
actual dictionary name.
In[]: bolwd_million_dollar =
million_dollar.fromkeys(million_dollar, “1,00,00,000”)
In[]: bolwd_million_dollar
'dangal': '1,00,00,000',
'bajrangibhaijaan': '1,00,00,000'}
Out[]: 2015
In[]: million_dollar.keys()
In[]: million_dollar.values()
In[]: million_dollar.items()
In[]: million_dollar
Out[15]:
{'sanju': 2018,
'bajrangibhaijaan': 2015,
In[]: states.update({"Haryana":"Chandigarh"})
In[]: states.update({"Bihar":"Patna"})
In[]: states
print(key, states[key])
Out[]:
Haryana Chandigarh
Bihar Patna
west bengalkolkata
To delete the key:value pair, use the del statement followed by the name of
the dictionary along with the key you want to delete.
In[]: states
In[]:pm_year =
(('jln',1947),('lbs',1964),('ig',1966),('rg',1984),('pvn',1991),('abv',1998),('n
m',2014))
In[]: pm_year
Out[]:
(('jln', 1947),
('lbs', 1964),
('ig', 1966),
('rg', 1984),
('pvn', 1991),
('abv', 1998),
('nm', 2014))
In[]: pm_year_dict = dict(pm_year)
In[]: pm_year_dict
Out[]:
256
{'jln': 1947, Data Structures and
Control Statements
'lbs': 1964, in Python
'ig': 1966,
'rg': 1984,
'pvn': 1991,
'abv': 1998,
'nm': 2014}
The tuples can be converted to dictionaries by passing the tuple name to the
dict() function. This is achieved by nesting tuples within tuples, wherein each
nested tuple item should have two items in it. The first item becomes the key
and the second item as its value when the tuple gets converted to a
dictionary.
Q45. Items are accessed by their position in a dictionary and all the keys in a
dictionary must be of the same type.
a) True
b) False
Q50. Select all correct ways to remove the key ‘marks‘ from a dictionary
student = {
“name” : “Emma”,
“class” : 9,
“marks” : 75
}
a) student.pop(“marks”)
b) del student[“marks”]
c) student.popitem()
d) dict1.remove(“key2”)
Curly braces{} or the set() function can be used to create sets with a comma-
separated list of items inside curly brackets{}. Note: to create an empty set
you have to use set() and not{} as the latter creates an empty dictionary.
258
Sets are mutable. Indexing is not possible in sets, since set items are Data Structures and
Control Statements
unordered. One cannot access or change an item of the set using indexing or in Python
slicing.
In[]: basket
A set is a collection of unique items. Duplicate items are removed from the
set basket. Here, the set will contain only one item of ‘orange’ and ‘apple’.
Out[]: True
Out[]: False
One can test for the presence of an item in a set using in and not in
membership operators.
In[]: len(basket)
Out[]: 4
In[]: sorted(basket)
Total number of items in the set basket is found using the len() function. The
sorted() function returns a new sorted list from items in the set.
In[]: a = set('abrakadabra')
In[]: a
In[]: b = set('alexander')
In[]: b
Out[]: {'a', 'b', 'd', 'e', 'k', 'l', 'n', 'r', 'x'}
A list of all the methods associated with the set can be obtained by passing
the set function to dir().
Note: Replace the words “set_name”, “other” and “others” mentioned in the
syntax with your actual set names in your code.
In[]: flowers2.add('orchids')
In[]: flowers2.difference(flowers1)
In[]: flowers2.intersection(flowers1)
In[]: flowers2.isdisjoint(flowers1)
Out[]: False
In[]: flowers2.issuperset(flowers1)
Out[]: False
In[]: flowers2.issubset(flowers1)
Out[]: False
In[]: flowers2.symmetric_difference(flowers1)
In[]: flowers2.union(flowers1)
Out[]:
{'daisies',
'goldcrest',
'lavender', 261
'lilies', Data S
Cont
'orchids',
'roses',
'sunflower',
'tulips'}
In[]: flowers2.update(flowers1)
Out[]: flowers2
Out[]:
{'daisies',
'goldcrest',
'lavender',
'lilies',
'orchids',
'roses',
'sunflower',
'tulips'}
In[]: flowers2.discard("roses")
In[]: flowers2
Out[]:
{'daisies',
'goldcrest',
'lavender',
'lilies',
'orchids',
'sunflower',
'tulips'}
In[]: flowers1.pop()
Out[]: 'roses'
In[]: flowers2.clear()
In[]: flowers2
Out[]: set()
10.8.4.2Traversing of Sets
One can iterate through each item in a set using a for loop.
tulips is a flower
goldcrest is a flower
sunflower is a flower
10.8.4.3Frozenset
In[]: fs = frozenset(["g","o","o","d"])
#creating/declaring frozenset
In[]: pets
In[]: lang_used
Q56. The isdisjoint() method returns True if none of the items are present in
both sets, otherwise, it returns False.
a) True
b) False
264
Q58. The symmetric_difference() method returns a set that contains all items Data Structures and
Control Statements
from both sets, but not the items that are present in both sets. in Python
a) False
b) True
10.9.1 Sequential Control Flow Statements :This refers to the line by line
execution, in which the statements are executed sequentially, in the
same order in which they appear in the program.
10.9.2 Decision Control Flow Statements :Depending on whether a
condition is True or False, the decision structure may skip the
execution of an entire block of statements or even execute one block
of statements instead of other (if, if…else and if…elif…else).
10.9.3 Loop Control Flow Statements : This is a control structure that
allows the execution of a block of statements multiple times until a
loop termination condition is met (for loop and while loop). Loop
Control Flow statements are also called Repetition statements ot
Iteration Statements.
if Boolean_Expression :
statement (s)
The Boolean expression after the if statement is called the condition. We end
the if statement with a colon character (:) and the line(s) after the if statement
are indented. The if statement decides whether to run statement (s) or not
depending upon the value of the Boolean expression. If the Boolean
expression evaluates to True then indented statements in the if block will be
executed,otherwise if the result is False then none of the statements are
executed. E.g.,
265
is x > 0? Yes
If x >0 : Data S
Cont
print ( ‘x is positive’) print(‘x is positive’)
Fig. 5: If Logic
Here, depending on the value of x, print statement will be executed i.e. only
if x > 0.
There is no limit on the number of statements that can appear in the body, but
there must be at least one. In Python, the if block statements are determined
through indentation and the first unindented statement marks the end. You
don’t need to use the == operator explicitly to check if the variable’s value
evaluates to True as the variable name can itself be used as a condition.
Here, condition is False, so indented block would not be executed and only
the unindented statement after the if block would be executed.
if Boolean_Expression :
statement_blk_1
else
statement_blk_2
No
Yes
num % 2 == 0
A number is read and stored in the variable named num. The num is checked
using modulus operator to determine whether the num is perfectly divisible
by 2 or not. Num entered is 15 which makes the evaluated expression False,
so the else statement is executed and num is odd.
267
Data S
Cont
if Boolean_Expression_1 :
statement_blk_1
elif Boolean_Expression_2 :
statement_blk_2
elif Boolean_Expression_3 :
statement_blk_3
:
:
:
else :
statement_blk_last
Program 10.7 : Write a program to prompt for a score between 0.0 and
1.0. If the score is out of range, print an error. If the score is between 0.0
and 1.0, print a grade using the following table
268
Score Grade Data Structures and
Control Statements
>= 0.9 A in Python
>= 0.8 B
>= 0.7 C
>= 0.6 D
< 0.6 F
Yes
score >= 0.7
Your Grade is “C”
Yes
score >= 0.6 Your Grade is “D”
The outer conditional contains two branches. The first branch contains a
simple statement. The second branch contains another if statement has two
branches of its own. Those two branches are both simple statements, although
they could have been conditional statements as well.
Ye No
x == y
Ye No
x<y
print(‘equal’)
print(‘less’) print(‘greater’)
All years which are perfectly divisible by 4 are leap years except for century
years (years ending with 00) which is a leap year only it is perfectly divisible
by 400. For example, years like 2012, 2004, 1968 are leap years but 1971,
2006 are not leap years. Similarly, 1200, 1600, 2000, 2400 are leap years but
1700, 1800, 1900 are not.
You can almost read the while statement as if it were English. It means,
“While n is greater than 0, display the value of n and then reduce the value of
n by 1. When you get to 0, exit the while statement and display the word
Blastoff!”
The for loop is incomplete without the use of range() function which is a
built-in function. It is very useful in demonstrating for loop. The range()
function generates a sequence of numbers which can be iterated through
using for loop. the syntax for range() function is,
range([start ,] stop [, step])
Both start and step arguments are optional and is represented with the help of
square brackets and the range argument value should always be an iteger.
start value indicates the beginning of the sequence. If the start
argument is not specified, then the sequence of numbers start from zero by
default.
stop generates numbers up to this value but not including the
number itself.
step indicates the difference between every two consecutive
numbers in the sequence. The step value can be both negative and positive
but not zero.
PROGRAM 10.11 : Program to find the sum of all odd and even
numbers up to a number specified by the user.
1. number = int(input(“Enter a number”))
2. even = 0
274
3. odd = 0 Data Structures and
Control Statements
4. for i in range(number) : in Python
5. if i % 2 == 0 :
6. even = even + i
7. else :
8. odd = odd + i
9. print(f”Sum of Even numbers are {even} and Odd numbers are
{odd}”)
Fig. 14: Screen Shot of execution of Program 10.11
A range of numbers are generated using range() function. As only stop value
is indicated in the range() function, so numbers from 0 to 9 are generated.
Then the generated numbers are segregated as odd or even by using the
modulus operator in the for loop. All the even numbers are added up and
assigned to even variable and odd numbers are added up and assigned to odd
variable and print the result. The for loop will be executed / iterated number
of times entered by user which is 10 in this case.
PROGRAM 10.12 : Program to find the factorial of a number.
1. number = int(input(‘Enter a number’))
2. factorial = 1
3. if number <0 :
4. print(“Factorial doesn’t exist for negative numbers”)
5. elif number == 0 :
6. print(“The factorial of 0 is 1”)
7. else :
8. for i in range(1, number + 1) :
9. factorial = factorial * i
10. print(f”The factorial of number {number} is {factorial}”)
Fig. 15: Screen Shot of execution of Program 10.12
275
Data S
Cont
Read the number from user. A value of 1 is assigned to variable factorial. To find
the factorial of a number it has to be checked for a non – negative integer. If the user
entered number is zero then the factorial is 1. To generate numbers from 1 to the
user entered number range() function is used. Every number is multiplied with the
factorial variable and is assigned to the factorial variable inside the for loop. The for
loop block is repeated for all the numbers starting from 1 up to the user entered
number. Finally, the factorial value is printed.
276
Data Structures and
Control Statements
in Python
Fig. 16: Screen Shot of execution of Program 10.13
The continue statement in the while loop will not let the print statement to execute if
the count value is even and control will go for next iteration. Here, loop will go
through all the iterations and the continue statement will affect only the statements
in the loop to be executed or not occurring after the continue statement. Whereas,
the break statement will not let the loop to complete its iterations depending on the
condition specified and control is transferred to the statement outside the loop.
PROGRAM 10.15 : Program to check whether a number is prime or not
277
1. number = int(input(‘Enter a number: ‘)) Data S
Cont
2. prime = True
3. for i in range(2, number) :
4. if number % i == 0 :
5. prime = False
6. break
7. if prime :
8. print(f”{number} is a prime number”)
9. else :
10. print(f”{number} is not a prime number”)
Fig. 18: Screen Shot of Program 10.15
Q62. Given the nested if-else below, what will be the value x when the code
executed successfully?
x=0
278
a=5 Data Structures and
Control Statements
b=5 in Python
if a > 0:
if b < 0:
x=x+5
elif a > 5:
x=x+4
else:
x=x+3
else:
x=x+2
print(x)
a) 0
b) 4
c) 2
d) 3
279
Q66. What is the value of the var after the for loop completes its execution? Data S
Cont
var = 10
for i in range(10):
for j in range(2, 10, 1):
if var % 2 == 0:
continue
var += 1
var+=1
else:
var+=1
print(var)
a) 20
b) 21
c) 10
d) 30
10.10 SUMMARY
After the completion of this chapter, I am sure, you would be able to learn
and understand the basics of Python language. Using the contents explained
in this chapter, you would be able to turn your logic into codes where
identifiers and variables would help you to form statements and expressions
using operators, lists, tuples, sets and dictionries which are the back bone of
Python language which makes it unique and easy to program with. All the
basic structures of Python can be bound together with the control flow
statements which ultimately form a Python program.However, this is not all;
there is still a long way to go. Python has many more unique features which
make it a programmer’s language. So, Happy Programming!
280
Data Structures and
SOLUTIONS TO CHECK YOUR PROGRESS Control Statements
in Python
1. a 2. d 3. d 4. a 5. c 6. d
7. b 8. e 9. b 10. a 11. b 12. a
13. d 14. c 15. b 16. e 17. d 18. a
19. a 20. d 21. b 22. c 23. c 24. c
25. b 26. b 27. b 28. b 29. c 30. b
31. c 32. b 33. b 34. c 35. a 36. b
37. c 38. d 39. a,c 40. b 41. b 42. c
43. c 44. a,b 45. b 46. b 47. b 48. d
49. c 50. a,b,c 51. a,b,c 52. a,b,c 53. c 54. b
55. a 56. a,c,d 57. a,c,d 58. b 59. b 60. b
61. a 62. d 63. a 64. a 65. d 66. b
67. d
281