0% found this document useful (0 votes)
248 views

Test Your Skills in Python

Uploaded by

laxminayanan546
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
248 views

Test Your Skills in Python

Uploaded by

laxminayanan546
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 308

Test Your Skills In

Python
SECOND EDITION

SHIVANI GOEL

www.bpbonline.com
FIRST EDITION 2022
Copyright © BPB Publications, India
ISBN: 978-93-5551-181-2

All Rights Reserved. No part of this publication may be reproduced, distributed or transmitted in any
form or by any means or stored in a database or retrieval system, without the prior written permission
of the publisher with the exception to the program listings which may be entered, stored and executed
in a computer system, but they can not be reproduced by the means of publication, photocopy,
recording, or by any electronic and mechanical means.

LIMITS OF LIABILITY AND DISCLAIMER OF WARRANTY


The information contained in this book is true to correct and the best of author’s and publisher’s
knowledge. The author has made every effort to ensure the accuracy of these publications, but
publisher cannot be held responsible for any loss or damage arising from any information in this
book.
All trademarks referred to in the book are acknowledged as properties of their respective owners but
BPB Publications cannot guarantee the accuracy of this information.

www.bpbonline.com
Dedicated to
My GuruJi
&
My Family and Friends
Are you a Pythonist?
Test Your Skills in Python
The Zen of Python:
“Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced. ”
---- Tim Peters
About the Author
Dr Shivani Goel is an educator and researcher since last 22 years. She is
graduate in B.E. Computer Engineering (1998), post graduate in M. E.
Software Engineering (2006) and PhD.(2012) in Computer Science and
Engineering from Thapar University, Patiala, Punjab, India. Presently she is
Professor at Bennett University, Greater Noida, U.P., India. Her research
areas are artificial intelligence, software engineering, algorithms, data
structures and programming. She has guided many theses at post graduate
and doctorate level. She has more than 100 research publications in
International/National Conferences and reputed Journals. Counselling
students and motivating them for better learning is her passion. She is also
part of projects for designing MOOCs for better education in engineering.
She has authored two books: Test Your Skills in Python by BPB Publishers,
India and Express Learning- Artificial Intelligence by Pearson Education,
India. She has adapted many books for Indian audience.
Acknowledgement
I would like to thank Almighty for giving me desire and strength to write
this book. I am grateful to all my mentors for guiding me through all phases
of life.
I dedicate this book to all my mentors and students.
I am thankful to all members of my family especially my mother Mrs Usha
for their unconditional love, encouragement and kind support. My special
thanks to my loving daughters Gariyasi, Prakriti and caring husband
Deepak.
I am thankful to father late Sh. Ramesh Chand Goel, brother Vishal and
sisters Ashu and Shikha for giving me valuable feedback for improving the
contents and layout of this book.
My sincere thanks to my colleagues at School of Computer Science
Engineering and Technology, Bennett University for providing good
academic environment and support whenever needed.
This book is a result of constant encouragement and guidance from Dr
Deepak Garg, Dean, School of Computer Science Engineering and
Technology, Bennett University. I would also like to thank all my readers
who appreciated first version of the book and gave a positive review.
I would also like to thank BPB publications for publishing this work and
making my dream come true.
Preface
In this changing world, new programming languages are coming up and
curriculum is revised to help students learn the latest trends. I was to teach
Python to first year students for the first time. I was on a new journey to
learning Python. I found it really interesting. I came up with an idea to write
a book for learning in a simple way. I collected more than 400 questions on
all the topics learned. This was published as “Test Your Skills in Python”
first edition in 2017. Many questions on one topic in one chapter helped the
reader in getting a holistic view on a particular topic. This collection of
questions was from my own experience of learning through reading books,
visiting online websites on Python and teaching with my colleagues at
Bennett University.
After getting a good feedback from the readers of my book, I have extended
the contents to include more than 1000 questions in this second edition of
the book. There are 16 topics covered namely: Syntax and Input-output,
Data types, Strings, Operators and Expressions, Decision Control
Statements, Loops, User- Defined Functions, Lists, Dictionaries, Sets,
Tuples, Classes, Files, Graphics, Arrays and Databases.
The details of the contents of all chapters are given below:
Chapter 1 covers the basic syntax of writing a Python program, different
formats for input from the screen and output on the screen. The chapter
starts with syntax for comments, string formats. Various types of errors in
Python while input-output are also discussed. The chapter also includes
functions for modules os in Python for getting information about files and
directories in the system. The module sys is covered for getting system
related information like path, version etc.
Chapter 2 covers various data types that are allowed in Python for storing
and manipulating data of different types. In includes scalar datatypes and
functions for converting from one datatype to another. The functions from
modules random, math and statistics are also included. Module random
includes functions for generating random numbers in different ranges. The
module math includes functions for log, sin, tan cos etc. The module
statistics include functions like mean, mode, median, standard deviation etc.
Chapter 3 covers many operations which can be performed on strings in
Python. The required package string for manipulation of strings and format
of various functions is discussed with examples. The functions include
changing cases to uppercase or lowercase, finding sub string, finding length
of a string, and many more. The module re is also covered in the chapter as
it provides functions for identifying various regular expressions in strings.
Chapter 4 covers all operators in Python along with their precedence order
for execution. The categories of operators covered are arithmetic, bitwise,
relational, assignment, identify, membership and logical. Different types of
expressions are given and explained.
Chapter 5 covers various decision control statements like if statement, if-
else statement, if-elif statement etc. Different programs using these are
given for finding the output.
Chapter 6 covers loop control statements like for loop, while loop, do-
while loop. Different programs using these are given for checking the errors
or finding the output. Nested loops and break and continue statements are
explained with many examples and detailed explanation.
Chapter 7 covers the syntax of writing user-defined functions. Recursive
functions are also covered in the chapter. The use of lambda for creating
anonymous function is also discussed. The differences between local and
global variables are also included with many examples.
Chapter 8 covers lists in Python, how to use these for solving many
problems. Various functions and ways to manipulate lists are discussed in
different ways. These include functions for inserting, deleting, appending,
extending, copying, sorting, reversing, counting frequency in lists etc.
Various operators for performing operations are also given. The module
collections is also defined which appends and removes elements from the
end of a list.
Chapter 9 covers the ways of using dictionaries in Python. Operations ike
creating, printing, deleting from a dictionary are discussed.
Chapter 10 covers the use of sets and their use in solving different
problems in Python. Various operations that can be performed on sets are
discussed in detail with examples and explanation. These include finding
union, difference, intersection, membership and symmetric differences
between sets.
Chapter 11 covers the concept of tuples in Python. The process of using
tuples is also covered. The operators include performing membership,
addition, maximum and minimum operations on elements of a tuple.
Chapter 12 covers concept of classes and objects. The chapter includes the
details for defining new classes, constructors, member functions and data
members. The reuse of existing classes is also discussed using the concept
of inheritance.
Chapter 13 covers the use of files in Python. Different modes of creating,
reading and writing in files and various related errors are covered in the
chapter.
Chapter 14 covers the concepts of implementing graphics using package
tkinter. The information about functions to create various graphical objects
like button, list box, textbox etc. are summarized in the chapter.
Chapter 15 covers the concept of arrays in Python. Package NumPy is
illustrated for creating and manipulating one-dimensional and two-
dimensional arrays. The functions from package NumPy are discussed to
create arrays with different initial values, for finding shape and dimensions
of the array, for finding sum, maximum and minimum values in the array.
Chapter 16 covers the concept of databases in Python. The package
SQLite3 and its commands for database manipulations are covered in the
chapter. The commands include insert, delete, drop, dump, quit, connect,
create, select and update.
To get complete benefits, the reader should read first Getting Started. The
novice users should read all the chapters in the given sequence because all
the topics required in a chapter are discussed in all proceeding chapters.
However, readers who know Python can jump to any chapter for testing
their skills in that topic. The detailed explanation provided along with
answers help the reader in understanding the concepts. Model test papers
add theory part and programs as well.
My best wishes to all my readers for a successful journey to programming
in Python.
Getting Started
Before beginning journey to programming in Python, we need to note
important steps:
Download python from www.python.org and install as par the
instructions given on the website for your operating system. Say for
windows it is stored in folder C:\python35.
Note: We have executed all programs/commands in version 3.5.2 for
windows. Some of the conventions may not work in different
versions.
Set Python path variable in window’s class path variable by adding
using
My Computer>Properties>Advanced System Settings>Environment
Variables> Path Variable> Edit> ;C:\Python35 (in the end of current
value). This can also be done while downloading Python.
This enables you to run python interpreter by calling python.exe on
command line or Start Python IDLE (in windows) and execute
programs saved from any folder in your computer.
To run any command in Python, type it in Python shell window:
>>> print (“Welcome to Python”)
You will see the following Python shell window

Figure 1: Python 3.5.2 Shell

To exit from the python interpreter, press ctrl+D or File→Exit.


The menus in Python Shell window helps in performing various tasks.
File handling functions like creating a new file, opening an existing one
and saving can be done using File menu. In order to write a Python
program, open Python editor window using the following in Python shell:
File→New
The program is to be written in editor window and saved with a filename
with extension .py say for.py :

Figure 2: Python 3.5.2 Editor Window

To execute the program, choose File→Run (Module) or press F5 in


editor window. If more programs are written in a single file, it executes
all. The output will be shown in Python shell window:

Figure 3: Program output in Python 3.5.2 Shell

The IDLE of Python can be configured using Options →Configure


IDLE. The user can set the font size, color indentation etc. according to
his/her choice.
Python is a case sensitive language i.e. lowercase and uppercase letters
are different. All the statements in the body of a statement (decision
control, loop, function or class) should be indented.
For any help on any topic, press F1 or use Help Python Docs in Python
shell or refer to websites given in bibliography.
Any other online compiler for Python can be used:
https://www.onlinegdb.com/online_python_compiler
Code Bundle and Coloured Images
Please follow the link to download the
Code Bundle and the Coloured Images of the book:

https://rebrand.ly/31229b
The code bundle for the book is also hosted on GitHub at
https://github.com/bpbpublications/Test-Your-Skills-In-Python-
Language. In case there's an update to the code, it will be updated on the
existing GitHub repository.
We have code bundles from our rich catalogue of books and videos
available at https://github.com/bpbpublications. Check them out!

Errata
We take immense pride in our work at BPB Publications and follow best
practices to ensure the accuracy of our content to provide with an indulging
reading experience to our subscribers. Our readers are our mirrors, and we
use their inputs to reflect and improve upon human errors, if any, that may
have occurred during the publishing processes involved. To let us maintain
the quality and help us reach out to any readers who might be having
difficulties due to any unforeseen errors, please write to us at :
[email protected]
Your support, suggestions and feedbacks are highly appreciated by the BPB
Publications’ Family.

Did you know that BPB offers eBook versions of every book
published, with PDF and ePub files available? You can upgrade to
the eBook version at www.bpbonline.com and as a print book
customer, you are entitled to a discount on the eBook copy. Get in
touch with us at: [email protected] for more details.
At www.bpbonline.com, you can also read a collection of free
technical articles, sign up for a range of free newsletters, and receive
exclusive discounts and offers on BPB books and eBooks.
Piracy
If you come across any illegal copies of our works in any form on the
internet, we would be grateful if you would provide us with the
location address or website name. Please contact us at
[email protected] with a link to the material.

If you are interested in becoming an


author
If there is a topic that you have expertise in, and you are interested in
either writing or contributing to a book, please visit
www.bpbonline.com. We have worked with thousands of developers
and tech professionals, just like you, to help them share their insights
with the global tech community. You can make a general application,
apply for a specific hot topic that we are recruiting an author for, or
submit your own idea.

Reviews
Please leave a review. Once you have read and used this book, why
not leave a review on the site that you purchased it from? Potential
readers can then see and use your unbiased opinion to make purchase
decisions. We at BPB can understand what you think about our
products, and our authors can see your feedback on their book.
Thank you!
For more information about BPB, please visit www.bpbonline.com.
Table of Contents
1. Syntax and Input–Output
2. Data types
3. Strings
4. Operators and Expressions
5 Decision Control statements
6 Loops
7 User Defined Functions
8 Lists
9 Dictionaries
10 Sets
11 Tuples
12 Classes
13 Files
14 Graphics
15 Arrays (NumPy)
16 Databases
Appendix A: Python keywords and their use
Appendix B: Operators in Python and their precedence
Appendix C: Libraries in Python and common functions
Bibliography
Model Test Paper 1 (Solved)
Model Test Paper 2 (Solved)
Model Test Paper 3 (Solved)
Model Test Paper 4 (Solved)
Model Test Paper 5 (Solved)
Model Test Paper 6 (Solved)
Model Test Paper 7 (Unsolved)
CHAPTER 1
Syntax and Input-Output
In this chapter, you need to answer many questions related to the syntax
and input output in Python.

Key Points
A Python program consists of one or more statements.
One Python statement is written on separate line. Every Python statement
ends with a NEWLINE character (known as carriage return).
Backslash character(\) is used to extend one logical statement to next
physical line. Character semicolon (;) is used to separate multiple logical
statements in a single line.
The expressions in parentheses ( ), braces { } or square brackets [ ] can be
written in multiple lines without backslashes.
Many statements are grouped as a block using indentation (leading spaces
or tab with 4 spaces). These are used for defining bodies of functions, loops
or classes. A block can have inner blocks with more tabs. Colon (:) is used
to start a block.
A line in commented by using # at the beginning of the statement.
A triple quoted ‘’’ multi-line string is treated as a comment provided it is
not a docstring of a function or class.
Naming conventions: The name given to constants, variables, functions,
modules, classes etc. are called identifiers. It should start with either an
alphabet letter or an underscore (_). Any number of digits (0-9) or alphabets
(a-z, A-Z) can be used in identifier name. Variable. Module, package and
function names should be in lowercase and multiple words should be
separated by _. Class names should use TitleCase convention. Two leading
and trailing underscores are reserved for special purpose.
The function input ( ) is used to read the value entered by the user on the
command prompt.
Reserved identifers start with _*, __*__, __*. _* stores the result of last
evaluation; __*__ represents system-defined identifiers like __new__(),
__init__(), __name__, __main. These are also known as dunder names. __*
is used to represent private members of a class.
There are 33 keywords in Python 3 which have predefined meaning. Please
refer to annexure A for details. An identifier name cannot be same as a
keyword.
The function print ( ) is used to print the specific output on the output
screen.
The string can be formatted using .format() function in print function.
string.format(var1,var2…)
Formatters can be put in one or more replacement fields and placeholders
defined by a pair of curly braces {} into the string.{}. format(value) where
value can be integers, floating-point, strings or variables. The order is
important in case of multiple placeholders and corresponding values.
d-integer, f-floating-point, b-binary equivalent, o-octal equivalent, X or x-
hexadecimal equivalent, s- string, c- character, i-signed decimal integer, u-
unsigned decimal integer, e-exponent notation
%n reserves n spaces for the value (right justified)
%-n reserves n spaces for the value (left justified)
%< left align, > right align, ^ centre align
Python uses try and catch block for exception handling. The try block
contains the statements which are likely to get an exception like divide by
zero, divide an integer by a string, a wrong format specifier for output etc.
The except block is required to have statements which are required to
handle the exception, mostly an error message.
The functions from a package can be used by including package for given
program using import package_name.
SyntaxError is raised when the statements are not in the prescribed usage.
IndentationError is raised when there is incorrect indentation.
TabError is raised when the indentation consists of inconsistent tabs and
spaces.
TypeError is raised when a function or operation is applied to an object of
an incorrect type.
ImportError is raised when a specific function from module cannot be
imported.
NameError is raised when a variable if not found in the local or global
scope
ModuleNotFoundError is thrown when a module is not found.
ValueError is raised when a function gets an argument of correct type but
improper value.
OS module functions: import os
os. getcwd( ) function returns the current working directory in OS.
os.mkdir( ) to create a new directory in current working directory or drive
os.chdir( ) to change directory to given directory or drive or to parent
directory(..)
os.rmdir( ) removes the specified directory (empty) [absolute or relative
path]
os.listdir( ) returns the list of all files and directories in the specified
directory.
os.getpid() returns the process ID of the current process
Sys module displays system variables in runtime environment: import sys
sys.path - displays the path for all modules
sys.version- displays the current version of the Python interpreter
sys.version_info- displays the detailed information current version of the
Python interpreter
sys.maxsize – displays the largest integer value an integer can take.
sys.exit – causes the Python script/program to exit
sys.argv – returns a list of command line arguments passed to a Python
script or program

Questions
Q.1.1 What will be the output of the following command(s) in Python?
1. >>>print(“Thank You God!”)
2. >>>x=”Pinky”
>>>print(“Believe in yourself ”, x)
3. >>>print(“3 raised to power 4 = ”, 3**4)
4. >>>m=10
>>>n=20
>>>print(m, “ + ”, n, “ = ”, m+n)
5. >>>print(2+4, 6/3, 90*8)
6. >>> x=input()
[12]
>>>x
7. >>> x1= int(input(‘Enter an integer number’)) [23]
x1
Important terms: There is no explicit data type associated with a
single variable. For example x=10 defines x to be an integer variable
while x=9.5 defines it to be a floating variable. The character or string
variables are defined using single or double quotes. The function
input() function by default considers the input to be a string. We
need to type cast these explicitly to integer using function int() or to
floating-point using function float().
8. >>>
x=input()
[ 12 ]
x1= int(input(‘Enter an integer number’)) Enter an integer
number [ 23 ]
x1+x
9. >>> val=int(input(‘Enter a floating value’)) Enter a
floating value [23.7]
10. >>> int1=float(input(‘Enter a floating value: ‘))
Enter a floating value: [23]
int1
11. >>>import string
>for i in range(5):
print(repr(i).rjust(5))
Important terms: There are many in-built functions provided in
Python. These are defined using a module. One specific module
contains all related functions. For example, the module math contains
all functions related to mathematical functions. Similarly string
module contains definition of all functions which can be performed
with strings. In order to use the functions defined in a module, we
need to import it using command
import modulename
12. >>> "12".zfill(5)
13. >>>print(‘{0:.3f}’.format(5.7416))
14. >>> print(‘{0:.6f}’.format(5.9456))
15. >>>print(‘{4:.3f}’.format(8.2496))
16. >>>print(‘{0:9.3f}’.format(9.1011))
17. > for x in [‘Sunny’, ‘Monty’]:
print(‘hi “{} !”’.format(x) )
18. >>> print(‘{0:3d}, {2:6.1f}, {1:4d}’ .format(1,2,3.0))
19. >>>print(‘{0:3},{1:5},{2:6}’.format(‘Hello1’,‘Bye2’,3))
20. >>> count = {‘Unit’: 1, ‘Tenth’: 10, ‘Hundredth’: 100}
for place, value in count.items():
print(‘{0:10} ==> {1:10d}’.format(place, value))
21. >>> print (“Result {0:f}% : {1}!!”. format(100,
“Congrats”))
22. >>>print (“Average of {0} is {1:.2f}%”.format(“class”,
78.234876))
23. >>>print (“Overall Average: {0:.0f}%”.format(75.2876))
24. >>> print(“The {0} of 13 is {1:b}”.format(“binary”, 13))
25. >>> print(“The {0} of 10 is {1:o}”.format(“octal”, 10))
26. >>> print(“The {0} of 20 is {1:x}”.format(“hexadecimal”,
20))
27. >>> print(“The {0} of 20 is {:x}”.format(“hexadecimal”,
20))
28. >>> print(“The {} of 30 is {:X}”.format(“hexadecimal”, 30))
29. >>> print(“It is {0:5} degrees !”.format(34))
30. >>> print(“{0:10} temperature in {1:8}!”.format(“Average”,
2010))
31. >>> print(“{0:4} temperature in {1:7}!”.format(“Average”,
2014))
32. >>> print(“{:*^20s}”.format(“GuruJi”))
33. >>> print(“{:^20s}”.format(“GuruJi”))
34. >>> for i in range(5,7):
>>> print(“{:5d} {:5d} {:5d} {:5d}”.format(i, i ** 2, i
** 3))
35. >>> for i in range(5,7):
>>> print(“{:5d} {:5d} {:5d}”.format(i, i ** 2, i ** 3))
36.
>>> import sys
>>> print(sys.version)
37.
>>> import sys
>>> print(sys.version_info)
38.
>>> import sys
>>> print(sys.maxsize)
39.
>>> import os
>>> print(os.getcwd())
40.
>>> import os
>>> print(os.getpid() )
41. >>> print(“SyntaxError”
42. >>> for i1 in range(4):
>>> print(i1)
43. >>> print(“Hello”)
>>> print(“123”)
44. >>> ‘3’+4
45. >>> from math import cube
46. >>> import operating_sys
47. >>> print(x)
48. >>> print(“{:d}”.format( 45.5))
49. >>> int(‘string’)
50. >>>name=input(“Enter your name:”
Enter your name ^c

Q.1.2 State whether the statements given below are True or False:________
i. The function input() takes an integer as input.
ii. x,y = input() is a valid statement in Python.
iii. We need to type cast an input value into an integer using function
int().
iv. We need to type cast an input value into a floating value using
function float().
v. We can input() a list of elements using a single input() function.
vi. print(‘ {0} and {1}’. format(‘abcd’, 24)) prints abcd as a string
while 24 as an integer.
vii. A number in the brackets refers to the position of the object passed
into the str.format() method used in function print().
viii. A function str.zfill() pads a numeric string on the right with
zeroes.
ix. The result of ‘-5.24’.zfill(9) will be -000005.24
x. ‘-5.24’.zfill(-10) fills zeroes in right making a total count of 10 digits.
xi. break is a valid identifier name.
xii. import statement can be written at any place in a Python program.
xiii. Multiple packages can be imported using single import statement
using comma operator.
xiv. The expressions in parentheses ( ), braces { } or square brackets [ ]
can be written in multiple lines without backslashes.
xv. listdir( ) function from os package returns the list of all files and
directories in the specified directory.
xvi. A line can be commented by placing # at any position.
xvii. sys.argc returns a list of command line arguments passed to a Python
script or Program.
xviii. IndexError is thrown in case placeholders in format string are more
than the values supplied.
xix. Format b is used for specifying a number in binary format.
xx. ValueError is thrown in case the format character specified is incorrect
for a particular type of value.

ANSWERS

1.1
1. print() function in Python takes a string argument in single quotes
or double quotes and print it on the screen. So the output will be
Thank You God!
2. print() function in Python can take any number of arguments such as
constant string, variable or an expression. In the given print()
function, the two arguments are constant string and a string variable.
So the value of string variable will be printed after the given string i.e.
Believe in Yourself Pinky
3. In given print() function, two arguments are passed, one is constant
string and the other one is the arithmetic expression. The output will
be constant string followed by the value of the arithmetic expression,
i.e. 3 raised to power 4 = 81.
4. In given print() function, there are three types of arguments, constant
strings, variables and an expression. The output will be constant
strings, values of variables and evaluation of expression, i.e. 10 + 20 =
30
5. In given print() function, there are three arithmetic expressions. The
output will be the result of their evaluations i.e. 6 2 720
6. In Python, input() function is used to input any value from user. The
interpreter prompts at the console for input using a blinking vertical
bar (|). The value entered is stored in variable on the left. By default,
the value entered is stored as a string. So the output of value 12
entered as integer will be printed as string i.e. ‘12’.
7. In Python, input() function is used to input any value from user. If it
does not take any argument, the interpreter prompts at the console for
input using a blinking vertical bar (|) without writing anything on the
screen. But it prints the message on the screen if it is passed as an
argument to input() function. The value entered is stored in variable
on the left. By default, the value entered is stored as a string. So the
function int() is used to type cast the string value into an integer.
The output will be: Enter an integer value:
If value 23 entered as integer will be printed as 23.
8. The command is an arithmetic operator + which is taking an integer
value and a string value which is not allowed in Python. An error
message will be printed by the Python interpreter:
TypeError: unsupported operand type(s) for +: ‘int’ and
‘str’
9. The input() function is type casting the string value into an integer. It
will print “Enter a floating value” because it is written in input()
message, but when the user enters a floating-point value, an error is
given:
ValueError: invalid literal for int() with base 10: ‘23.7’
10. The value entered is stored as a floating-point value using type cast
function float(). So value will be stored as 23.0 and printed on the
screen.
11. The values from 0 to 4 (not including 5) will be printed on each line
right justified to 5 places.
0
1
2
3
4
12. The output is printed as a string with total width 5 and zeroes filled on
left ‘00012’.
13. The output is formatted to three digits after decimal point. Since the
value after decimal contains 4 digits, it has been rounded off : 5.742
14. The output is formatted to 6 digits after decimal point. Since the value
after decimal contains 4 digits, zeroes have been added: 5.945600
15. Following error is reported because the index in the format string in
print() should start from 0 instead of 4 as there is only 1 argument for
printing
IndexError: tuple index out of range
16. The output is justified to total 9 digits with three digits after decimal
point. Since the value after decimal contains 4 digits, it has been
rounded off:
9.101
17. The two strings in the list are formatted according to the given format:
hi Sunny !
hi Monty !
18. The output is formatted as follows: first integer argument justified to 3
digits (using 0:3d), second integer argument is justified to 4 digits
(using 1:4d) and third floating point argument is justified to 6 places
with one digit after decimal place (using 2:6.1f). Since the order given
for printing is {0:3d}, {2:6.1f}, {1:4d}, so third value is printed after
first value and then the second value:
1, 3.0, 2
19. The output is formatted as follows: first integer argument justified to 3
digits (using 0:3), second integer argument is justified to 5 digits
(using 1:5) and third integer argument is justified to 6 places (using
2:6). Since the order given for printing is {0:3}, {1:5}, {2:6}, the
values are printed in the given order. For first argument only three
spaces are reserved, but being a string, it will display the entire
content, followed by second string left justified in 5 spaces and then
integer value right justified to 6 places:
Hello1,Bye2 , 3
20. The output is formatted with place values left justified to 10 places
and values right justified to 10 places (printed in any order):
Unit ==> 1
Hundredth ==>
100 Tenth ==>
10
21. Result 100.000000% : Congrats!!
22. Average of class is 78.23%
The result is round off to 2 decimal place after decimal point
23. Overall Average: 75%
The result is round off to 0 decimal place after decimal point
24. The binary of 13 is 1001
The format specifier b prints the binary equivalent of the number.
25. The octal of 10 is 12.
The format specifier o prints the octal equivalent of the number.
26. The hexadecimal of 20 is 14.
The format specifier x prints the hexadecimal equivalent of the
number.
27. ValueError: cannot switch from manual field specification to
automatic field Numbering.
Numbering should be used at all places in {} if used at any one place.
28. The hexadecimal of 30 is 1E.
The format specifier o prints the hexadecimal equivalent of the
number. The numbering is not used in both places {}. X uses A-F in
hexadecimal values.
29. It is 34 degress!
The value 34 is right justified to 5 total places.
30. Average temperature in 2010.
The value Average is right justified to 10 total places and 2010 is right
justified to 8 places.
31. Average temperature in 2014.
The value Average is right justified to 3 total places (full string printed
as such) and 2010 is right justified to 7 places.
32. *******GuruJi*******
The string is centre justified to total 20 places and filled with * in
place of spaces.
33. GuruJi
The string is centre justified to total 20 places and filled with spaces.
34. IndexError: tuple index out of range
Here 4 format specifiers are given for 3 placeholders. So error.
35. 5 25 125
6 36 216
The output is formatted to be placed in right justified to 5th column for
each value.
36. print(sys.version) prints the current version of Python.
3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32
bit (Intel)]
37. print(sys.version_info) prints the details about the version of Python:
sys.version_info(major=3, minor=5, micro=2,
releaselevel=’final’, serial=0)
38. print(sys.maxsize) prints the largest value an integer can take
39. The os module contains many functions. print(os.getcwd()) will print
the current working directory on screen.
40. print(os.getpid()) function is in os module. It prints the process ID of
the current process.
5884
41. SyntaxError: ) missing in print()
SyntaxError is thrown when the statements are not in the prescribed
usage.
42. IndentationError is thrown when there is incorrect indentation.
43. TabError is thrown when the indentation consists of inconsistent tabs
and spaces.
44. TypeError: must be str, not int
TypeError is thrown when a function or operation is applied to an
object of an incorrect type.
45. ImportError is thrown when a specific function from module cannot
be imported.
46. ModuleNotFoundError: No module named operatin_sys
ModuleNotFoundError is thrown when a module is not found.
47. NameError : x is not defined
NameError is thrown when a variable if not found in the local or
global scope ValueError:
ValueError is thrown when a function gets an argument of correct type
but improper
ValueError: invalid literal for int() with base 10: ‘string’
ValueError is thrown when a function gets an argument of correct type
but improper
48. KeyboardInterrupt
KeyboardInterrupt Error is thrown when the user presses the interrupt
key (ctrl+C or some other key) during the input operation or execution
of the program.

1.2
i. False
By default, the function input() takes the value as a string.
ii. False
Only one variable should be on the left side as we are taking only one
input through function input()
iii. True
input() function takes the value as a string. The function int() converts
the value into an integer.
iv. True
input() function takes the value as a string. The function float()
converts the value into a floating value.
v. False
Only one value can be taken as input using function input(). The
input() function is to be used in a loop for reading values in a list.
vi. False
We need to put {1d} in order to print the value as an integer.
vii. True
viii. False
A function str.zfill() pads a numeric string on the left with zeros.
ix. False
The minus sign ‘-’ will be counted in the total length 9.So the output
will be -00005.24
x. False
It does not fill zeroes in the string and prints only the string as it is.
This is because -10 in not a valid count of zeroes.
xi. False
A keyword cannot be a name of an identifier
xii. False
The statement import should be in the beginning of the program only.
xiii. False
Separate import statement should be used for each package.
xiv. True
xv. True
xvi. True
xvii. False
Sys.argv is used to read all command-line arguments
xviii. True
xix. True
xx. True
CHAPTER 2
Data Types
In this chapter, you need to answer many questions related to various data
types in Python.

Key Points
Python supports built-in scalar datatypes:
int – for storing whole numbers (positive or negative or zero). These can be
decimal, binary (starts with 0b and has 8 digits with 0’s or 1s), octal(starts
with 0o or 0O) or hexadecimal (starts with 0x or 0X). Leading zeroes are
not allowed in numbers.
float - for storing any real number with a floating-value representation in
which a fractional component is denoted by a decimal symbol or scientific
notation, e.g. 4.55, 1.24e2. These can be separated with _ for large values
like 23_345.34_678. The maximum size depends on the system. 2e400 is
considered as INFINITY, Inf, inf or infinity.
bool – for storing data with one of two built-in values True or False.
complex- for storing a number with a real and imaginary component (x+3y)
None- represents the null object in Python (returned by functions that do
not explicitly return a value).
string- It is sequence of unicode characters enclosed in single quotes,
double quotes or triple quotes.
The escape characters can be used to specific type of printing. It is formed
by using character backslash(\) followed by a character : \n (for printing a
new line), \’ (to print single quote on screen), \” (to print double quote on
screen), \\ (to print \ on screen), \b (to remove previous character), \t (to
print a tab), \nnn (to print number in octal notation where n is in range 0-7),
\xnn (to print number in hexadecimal notation), \onn ( to print in octal
notation where n is in range 0-9)
The function type( ) can be used to get the name of the class of a value.
The function int( ) converts a float or string to integer.
The function float( ) converts a integer or string to float.
The function complex( ) returns a complex number with real and
imaginary components.
The function hex( ) converts a decimal integer into hexadecimal number
with prefix 0x.
The function oct( ) converts a decimal integer into octal number with
prefix 0O.
The function bin( ) converts a decimal integer into binary number with
prefix 0b.

Random module : import random


random.random () returns a random floating-point between 0.0 to 1.0.
random.randint(x,y) returns a random integer number between the
specified integers.
random.randrange() returns a randomly selected element from the range
created by three arguments : start, stop and step. 0- default value of start, 1-
default value of step
random.choice() – returns a randomly selected element from a non-empty
sequence. IndexError exception s raised in case of empty sequence as
argument.
Random.shuffle() – re-oders the elements in a given list in random fashion
Math module- import math
math.radians() – converts angle degrees to angle in radians
math.degrees() – converts angle radians to angle in degrees
math.log10() – returns base-10 algorithm of given number.
math.log() – returns natural algorithm of given number.
math.sin() – returns the sine function for angles in radians
math.cos() – returns the cosine function for angles in radians
math.tan() – returns the tangent function for angles in radians
math. exp() – returns a float number after raising e to the power of given
number
pow(first, second) – raises first to second
math.ceil(23.5) returns the ceiling value 24
math.floor(23.5) returns the floor value 23
math.sqrt(25) returns square root of 25 in double 5.0
math.random() – returns a random value
math.pi- 3.141592653589793 (circumference to the diameter of a circle
and its value)
math.e- 2.718281828459045 (Euler’s number- base of the natural
algorithm)
Statistics module- import statistics
statistics.mean() – returns mean of given list of numbers
statistics.median() – returns median of given list of numbers
statistics.mode() – returns mode of given list of numbers
statistics.stdev() – returns standard deviation of given list of numbers

Questions
Q.2.1. What will be the output of the following command(s)?
1. >>> abs(-24.75)
2. >>>round(45.236) any(x > 0 for x in [1,2,-3,-4])
3. >>> round(45.236,1)any(x > 0 for x in [-1,-2,-3,-4])
4. >>> round(45.236,2)all(x > 0 for x in [1,2,-3,-4])
5. >>> x=10
>>> eval(‘x +1’)
6. >>> round(45.236,-1)globals()
7. >>> round(45.236,0)locals()
8. >>> max([2,3,56,0,-9])
9. >>> hex(147)
10. >>> bin(89)
11. >>> oct(13)
12. >>> complex(2,13)
13. >>> int(‘11’)
14. >>> int(‘s’)
15. >>> float(’23.4’)
16. >>> float(‘2x.5’)
17. >>>print(“\079”)
18. >>>print(“\x75”)
19. >>>print(“\x27”)
20. >>>print(0b1101)
2.21 What will be the output of the following commands?
>>> import math
>>> print(math.pi)
2.22 What will be the output of the following commands?
>>> import math
>>> random.random()
2.23 What will be the output of the following commands?
>>> import math
>>> data = [12.5, 71.75, 13.25, 10.75]
>>> statistics.mean(data)
2.24 What will be the output of the following commands?
>>> import statistics
>>> data = [12.5, 17.75, 15.5, 13.25, 10.75]
>>> statistics.median(data)
2.25 What will be the output of the following commands?
>>> import statistics
>>> data = [12.5, 71.75, 10.5, 13.5, 14.5,10.75]
>>> statistics.median(data)
2.26 What will be the output of the following commands?
>>> import statistics
>>> data = [12, 71, 12, 13, 10, 7, 13, 13]
>>> statistics.mode(data)
2.27 What will be the output of the following commands?
>>> import statistics
>>> data = [12, 12, 12, 71, 12, 13, 10, 7, 13, 13]
>>> statistics.mode(data)
2.28 What will be the output of the following commands?
>>> import statistics
>>> data = [12.5, 17.75, 15.5, 13.25, 10.75]
>>> statistics.stdev(data)
2.29 What will be the output of the following commands?
>>> import math
>>> math.log(1000,2)
2.30 What will be the output of the following commands?
>>> import math
>>> math.log10(1000)
2.31 What will be the output of the following commands?
>>> import math
>>> math.log10(100)
2.32 What will be the output of the following commands?
>>> import math
>>> math.log10(1300)
2.33 What will be the output of the following commands?
>>> import math
>>> math.radians(1000)
>>> math.radians(180)
2.34 What will be the output of the following commands?
>>> import math
>>> print(math.degrees(0))
>>> print(math.degrees(3.14))
2.35 What will be the output of the following commands?
>>> import math
>>> print(math.sin(0))
>>> print(math.sin(45.5))
2.36 What will be the output of the following commands?
>>> import math
>>> print(math.cos(0))
>>> print(math.cos(45.5))
2.37 What will be the output of the following commands?
>>> import math
>>> print(math.tan(0))
>>> print(math.tan(45.5))
2.38 What will be the output of the following commands?
>>> import math
>>> math.exp(10)
2.39 What will be the output of the following commands?
>>> import math
>>> math.exp(3)
2.40 What will be the output of the following commands?
>>> import math
>>> math.e
2.41 What will be the output of the following commands?
>>> x=50.13
>>> type(x)
2.42 What will be the output of the following commands?
>>> x=50+3j
>>> type(x)
2.43 What will be the output of the following commands?
>>> x=”Shivay”
>>> type(x)
2.44 What will be the output of the following commands?
>>> import random
>>> print(random.randint(20,100) )
2.45 What will be the output of the following commands?
>>> import random
>>> print(random.randrange(20,50))
2.46 What will be the output of the following commands?
>>> import random
>>> print(random.randrange(20,50,3))
2.47 What will be the output of the following commands?
>>> import random
>>> print(random.randrange(20,50,0.5))
2.48 What will be the output of the following commands?
>>> import random
>>> print(random.choice([20,50,3,11,13])
2.49 What will be the output of the following commands?
>>> import random
>>> print(random.choice(“random”)
2.50 What will be the output of the following commands?
>>> import random
>>> numbers= [1,3,7,13, 21, 10, 7]
>>> random.shuffle(numbers)
>>> print(numbers)

Q Select the most appropriate answer for the following


questions:
2.51 Which of the following function returns the absolute value of a
number, long integer or a floating point number?
a. ord()
b. chr()
c. abs()
d. None of these
2.52 Which of the following function is used to round off a floating-
point value to 2 places after decimal?
a. round(x,1)
b. round(x,-2)
c. round(x,2)
d. None of these
2.53 Which of the following function returns True if any element of
iterable is True?
a. all()
b. any()
c. iter()
d. None of these
2.54 Which of the following function takes an integer as argument and
returns a character whose ASCII code is that integer?
a. ord()
b. chr()
c. bin()
d. None of these
2.55 Which of the following function takes one character as input and
returns the Unicode code as integer?
a. ord()
b. chr()
c. bin()
d. None of these
2.56 Which of the following function converts an integer into an octal
string?
a. ord()
b. oct()
c. bin()
d. None of these
2.57 Which of the following function takes an object as input and
returns a string containing a printable representation of an object?
a. repr()
b. print()
c. reload()
d. None of these
2.58 Which of the following function is used to get a random listing of
given list of numbers?
a. random.random()
b. random.shuffle() (ans)
c. random. randrange()
d. None of these
2.59 Which of the following function returns a new sorted list from the
items in the iterable passed as argument?
a. list()
b. sorted()
c. slice()
d. None of these
2.60 Which of the following function returns a floating-point value
number rounded to some digits after the decimal point?
a. round()
b. setattr()
c. slice()
d. None of these
2.61 Which of the following function is used to get the most frequently
occurring element in the given list of numbers?
a. statistics. mode()
b. statistics. median()
c. statistics. mean()
d. None of these
2.62 Which of the following function retrieves the next item from the
iterator?
a. next()
b. range()
c. slice()
d. None of these
2.63 Which of the following function returns 100 for 100.5?
a. math. ceil()
b. math.floor()
c. math. abs()
d. All of these
2.64 Which of the following function returns the smallest item in the
given iterable or arguments(>=2)?
a. min()
b. hash()
c. id()
d. None of these
2.65 Which of the following function returns a floating-point number
constructed from a number or a string?
a. eval()
b. float()
c. bin()
d. None of these
2.66 Which of the following function executes expressions or arbitrary
code objects?
a. eval()
b. float()
c. int()
d. None of these
2.67 Which of the following function returns 51 for 50.5?
a. math. ceil()
b. math.floor()
c. math. abs()
d. All of these
2.68 Which of the following function constructs a list from those
elements of an iterable for which the function returns True?
a. sorted()
b. eval()
c. filter()
d. None of these
2.69 Which of the following function returns -51 for -50.5?
a. math. ceil()
b. math.floor()
c. math. abs()
d. All of these
2.70 Which of the following function converts an integer number to a
binary string?
a. bin()
b. oct()
c. str()
d. None of these
2.71 Which of the following function which returns a True or FALSE
value of an expression?
a. int()
b. bool()
c. hex()
d. None of these
2.72 Which of the following function returns a complex number?
a. getattr()
b. complex()
c. setattr()
d. None of these
2.73 Which of the following function returns -50 for -50.5?
a. math. ceil()
b. math.floor()
c. math. abs()
d. All of these
2.74 Which of the following function returns a randomly selected
element from a non-empty sequence?
a. random. shuffle()
b. random.choice()
c. random. randrange()
d. None of these
2.75 Which of the following is the use of random.randint() function?
a. returns a random floating-point between 0.0 to 1.0.
b. returns a random integer number between the specified integers.
c. returns a randomly selected element from the range
d. All of these

ANSWERS

2.1
i. 24.75
abs() returns the absolute value.
ii. 45 The number is rounded as integer value
True
any() returns True if any element of the iterable is True.
iii. 45.2 The number is rounded off to 1 decimal place
False
iv. any() returns True if any element of the iterable is True. Since none of
these is True, so the output is False.
v. 45.24
The number is rounded off to 2 decimal places
False
all() returns True if all elements of the iterable are True.
vi. 11
vi. 50.0
The number is rounded off to one digit to left of decimal
globals() returns a dictionary representing the current global
symbol table
{‘__name__’: ‘__main__’, ‘__package__’: None,
‘__builtins__’: <module ‘builtins’ (built-in)>,
‘__spec__’: None, ‘__loader__’: <class
‘_frozen_importlib.BuiltinImporter’>, ‘__doc__’: None}
vii. 45.0
The number is rounded off to no decimal place.
locals() returns a dictionary representing the current global symbol
table
{‘__name__’: ‘__main__’, ‘__package__’:
None, ‘__builtins__’: <module ‘builtins’
(built-in)>, ‘__spec__’: None, ‘__loader__’: <class
‘_frozen_importlib.
BuiltinImporter’>, ‘__doc__’: None}
viii. 56
(max() returns the maximum value in the list.
ix. ‘0x93’
The hexadecimal equivalent of 147.
x. ‘0b1011001’
The binary equivalent of 89.
xi. ‘0o15’
The octal equivalent of 13.
xii. The equivalent complex number : (2+13j)
xiii. The integer equivalent of 11: 11
xiv. ValueError: invalid literal for int( ) with base 10:’s’
Only base 10 digits (0 to 9) can be passed as string
xv. 23.4
The floating-point equivalent of 23.4
ValueError: cannot convert string to float:’s’
xvi. ‘u’
The hexadecimal equivalent of 75 (5+16*7=117)
xvii. ‘u’
The hexadecimal equivalent of 75 (5+16*7=117)
xviii. ‘ (single quote)
The hexadecimal equivalent of 27 (7+32=39)
xix. 13
The binary equivalent of 1101 (8+4+0+1=13)
2.21 By default, the pi value is stored as a double value
3.141592653589793
2.22 The random() function is defined in random module. It is not a part of
math library. So, following error will be reported because ‘import
random’ is missing:
NameError: name ‘random’ is not defined
The output with import random is 0.43704553941814095
2.23 The statistics.mean() function is defined in statistics module. It is not a
part of math library. So, following error will be reported because
‘import statistics’ is missing:
NameError: name statistics is not defined
The output with import statistics is 27.0625
2.24 The median is middle element in the sorted list [10.75, 12.5, 13.25,
15.5, 17.75] i.e. 13.25
2.25 The median is average of middle elements in the sorted list [10.5,
10.75, 12.5, 13.5, 14.5, 71.75] i.e. 12.5+13.5 = 13.0
2.26 The output is mode, i.e. most frequently occurring element, 13
2.27 The output is mode, i.e. most frequently occurring element, 12
2.28 The output is standard deviation i.e. 2.7237382399929695
2.29 The logarithm of 1000 base 2 will be printed: 9.965784284662087
2.30 The logarithm of 1000 base 10 will be printed: 3.0
2.31 The logarithm of 1300 base 10 will be printed:
2.32 The logarithm of 100 base 10 will be printed: 2.0
2.33 The angles in radians will be printed:
17.45329
3.14
2.34 The angles in degrees will be printed:
0.0
179.90874
2.35 The sine function values will printed:
0.0
0.99859087
2.36 The cosine function values will printed:
1.0
0.05306853
2.37 The tangent function values will printed:
0.0
18.8170042
2.38 The exponent of 10 (e**10) will printed: 22026.465794
2.39 The exponent of 3 (e**3) will printed: 20.0855369
2.40 The value of e will be printed i.e. 2.718
2.41 class <’float’>
2.42 class <’complex’>
2.43 <class ‘str’>
2.44 Any random value between 20 and 100 will be printed
2.45 Any random value between 20 and 100 will be printed.
2.46 Any random value between 20 and 100 will be printed, which is
selected from numbers in series 20, 23,26,…
2.47 ValueError exception will be raised because step value needs to be
integer only
2.48 Any one value from the given list of numbers will be printed
2.49 Any one character from the given string will be selected and printed.
2.50 The given list of numbers will be printed in any other order.
2.51 c
2.52 b
2.53 b
2.54 b
2.55 a
2.56 b
2.57 a
2.58 c
2.59 b
2.60 a
2.61 a
2.62 a
2.63 a
2.64 a
2.65 b
2.66 a
2.67 a
2.68 c
2.69 b
2.70 a
2.71 b
2.72 b
2.73 a
2.74 b
2.75 b
CHAPTER 3
Strings
In this chapter you will be able to check how much you know string
handling in Python.

Key Points
Every string is an object of class str in Python.
The function str() converts a number into string.
len()- returns number of characters in a string
string module: import string
string.lower()- returns a string in lower case
string.upper()- returns a string in upper case
string.title()- returns a string in tile case( first character in upper case
and rest of the characters in lowercase)
string.swapcase() – returns a string where uppercase is converted into
lowercase and vice-versa
string.zfill()- returns a copy of the string with ‘0’s padded to the left of
the string to make it equal to the length given in zfill().
string.center() – returns a new string centered justified for specific
length, padded with the given character, space otherwise.
string.rstrip()- returns a copy of the string be removing the trailing
characters.
string.lstrip()- returns a copy of the string be removing the leading
characters.
string.strip()- returns a copy of the string be removing both the leading
and trailing characters.
string.split()- returns a list object with string elements which are
splitted from the specified separator
string.rsplit()- returns a list object with string elements which are
splitted from the specified separator
string.splitlines()- returns a list object with string elements which are
splitted from the line boundaries.
String.rpartition()- returns a tuple with 3 elements (part before the
separator, the separator, part after the separator); returns (‘’,’’, string) in
case separator not found
string.join()- returns a string which is concatenated from given list of
strings.
string.replace()- returns a copy of the string where all occurrences of a
substring are replaced with another substring.
string.isupper()- returns True of all characters in the string are in
uppercase, False otherwise.
string.islower()- returns True of all characters in the string are in
lowercase, False otherwise.
string.istitle()- returns True of all characters in the string are in title
case, False otherwise.
string.isdigit()- returns True of all characters in the string are digits,
False otherwise.
string.isnumeric()- returns True of all characters in the string are
numeric characters, False otherwise.
string.isalpha()- returns True of all characters in the string are
albhabets, False otherwise.
string.isalpnum()- returns True of all characters in the string are
alphanumeric (numbers or alphabets) characters, False otherwise.
string.isspace()- returns True of all characters in the string are spaces,
False otherwise.
string.isidentifier()- returns True the string is a valid identifier, False
otherwise.
string.isdecimal()- returns True of all characters in the string are
decimal characters, False otherwise.
string.count()- searches for a given substring in the given string and
returns an integer indicating the number of occurrences of the substring.
string.find()- returns the index of the first occurrence of a substring in
the given string and -1, if not found.
string.rfind()- returns the index of the last occurrence (highest index) of
a substring in the given string and -1, if not found.
string.index()- returns the index of the first occurrence of a substring in
the given string.
string.rindex()- returns the index of the last occurrence of a substring in
the given string.
string.casefold()- returns a string in lower case
string.endswith()- returns True if a string ends with the specified suffix,
False otherwise.
Regular expression: a normal string prefixed with ‘r’ or ‘R’ becomes a raw
string which does not interpret any escape sequence in the string.
It can be used for find and replace operations on text using functions from
re module: import re
re.match()
re.search()
re.findall()
re.split()
re.complie()
meta characters: .^$*+?[]\|()

Questions
Q.3.1 What will be the output of the following commands?
1. >>> ‘hello’+‘world’
2. >>> 3*‘hi’+2*‘Usha’
3. >>> for c in “Gugu” :
>>> print(c)
4. >>> for ch in “ i love my Mammy and Papa”: print(ch,)
5. >>> weekend=”satsun”
>>> print(weekend[3:6])
6. >>> name = “Guido van Rossum”
>>> print(name[0]+name[:6])
7. >>> name = “Bhavica Bansal”
>>> print(name[-5])
8. >>> name = “Sujoy Bansal”
>>>print(name[:-5])
9. >>> name = “Sh. Ramesh Chand Goel”
>>> print(name[:])
10. >>> len(“Prakriti ! “)
11. >>> s= “Amit is elder to Sandeep”
>>> print(s.count(‘e’))
12. >>>import string
>>>s = “Bennett University”
>>>str. find (f small)(s, ‘i’)
13. >>> import string
>>> str.join(“ Bennett Colman and Co. Ltd. ”, “TOI”)
14. >>> eval(“47.5 + 27.5”)
15. >>> str1 = ‘Hello World’
>>> print(str1.rpartition(‘e’))
>>> print(str1.rpartition(‘o’))
>>> print(str1.rpartition(‘3’))
16. def comparison(word):
if word == ‘Apple’ :
>>> print(‘Your word is Apple’)
>>> elif word < ‘Apple’ :
>>> print(‘Your word’, word, ‘, comes before Apple’)
>>> else:
>>> print(‘Your word’, word,‘,comes after Apple’)
>>> comparison(‘Banana’)
17. >>>print(‘”It isn’t true,” Vishal said.’)
>>>print(‘”It isn\’t true,” Vishal said.’)
18. >>> import string
>>> s = “deepak is very loving and caring!”
>>> str.upper(s)
19. >>> import string
>>> s = “Gariyasi Prakriti Arnav Ayushi Ishaan Avni”
>>> str.lower(s)
20. >>> import string
>>> str.split(“Krishna Ajay Monika”)
21. >>> import string
>>> s = “I am proud to be Indian”
>>> str.replace(s,‘Indian’, ‘Hindustani’)
22. >>>print( “Did you smile today ?”. split())
23. >>> print( “Mon-Tue-Wed-Thu-Fri-Sat-Sun?”. rsplit(‘-’))
24. def odd_values_string(str):
result = “”
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print(odd_values_string(‘a1b2c3d4e5f6g7h8i9’))
25. name= “John Parera”
n=name.split()
n.insert(1, “Peter”)
print(“ ”.join(n))
26. n=“cock-bear-seal-cow”
items=n.split(‘-’)
items.sort()
print(‘-’.join(items))
27. greet=“never speak ill”
if not greet.istitle():
print(greet.title())
28. print(“Thank You #1 ”.swapcase())
29. greet=“Never Criticise”
if not greet.islower():
print(greet.casefold())
else:
print(“Already in lowercase”)
30. num = ‘$100’
print(num.zfill(6))
31. num = ‘-$100’
print(num.zfill(6))
32. num = ‘-$100.05’
print(num.zfill(4))
33. mystr = ‘Hello’
print(mystr.center(14,‘*’))Center()
34. mystr = ‘Hello World’
print(mystr.center(14,‘-’))
35. mystr = ‘-----Happy Life-----’
print(mystr.lstrip())
36. mystr = ‘ Happy Life’
print(mystr.lstrip())
37. mystr = ‘-----Blessed Life-----’
print(mystr.rstrip(‘-’))
38. str1 = ‘ Happy Life ’
str2= ‘ Happy Life ’
if (str1.strip()== str2.strip()):
print(“Same”)
else:
print(“Not same”)
39. text = ’’’Python
is an
easy language’’’
print(text.splitlines(True))
40. text = “Hello 1 2 3&”
digit=0
alpha=0
space=0
for c in text:
if c.isdigit():
digit= digit+1
elif c.isalpha():
alpha=alpha+1
elif c.isspace():
space+=1
else:
pass
print(“Digits:”, digit, “Alphabets:”,alpha, “Spaces:”,
space)
41. numstr = ‘345’
print(numstr.isdecimal(), end=’’ )
numstr = ‘10.75’
print(numstr.isdecimal(), end=’’)
alnumstr = ‘AB123’
print(alnumstr.isdecimal())
42. lang=‘Punjabi’
print(lang.isidentifier(), end=’’)
greet=‘Let Go’
print(greet.isidentifier())
43. numstr = ‘100’
print(numstr.isnumeric(), end=’’)
numstr= ‘10.4’
print(numstr.isnumeric())
44. greet=‘Hard Work!’
print(‘Index of H: ’,
greet.index(‘H’), end=’’)
print(‘Index of a: ’,
greet.index(‘a’), end=’’)
print(‘Index of d: ’,
greet.index(‘d’), end=’’)
print(‘Index of Work: ’,
greet.index(‘Work’))
45. greet=‘Hard Work!’
print(‘Index of h: ’,
greet.rindex(‘h’))
46. greet=’HaHaHa!’
print(‘R index of H: ’,
greet.rindex(‘H’))
47. mystr = ‘Python is an easy language.’
print(mystr.endswith(‘age.’))
48. str1 = ‘Hello’
print(str1.endswith(‘e’, 0, 2))
print(str1.endswith(‘o’, 0, 4))
49. mystr=‘tutorial tutorial’
print(‘Index of tutorial: ’,
mystr.rfind(‘tutorial’))
50. text = ‘Teacher’
trans = {‘T’:‘1’,‘e’:‘2’,‘a’:‘3’,‘h’:‘4’}
table = text.maketrans(trans)
translated = text.translate(table)
print(translated)

Q3.2 Select whether the pattern is matched or not matched for the following
regular expressions. Assume import re is part of the Python scripts:
1. patterns = ‘[A-Z]+[a-z]+$’
if re.search(patterns, “wOnDeR”):
print(‘Found a match!’)
else:
print(‘Not matched!’)
2. import re
patterns = ‘[A-Z]+[a-z]+$’
if re.search(patterns, “Anuradha”):
print(‘Found a match!’)
else:
print(‘Not matched!’)
3. import re
patterns = ‘xy+?’
if re.search(patterns, “xzy”):
print(‘Starts with x and has one y’)
else:
print(‘No matching’)
4. import re
patterns = ‘xy+?’
if re.search(patterns, “xz”):
print(‘Starts with x and has one y’)
else:
print(‘No matching’)
5. import re
patterns = ‘xy+?’
if re.search(patterns, “xyz”):
print(‘Starts with x and has one z’)
else:
print(‘No matching’)
6. import re
patterns = ‘ab*?’
if re.search(patterns, “abc”):
print(‘Starts with a’)
else:
print(‘Does not start with a’)
7. import re
patterns = ‘ab*?’
if re.search(patterns, “bc”):
print(‘Starts with a’)
else:
print(‘Does not start with a’)
8. import re
charRe = re.compile(r’[^a-zA-Z0-9.]’)
s=charRe.search(“BCDEFabcdef123450”)
print(not(s))
9. import re
charRe = re.compile(r’[^a-zA-Z0-9.]’)
s=charRe.search(“%12345”)
print(not(s))
10. import re
obj = re.findall(r”\w*”, “Moon in the sky.”)
print(obj)
for word in obj:
obj= re.search(r”[aeiou]”,word)
if word!=’’ and obj==None:
print(word)

Q.3.3 State True/False for the following statements:


i. Any integer or floating-point value can be converted into a string
using function str().
ii. Strings can be indexed using negative and positive numbers.
iii. String slicing using s[x:y] returns a sub-string from s[x] to s[y].
iv. String slicing using s[:i] returns a sub-string from beginning to
s[i].
v. String slicing using s[i:] returns a sub-string from s[i] till end.
vi. String slicing using s[-2:] returns characters from the second-last to
the end of the string.
vii. Strings in Python are mutable.
viii. If word is defined as a string of length 10, then word[2:] = ‘hello’ is a
valid statement in Python.
ix. If word = “String”, then ‘J’ + word[1:] is a valid statement.
x. If w = “String”, then statement w[:3] + ‘doc’ is an invalid statement.

ANSWERS

3.1
1. Concatenation of strings takes place using ‘+’ operator
‘helloworld’
2. Concatenation (using ‘+’ operator) along with repetition of strings
(using ‘*’ operator) takes place:
‘hihihiUshaUsha’
3. Each character of the string is printed on a new line:
G
u
g
u
4. Each character of the string is printed on the same line due to , in the
end of print() function:
i love my Mammy and Papa
5. String slicing takes place. The characters starting at index 3 till 5 (not
including 6) are printed on the screen:
sun
6. Concatenation of strings takes place using ‘+’ operator where first is
character at index 0 from string variable name followed by first 6
characters of string variable name:
GGuido
7. String slicing takes place. 5th Character from last of string variable
name is printed on the screen:
a
8. String slicing takes place. All characters except last 5 characters in
string variable name are printed on the screen:
Sujoy B
9. String slicing takes place. All characters in string variable name are
printed on the screen:
Sh. Ramesh Chand Goel
10. Length of the string is printed as the count of the number of
characters: ‘P’ , ‘r’ , ‘a’, ‘k’, ‘r’, ‘i’ , ‘t’, ‘i’, ‘ ’ ‘!’.
10
11. The count() function of string library counts the occurrences of the
given character in the given string. As ‘e’ occurs 4 times in given
string “Amit is elder to Sandeep”. The output is:
4
12. The find() function in string library finds the first occurrence of the
character given as argument and returns its index. The first
10
13. The join() function of string library prints the first string with
characters of second in beginning and end :
‘T Bennett Colman and Co. Ltd. O Bennett Colman and Co.
Ltd. I’
14. The arithmetic expression inside the string format is evaluated and the
result is printed on the screen:
75.0
15. (‘H’, ‘e’, ‘llo World’)
(‘Hello W’, ‘o’, ‘rld’)
(‘’, ‘’ , ‘Hello World)
16. The string will be compared based on their ASCII values:
“Your word Banana , comes after Apple”
17. An invalid syntax error will be reported by Python IDLE because
there is text written after the closing quote in first print().
For the second print(), the output will be a string where isn’t will be
printed as it is and ‘ will not be considered as a closing quote for
print(). This is due to use of ‘\’ to escape the next character as its
regular meaning and print as it is on the screen.
“It isn’t true” Vishal said.
18. The capitalize() function of string library converts the first character to
capital and rest all characters in small letters.
Deepak is very loving and caring!
19. The lower() function of string library converts all characters in small
letters.
gariyasi prakriti arnav ayushi ishaan avni
20. The split() function from string library separates the contents of the
string as separate strings and return as a list:
[‘Krishna’, ‘Ajay’, ‘Monika’]
21. The replace() function in string module replaces the given string with
another one.
‘I am proud to be Hindustani’
22. The split() function splits the given string into a list using space:
[‘Did’, ‘you’, ‘smile’, ‘today’, ‘?’]
23. The rsplit() function splits the given string into a list using character
(-):
[“Mon”,“Tue”,“Wed”,“Thu”,“Fri”,“Sat”,“Sun?”]
24. The program removes every character at even place. The output will
be:
abcdefghi
25. The split() function splits the given string into a list of 2 strings. The
string ‘Peter’ will be inserted at 2nd place in given list. The join()
function again converts the list of 3 strings into a single string.
The output will be: “John Peter Parera”
26. The split(‘-’) function creates a list by removing hyphens from the
given string i.e. [‘cock’, ‘bear’, ‘seal’, ‘cow’]. The function sort() sorts
the list alphabetically i.e. [‘bear’, ‘cock’, ‘cow’, ‘seal’]. The function
join(‘-’) again creates a list joined with hyphen ‘-’.
The output will be:“bear-cock-cow-seal”
27. Never Talk Ill
The function istitle() returns True because the given string greet is not
in title case, i.e. first upper case letter of each word followed by lower
case letters. So it prints the string in title case using title().
28. tHANK yOU#1
The function swapcase() converts uppercase letters to lowercase and
vice versa. Special symbols and digits are printed as it is.
29. never criticise
The function islower() returns True because the string is not in
lowercase. It is printed in lowercase using casefold() function.
30. 00$100
The function zfill() fills the 0s on left side to make total width equal to
the width given in function call.
31. -0$100
The function zfill() fills the 0s on left side to make total width equal to
the width given in function call. The minus sign is counted as one.
32. -0$100.05
The function zfill() fills the 0s on left side to make total width equal to
the width given in function call. The minus sign is counted as one.
Here the width is less than the width of the string. So no zero is
appended to the left.
33. ****Hello ****
The function center() returns a new string with specified length, which
is padded with a specific character. It is centered by padding on both
sides. The default character for padding is space.
34. -Hello World—
The function center() returns a new string with specified length, which
is padded with a specific character. It is centered by padding on both
sides. The default character for padding is space.
35. Happy Life-----
The function lstrip() removes the leading characters from the string.
Default characters to be striped off is space.
36. Happy Life
The function lstrip() removes the leading spaces from the string.
37. -----Blessed Life
The function rstrip() removes the characters at the end of the string.
Default characters to be striped off is space.
38. Same
The function strip() removes the spaces before and after the letters in
the string. The code compares the content of the 2 strings irrespective
of the spaces and returns True in this case.
39. [‘Python\n’, ‘is an\n’, ‘easy language’]
The function splitlines() spilts the string at the line boundaries and
returns a list of lines in the string.
40. Digits: 3 Alphabets: 5 Spaces: 3
The function isdigit() returns True if the character or string is all digits
(0-9). The function isalpha() returns True if the character or string is
all alphabets (a-z, A-Z), The function isspace() returns True if
character or string is space. The code counts the total number of digits,
alphabets and spaces.
41. True, False, False
The function isdecimal() returns True of the character or string is all
decimal, False otherwise
42. True False
The function isidentifer() returns True if the string is valid identifier in
Python. Let Go has space in between, so not a valid identifier.
43. True False
The function isnumeric() returns True if the string has all numeric
values, False otherwise.
44. Index of H=0 Index of a=1 Index of Work:5
The function index() returns the index where the character or substring
appears in the string. It returns -1 of it is not found in the string.
45. ValueError: substring not found
The function rindex() returns the index of the last occurrence of
character o substring, -1 otherwise.
46. R index of H: 4
The function rindex() returns the index of the last occurrence of
character o substring, -1 otherwise.
47. True
The function endswith() returns True if the string ends with given
substring, False otherwise.
48. True False
The function endswith(string, start_index, end_index) returns True if
the string ends with given substring by comparing with start_index to
end_index, False otherwise. String from 0 to 5 is Hello which does not
end with ‘o’.
49. Index of tutorial: 9
The function rfind() returns the index of last occurrence of given
substring in the string
50. 123c42r
The function maketrans() returns a table that includes unicode ordinal
of the keys of the dictionary trans. These are mapped to their
respective values. The translate method converts the string by
replacing keys with the corresponding values of dictionary trans.

3.2
1. Not a match!
The expression checks whether the string starts with one capital letter
followed by small case letters.
2. Found a match!
The expression checks whether the string starts with one capital letter
followed by small case letters.
3. No matching
The expression checks whether the string starts with one x followed
by one or more ys.
4. No matching
The expression checks whether the string starts with one x followed
by one or more ys.
5. Starts with x and has one y
The expression checks whether the string starts with one x followed
by one or more ys.
6. Starts with a
The expression checks whether the string starts with one a followed by
zero or more bs.
7. Does not start with a
The expression checks whether the string starts with one a followed by
zero or more bs.
8. True
The expression checks that a string only contains alphabets A-Za-z or
digits 0-9.
9. False
The expression checks that a string only contains alphabets A-Za-z or
digits 0-9. As string contains %, it returns False.
10. [‘Moon’, ‘’, ‘in’, ‘’, ‘the’, ‘’, ‘Sky’]
Sky
The expression findall() returns a list of all words in the sentence. The
code then checks each word and prints only the word without any
vowel using function search().
3.3
i. True: str(47) will store integer 47 as ‘47’.
ii. True
A positive index i+1 means ith character from beginning of the string
while a negative index –i means ith character from end of the string.
iii. False
It returns sub-string s[x] to s[y-1].
iv. False
String slicing using s[:i] returns a sub-string from beginning to s[i-1].
v. True
vi. True
vii. False: A string in Python cannot be changed.
viii. False: Strings are not mutable in Python.
ix. True
This is because it does not affect existing string ‘word’, but just
returns a new string as ‘Jtring’.
x. False
It is a valid statement because it does not affect existing string ‘w’ but just
returns a new string as ‘Strdoc’.
CHAPTER 4
Operators and Expressions
In this chapter you will be able to check how much you know about
operators in Python. Please refer to Table 2 in Appendix B

Key Points
The list of all operators in Python are given in Appendix B
Arithmetic operators in Python: ** ~ +(unary) -(unary) * / % // + -
Bitwise operators in Python are: >> << & ^ |
Relational operators in Python: <= < > >= == !=
Assignment operators in Python: = %= *= **= /= //= -= +=
Identity operators: is, is not
Membership operators: in, not in
Logical operators in Python: not, or, and.

Questions
Q.4.1 State the output of executing the following expressions in Python.
a. 27 + 8 * 2 - 6
b. 2 + 7 | 8 & 2
c. 3 - ( 5 + 4 ) * 2
d. 8 ^ 2 * 4 + 3
e. 9 * 6 - (4 | 6) + 5
f. (13 + 4) > ( 3 + 4)
g. (25 // 2 + 3.5) <= (7.5 + 20)
h. (40 and 50) or (0 or 30)
i. (40 and 50) and (0 or 20)
j. (not (200 | 120) and (30 & 20))
k. 2+3 * 5 & 7**2
l. 15| 56*4+3-20
m. 20>>2>>3
n. 10<<3>>4
o. (12+20-10) and (34 & 3)
p. 45*90-8&4|5
q. 50^2>>8+20<<3
r. (40&5+10)<=(30+60|5)
s. (60^5) == (90^70)
t. 100>>5+90<<80
u. 9*10>>1-8
v. 1 in [1,2,3,4]
w. 1 not in [2,3,1,4]
x. True is True
y. (90 and 60 | 34) != (80 or 50 & 30)
z. 90-80+70-60+50*2
Q.4.2 State whether each of the given statement is True/False:
i.Bitwise operators have higher precedence than logical operators.
ii. ^ operator is a unary operator.
iii. / and // operators give same output.
iv. Logical operator ‘and’ returns True if all its operands are not False.
v. Logical operator ‘or’ returns True if any one of its operand is True.
vi. Logical operator ‘not’ returns False if the operand is True.
vii. Membership operator ‘in’ can be used with lists only.
viii. Identity operator ‘is’ is used for testing whether the two objects
are equal or not.
ix. []==[] is True while [] is [] is False.
x. Multiplication by 2n can be performed using left shift operator
xi. Membership operator ‘not in’ returns True if the given element is
not in the give list or string, False, if it is found.
xii. Membership operator ‘in’ can be used for loop for creating a list of
numbers in the specified range.
xiii. x is y is True if and only if id(x)==id(y)
xiv. Bitwise operator left shift << multiplies the number by 2.
xv. The result of standard division / is integer.
xvi. The result of 1.1+2.2==3.3 will be True.
xvii. The result of (x<20.0) and isinstance(x,float) is True when x=10.0
xviii. 0.01 is considered as True.
xvix. ‘None’ is considered as False.
xx. If a=10 and b=20, then a and b is True.
Q.4.3 What will be the output of the following Python scripts?
4.3.1
y = x+10
4.3.2
x = ‘14’
y = x+10
4.3.3
(5/(6-5+1))
4.3.4
f1 = 20.5
product = f1 * s1
4.3.5
a=10
b=20
a,b = b,a
4.3.5
from math import sqrt
x = -100
print(x > 0 and sqrt(x))
4.3.6
from math import sqrt
x = 100
print(x > 0 and sqrt(x))
4.3.7
print(1+2**3*4)
4.3.8
i=3
j=2
print(i < j + 5 > j ** 2)
4.3.9
i=3
j=2
print(i < j + 5 > j ** 5)
4.3.10
i=4
j=2
print(j * 10 < i ** 2)
4.3.11 print(bool(0), bool(0.0))
4.3.12 print(bool (0+0j)
4.3.13 print(bool (-5))
4.3.14 print(bool(3.14))
4.3.15 print(bool (1+0j))
4.3.16 print(bool(‘’))
4.3.17 print(bool(“ ”))
4.3.18 print(bool(‘s’))
4.3.19 print(bool(‘Shiv’))
4.3.20 print(bool([1,2,3]))
4.3.21 print(bool ([]))
4.3.22 print(bool (None))
4.3.23 print(bool (‘None’))
4.3.24 x=100
y=100
print(x is y)
4.3.25 x=100
y=99
print(x is y)

ANSWERS

4.1
a. 37
The highest precedence is of *. 8*2 gives 16. Since + and – have same
precedence, these will be evaluated from left to right. 27+16 gives 43
and 43-6 gives 37. (Please see Appendix B)
b. 9
The highest precedence is of +. So 2+7 gives 9. Next precedence is of
bitwise AND &. So 8&2 gives 0 (bitwise ANDing of 1000 and 0010).
Next precedence is of |. So 9|0 gives 9 (bitwise ORing of 1001 and
0000).
c. -15
The highest precedence is of parenthesis (). So 5+4 gives 9. Next
precedence is of * operator. So we get the value 9*2=18. Finally 3-18
gives -15.
d. 3
Highest priority is of * operator. So 2*4 gives 8. Then, addition(+) of
8 and 3 is performed giving a value 11. Then XORing of 8 and 11
(8^11) gives 3 ( 1000 ^ 1011 = 0011).
e. 53
Highest precedence is of (). So 4|6 (100 | 110) gives 6 (110). Then 9*6
gives 54. As – and + have same precedence, these are evaluated from
left to right. 54-6 gives 48 and 48+5 is 53.
f. True
The relational operator > returns True if the value on its left is greater
than the value on its right. The value of the expression on its left is
(13+4) i.e. 17 which is greater than (3+4) i.e. 7, value on its right.
g. True
The relational operator <= returns True if the value on its left is less
than or equal to the value on its right. The value of the expression on
its left is (25 // 2 + 3.5) i.e. 12+3.5 = 15.5 which is less than (7.5 + 20)
i.e. 27.5, value on its right.
h. 50
In this expression, the operators used are logical ‘and’ and logical ‘or’.
Logical ‘and’ returns False if any one of the operand/expression is
False or 0. Otherwise, it returns the value of last True operand or
expression. Logical operator ‘or’ returns False if all the operands/
expressions are False. Otherwise it returns the value of the first True
operand/expression. In the given question, there are two expressions to
operator or : (40 and 50) and (0 or 30). The expression (40 and 50)
returns 50 because none of these is False and last value is 50. Since it
is the first True value, the second operand is not evaluated and the
value returned is 50.
i. 40
In this expression, the operators used are logical ‘and’ and logical ‘or’.
Logical ‘and’ returns False if any one of the operand/expression is
False or 0. Otherwise, it returns the value of last True operand or
expression. Logical operator ‘or’ returns False if all the operands/
expressions are False. Otherwise it returns the value of the first True
operand/expression. In the given question, there are two expressions to
operator and : (40 and 50) and (0 or 20). The expression (40 and 50)
returns 50 because none of these is False and last value is 50. The
expression (0 or 20) returns 20 since it is the first True value. The
operator and returns the last value evaluated i.e. 20.
j. False
In this expression, the operators used are logical ‘not’, logical ‘and’,
bitwise & and bitwise |. Logical ‘and’ returns False if any one of the
operand/expression is False or 0. Otherwise, it returns the value of last
True expression. Logical ‘not’ operator returns True if value of the
operand/expression is False and returns False if the value of the
operand/expression is True. Highest precedence is of ‘not’. So (200 |
120) will be evaluated first which gives value 248. not(248) gives
False. Since the first operand for and operator becomes False, it
simply returns False without executing the next operand/expression.
k. 17
Highest priority is of ** operator. So 7**2 gives 49. 3*5 gives 15 and
2+15 gives 17. 17 & 49 gives 17.
l. 207
Highest priority is of * operator. So 56*4 gives 224. 224+3 gives 227.
227-20 gives 207. 15|207 gives 207.
m. 0
is evaluated from left to right. 20>>2 gives 5 and 5>>3 gives 0.
n. 5
and << have same priority, so are evaluated from left to right. 10<<3
gives 80 and 80>>4 gives 5
o. 2
There are two operands for operator ‘and’. The expression (12+20-10)
is evaluated from left to right, i.e. 32-10 i.e. 22. The second operand is
34&3 gives 2. Both operands are True and operand ‘and’ returns the
last True expression.
p. 5
The operators ‘*’ and ‘-’ evaluated from left to right giving 4050-8 i.e.
4042. & and | are also evaluated from left to right. 4042&4 gives 0 and
0|5 gives 5.
q. 50
Highest precedence is of operator ‘+’. So 8+20 gives 28. Then >> and
<< are evaluated from left to right. 2>>28 gives 0 and 0<<3 gives 0.
50^0 gives 50.
r. True
The operator is <=. The two operands are evaluated and compared.
(40&5+10) is evaluated as 5+10=15 followed by 40&15 which is 8.
(30+60|5) is evaluated as 30+60 i.e. 90 followed by 90|5 which is 95.
Since 8<=95, the operator returns True.
s. False
For the equality operator ==, two expressions to be evaluated are 60^5
which is 57 and (90^70) which is 28. Since these two are not equal, so
the result is False.
t. 0
Highest precedence is of ‘+’. So 5+90 gives 95. >> and << are
evaluated from left to right. 100>>95 gives 0 and 0<<80 gives 0.
u. 9*10 gives 90 and 1-8 gives -7. So 90>>-7 gives error as shift count
cannot be negative.
So following message is shown:
Traceback (most recent call last): File “<string>”, line 1, in <module>
9*10>>1-8
ValueError: negative shift count
v. True
‘in’ operator checks whether the value is in the given list or not. Since
1 is present in the list, answer is True.
w. False
‘not in’ operator returns True if the value is not in the given list. Since
is present in the given list, so the answer is False.
x. True
‘is’ operator checks the identity of two variables. Since True is a
unique object in Python, it returns True.
y. True
The two expressions for ‘!=’ operators are (90 and 60|34) and (80 or
50 &30). 60|34 gives 62. 90 and 62 gives 62. Since 80 is True,
operator ‘or’ returns 80. Since 62 !=80, answer is True.
z. 120
50*2 gives 100. ‘+’ and ‘-’ are evaluated from left to right. 90-80
gives 10, 10+70 gives 80, 80-60 gives 20 and 20+100 gives 120.
4.2
i. False
All logical operators have precedence lower than all bitwise operators.
(refer to appendix on operator precedence)
ii. False
^ operator is binary bitwise XOR operator which performs the XOR of
two operands. It returns 1 if the bits in two operands are different and
returns 0 if bits in two operands are same.
iii. False
a/b gives the actual value of the quotient on dividing a by b while a//b
gives only integer part of the quotient on dividing a by b.
iv. False
Logical operator ‘and’ returns the value of the last operand if all the
operands are not False.
v. False
Logical operator ‘or’ returns the value of the first operand which is not
False.
vi. True
Logical operator ‘not’ is a unary operator which returns the negation
of the operand. If the value of the operand after evaluation is False, it
returns True and if it is True, it returns False.
vii. False
Membership operator ‘in’ can be used for testing whether a particular
value in present in a list, string or tuple etc.
viii. False
Identity operator ‘is’ is not used in Python to test whether the two
objects are equal. It tests whether they are identical i.e. if the two
variables refer to the same object.
Important terms: The equality operator ‘==’ is used to check
whether the values of two variables are equal or not.
ix. True
Important terms: An empty list [] is equal to anther empty list but
these are not identical objects because they are not located at same
place in memory.
x. True
Important terms: One left shift inserts a 0 in right and hence the value
gets multiplied by 2. So if a value is shifted left by n, it is multiplied
by 2n.
xi. True
xii. True.
for i in range(5): creates a list [0,1,2,3,4]
xiii. True.
xiv. False.
It multiplies by 2 raised to power n, where n is the number of bits the
number is shifted to left. For example, 3<<2 will multiply 3 by 2**2
i.e. 4. 3<<1 will multiply 3 by 2**1 i.e. 2.
xv. False.
It is float by default. 10/2 will be 5.0.
xvi. False.
The internal representation of float objects is not precise. So, it cannot
be relied on to equal exactly.
xvii. True
xviii. True.
Only False and 0 are False, rest all values are True.
xix. False.
Python object None is False, but string ‘None’ is considered as True.
xx. False.
When two non-boolean values are joined by and, last operand is the
answer. Here, the value of a and b will be 20.
4.3.1 NameError: name ‘x’ is not defined
Important term: A variable should be assigned a value before it can be
used in an arithmetic expression.
4.3.2 The ‘+’operator can be used for arithmetic addition or for string
concatenation. Here, one of the argument of binary operator ‘+’ is a string
and the other one is an integer. As first argument is a string, it is required to
perform string concatenation. But, in the absence of a string as second
argument, an error is reported:
TypeError: Can’t convert ‘int’ object to str implicitly
4.3.3 The expression evaluates from left to right and the denominator turns
out to be zero (6-(5+1)). So it becomes divide by zero which is reported as
an exception in Python:
ZeroDivisionError: division by zero
4.3.4 The values of variables a and b will be swapped. This is a good use of
tuples.
a = 20
b = 10
4.3.5 False
4.3.6 10.0
4.3.7 33 ( 1+ 8*4)
4.3.8 True
3<2+5 is True and 7>2**2 is True
4.3.9 False
3<2+5 is True and 7>2**5 is False
4.3.10 False
4*10 < 4**2 is not True
4.3.11 False 4.3.12 False 4.3.13 True 4.3.14 True
4.3.15 True
4.3.16 False
4.3.17 True
4.3.18 True
4.3.19 True
4.3.20 True
4.3.21 False
4.3.22 False
4.3.23 True
4.3.24 True
4.3.25 False
CHAPTER 5
Decision Control Statements
In this chapter you will be asked questions based on if, if-else, if-elif
statements.

Key Points
Various forms of ‘if’ statement in Python:
Simple if condition:
if condition:
if statement block
if condition: single print statement
if-else condition:
if condition:
if statement block
else:
else statement block
Short-hand if-else statement
single Print statement if condition else single print
statement
if-elif ladder
if condition1:
if statement block 1
elif condition2:
elif statement block 2
elif condition3:
elif statement block 3
…..
else:
else statement block

Questions
Q.5.1 What will be output of the following program?
x=10
if x>10:
x=x*5
y=x-10
print(x,y)
Q.5.2 What will be output of the following program?
x=10
if x>=10:
x=x*5
y=x-10
print(x,y)
Q.5.3 What will be output of the following program?
value=1000
if value<10000:
value-=50
print(value)
Q.5.4 What will be output of the following program?
x=10
if x>10:
x*=5
y=x-10
if x>20:
x*=2
y=x+10
print(x,y)
Q.5.5 What will be output of the following program?
x=10
if x>=10:
x*=5
y=x-10
if x<20:
x*=2
y=x+10
print(x,y)
Q.5.6 What will be output of the following program?
x=10
if x>=10:
x*=5
y=x-10
if x>20:
x*=2
y=x+10
print(x,y)
Q.5.7 What will be output of the following program?
v=300
if v%3==0:
print(v, ‘ is divisible by 3’)
else:
print(v, ‘ is not divisible by 3’)
Q.5.8 What will be output of the following program?
x=int(input(‘Enter an integer number: ‘))
if x>0:
print (x, ‘ is a positive number’)
elif x<0:
print(x, ‘is a negative number’)
else:
print(‘x is zero’)
Q.5.9 What will be output of the following program?
x=int(input(‘Enter a number between 1-7:’))
if x==7:
print (‘sunday’)
elif x==6:
print(‘monday’)
elif x==5:
print(‘tuesday’)
elif x==4:
print(‘wednesday’)
elif x==3:
print(‘thursday’)
elif x==2:
print(‘friday’)
elif x==1:
print(‘saturday’)
else:
print(‘invalid entry’)
Q.5.10 What will be output of the following program?
v1 = -10
if v1:
print (“1 - Got a true value”, v1)
else:
print (“1 - Got a False value”, v1)
v2 = 0
if v2:
print (“2 - Got a true value “, v2)
else:
print (“2 - Got a False value “, v2)
v3 = 1000
if v3:
print (“3 - Got a true value “, v3)
else:
print (“3 - Got a False value “, v3)
Q.5.11 What will be output of the following program?
print(“Input lengths of the triangle sides: “)
x = int(input(“x: “))
y = int(input(“y: “))
z = int(input(“z: “))
if x == y == z:
print(“Equilateral triangle”)
elif x != y != z:
print(“Scalene triangle”)
else:
print(“isosceles triangle”)
Q.5.12 What will be output of the following program?
a = float(input(“Input the length of side1: “))
b = float(input(“Input the length of side2: “))
c = float(input(“Input the length of side3: “))
if (a < (b + c)) and (b < (a + c)) and (c < (a + b)):
print(“The triangle is valid.”)
else:
print(“The triangle is not valid.”)
Q.5.13 What will be output of the following program?
x = True
y = True
z = False
if not x or y:
print (1)
elif not x or (not y and z):
print (2)
elif (not x or y) or (y and x):
print (3)
else:
print (4)
Q.5.14 What will be output of the following program?
x = True
y = False
z = True
if not x or y:
print (1)
elif not x or (not y and z):
print (2)
elif (not x or y) or (y and x):
print (3)
else:
print (4)
Q.5.15 What will be output of the following program?
x = False
y = False
z = False
if x or y:
print (1)
elif not x and (not y and z):
print (2)
elif (not x or y) or (y and x):
print (3)
else:
print (4)
Q.5.16 What will be output of the following program?
x = int(input(‘Enter an integer:’))
y = int(input(‘Enter an integer:’))
if x ^ y!=0:
print(x,’ and ‘, y, ‘ are different’)
else:
print(x,’ and ‘, y, ‘ are same’)
Q.5.17 What will be output of the following program?
x = int(input(‘Enter an integer:’))
y = int(input(‘Enter an integer:’))
if x and y:
print(‘x and y both are non-zero’)
else:
print(‘either x or y is zero’)
Q.5.18 What will be output of the following program?
x = int(input(‘Enter an integer:’))
y = int(input(‘Enter an integer:’))
if x or y:
print(‘either x or y is non- zero’)
else:
print(‘x and y both are zero’)
Q.5.19 What will be output of the following program?
x=13
if x%7==0: print(x, “ is divisible by 7”)
Q.5.20 What will be output of the following program?
x=14
if x%7==0: print(x, “is divisible by 7”)
Q.5.21 What will be output of the following program?
x=13
print(‘even’) if (x%2==0): else print(“odd”)
Q.5.22 What will be output of the following program?
x=13
print(‘even’) if (x%2==0) else print(“odd”)
Q.5.23 What will be output of the following program?
s1=input(‘Enter a string’)
print(s1.upper()) if (s1.islower()) else print(s1, ‘in
already has one uppercase’)
Q.5.24 What will be output of the following program?
s1=“One Fine Day”
print(s1.upper()) if (s1.istitle()) else print(s1, ‘already
in title case’)
Q.5.25 What will be output of the following program?1
s1=“rainin”
if s1.endswith(‘ing’):
print(“Continuous tense”)
else:
print(“not continuous tense”)
Q.5.26 What will be output of the following program?
s1=“raining”
i=s1.index(‘in’)
if i==-1:
print(“not found”)
else:
print(“found at index”,i)
Q.5.27 What will be output of the following program?
s1=“raining”
i=s1.rindex(‘in’)
if i==-1:
print(“not found”)
else:
print(“found at index”,i)
Q.5.28 What will be output of the following program?
s1=“raining”
i=s1.rindex(‘o’)
if i==-1:
print(“not found”)
else:
print(“found at index”,i)
Q.5.29 What will be output of the following program?
y=2010
if y%4==0:
if y%100==0:
if y%400==0:
print(y, ‘ is leap year’)
else:
print(y, ‘ is not a leap year’)
print(y, ‘ is leap year’)
else:
print(y, ‘ is not a leap year’)
Q.5.30 What will be output of the following program?
month_name = 5
if month_name == 1:
print(“January”)
elif month_name==2:
print(“February”)
elif month_name ==3:
print(“March”)
elif month_name ==4:
print(“April”)
elif month_name ==5:
print(“May”)
elif month_name ==6:
print(“June”)
elif month_name ==7:
print(“July”)
elif month_name ==8:
print(“August”)
elif month_name ==9:
print(“September”)
elif month_name ==10:
print(“October”)
elif month_name ==11:
print(“November”)
elif month_name ==12:
print(“December”)
else:
print(“Wrong input”)
Q5.31 State whether each of the following statement is True or False:
i. Only one condition can be given in one simple if statement.
ii. We can write only if part of if statement without else part.
iii. An if-elif ladder is used to test different values of same variable.
iv. Any type of operators can be used in if conditions.
v. All conditions in if-elif ladder should be mutually exclusive.
vi. The statement break is required to exit from each elif part.
vii. The following if statement will print True:
if not 1:
print(‘True’)
else:
print(‘False’)
viii. Consider the following if statement: x,y=4,5
if x==4:
print(‘x’)
elif y==5:
print(‘y’)
else:
print(‘nothing’)
It is a good example for using if-elif ladder.
ix. Any number of statements can be included in any block in if
statement.
x. The statements in else block are not executed if any of the condition in
if-elif ladder is True.
xi. More than one condition can be given in shorthand if statement.
xii. We can write only if part of if statement without else part in shorthand
if-else statement.
xiii. An if-elif ladder can be used without else part.
xiv. Bitwise operators cannot be used in if condition.
xv. Is the given if-elif ladder valid:
month_name = 5
if month_name == 1:
print(“1”)
elif month_name==2:
elif month_name ==3:
elif month_name ==4:
print(“2 or 3 or 4”)
else:
print(“5”)
xvi. Consider the if-else statement given. Will the last print be
always printed irrespective of value of x?
x = -10
if x < 0:
print(“The negative number “, x, “ is not valid here.”)
print(“This is always printed”)
xvii. Consider the if-else statement given. Is it a valid nested-if-else?
x = -10
if x < 0:
print(x, “is a negative number “)
else:
if x > 0:
print(x, “ is a positive number”)
else:
print(x, “ is 0”)
xviii. Consider the if-else statement given. Is it a valid if-else statement?
if x < 0:
print(x, “is a negative number “)
else x > 0:
print(x, “ is a positive number”)
else:
print(x, “ is 0”)
xix. Consider the if-else statement given. Is it valid?
x=5
if x < 0:
print(x, “is a negative number”)
elif x > 0:
print(x, “ is a positive number”)
else:
print(x, “ is 0”)
xx. Consider the if-else statement given. Is it correct to print whether the
given x is positive, negative or zero?
x=100
if x < 0:
print(x, “is a negative number”)
if x > 0:
print(x, “ is a positive number”)
else:
print(x, “ is 0”)

ANSWERS
5.1 Nothing will be printed as the condition in if statement x>10 is False
because the value of x is 10.
5.2 The value of x is 10 initially. The condition in if statement is True as
x>=10, so the statements inside if statement will be executed. The
value of x will be updated as 10*5 i.e. 50. Variable y has no value
initially. It is assigned the value 50-10 i.e. 40. The output will be
50,40.
5.3 The initial value of the variable value is 1000. The condition in if
statement is True because value<10000. Inside the if body, value is
decremented by 50 i.e. 1000-50 which gives the output as 950.
5.4 The condition in if statement is not True because value of x is 10 which
is not greater than 10. So the statements in if body are not executed.
The print statement is executed which contains an undefined variable
y. The output will be: NameError: name ‘y’ is not defined.
5.5 The condition in if statement is True as x>=10. The value of x is
updated as 10*5 i.e. 50. Variable y is assigned value 50-10 i.e. 40. The
condition in nested if statement is False because value of x is not less than
20. So the value of x as 50 and value of y as 40 is printed. The output is
50,40.
5.6 The condition in if statement is True as x>=10. The value of x is
updated as 10*5 i.e. 50. Variable y is assigned value 50-10 i.e. 40. The
condition in nested if statement is True because value of x is greater
than 20. So the value of x is updated as 50*2 i.e. 100 and value of y is
updated as x+10 i.e. 110 and printed. The output is 100,110.
5.7 The condition in if statement is True. The output will be: 300 is
divisible by 3.
5.8 The program will ask the user to input an integer number and stores it in
variable x. Suppose value entered is 34. It checks the value of x. If it is
greater than 0, it prints 34 is a positive number and exits the if
statement. If the value entered for x is -8, the condition in if statement
fails and it checks condition in elif statement which is True. So it prints
-8 is a negative number and exits the if statement. If the value entered
is neither >0 nor <0, it means it is zero. So the else part of if is
executed and x is zero is printed on screen.
5.9 The program will ask the user to enter a number between 1 and 7 and
stores in variable x. It has if-elif ladder. It prints the day of the week
according to the number entered. If x is 7, it prints Sunday and exits
the if-elif ladder. If it is other than 7 but greater than or equal to 1, it
prints corresponding day of the week and exits the if-elif ladder. If the
value of x is not between 1 and 7(both inclusive), it matches with none
of the conditions in the if-elif ladder, so the control reaches in else
block and prints Invalid entry.
5.10 There are three if-else statements in the program. Any value other than
0 is treated as True and value 0 is treated as False. The output will be:
1 - Got a true value -10
2 - Got a False value 0
3 - Got a true value 1000
5.11 The given Python program checks whether a triangle is equilateral,
isosceles or scalene. An equilateral triangle is a triangle in which all
three sides x,y,z are equal. A scalene triangle is a triangle that has three
unequal sides. An isosceles triangle is a triangle with (at least) two
equal sides.
For input: x=10, y=10, z=10
The output will be:
“Equilateral triangle”
5.12 The given Python function takes as input three sides of a triangle and
prints whether the triangle is valid or not. A triangle is valid if (a < (b
+ c)) and (b < (a + c)) and (c < (a + b)). For input:
a=20 b=30 c=10 The output will be: “The triangle is valid.”
5.13 Here x, y and z are Boolean variables with values True, True and False
respectively. First condition in if statement is True (not x or y). So the
statement in the first if is executed.
The output is: 1
5.14 Here x, y and z are Boolean variables with values True, False and True
respectively. First condition in if statement is False (not x or y). but
second condition is True (not x or (not y and z)). So the statement in
the first elif is executed.
The output is: 2
5.15 Here x, y and z are Boolean variables with values False, False and
False respectively. First condition in if statement is False (x or y).
Second condition is also False (not x and (not y and z)). Third
condition is True ((not x or y) or (y and x)). So the statement in the this
elif is executed.
The output is: 3
5.16 The program checks whether the two integer numbers are same or
different based on bitwise XOR operator (^) which returns 0 when
both are different
Enter an integer number x: 23
Enter an integer number y: 23
23 and 23 are same
Enter an integer number x: 34
Enter an integer number: 25
34 and 25 are different
5.17 The program checks whether the two numbers are non-zeroes based on
logical and operator which returns 0 in case any one of the operands is
0.
Enter an integer number x: 13
Enter an integer number y: 23
x and y both are non-zero
Enter an integer number x: 35
Enter an integer number: 0
either x or y is 0
5.18 The program checks whether the two numbers are non-zeroes based on
logical or operator which returns 0 in case both the operands are 0,
non-zero otherwise.
Enter an integer number x: 15
Enter an integer number y: 20
either x or y is non-zero
Enter an integer number x: 35
Enter an integer number: 0
x and y both are zero
5.19 Nothing will be printed as 13%7==0 is False and hence print statement
in short-hand if statement is not executed
5.20 14 is divisible by 7
This is printed as 14%7==0 is true and print statement in short-hand if
statement is executed.
5.21 SyntaxError will be printed as : is not required in short-hand is-else
statement
5.22 ‘odd’ will be printed because 13%2==0 is False, print in else will be
executed
5.23 It will print string in uppercase if none of the character is in uppercase
because string.islower() function returns true if all characters are in
lowercase.
Enter a string: Deepak
Deepak already has one uppercase
Enter a string: shivani
SHIVANI
5.24 ONE FINE DAY
string.istitle() function returns true of only first character of the string
is in uppercase and rest all in lowercase. So the string is printed in
uppercase because istitle() returns False.
5.25 Continuous tense
The function string.endswith(substring) returns true if the given string
has last substring as given as argument, False otherwise. Here it
returns true, so body of if-statement is executed.
5.26 found at index 2
The function string.index(substring) returns the index where the first
occurrence of the given substring is found in the given string, else it
returns -1.
5.27 found at index 4
The function string.rindex(substring) returns the index where the last
occurrence of the given substring is found in the given string, else it
returns -1.
5.28 not found
The function string.rindex(substring) returns the index where the last
occurrence of the given substring is found in the given string, else it
returns -1.
5.29 2010 is not a leap year
5.30 May
The elif body with value=5 is printed
5.31
i. False
There can be more than one conditions in one simple if statement but
these should be combined using logical operators forming a compound
condition. For example a>8 and b%3.
ii. True
There are situations where we need to work only when certain
condition is True and nothing if that is False. So there is no need for
else part.
iii. True
iv. True
Though the value in if statement should return either True or False, but
a value 0 is treated as False while any value other than 0 is treated as
True. So any type of operator can be used as condition in if statement.
For example, following if statement will print It is non-zero since 8+9
is a True value.
if 8+9:
print(‘It is non zero’)
v. True
This is because only one part of if statement is executed based on
certain True condition and then it exits the if statement.
vi. False
The if-elif ladder exits immediately after it executes the statements
without the use of break statement.
vii. False
1 is True and so ‘not 1’ will return False. Hence the statement in the
else part will be executed and ‘False’ will be printed.
viii. False
Since x is 4 and y is 5, so both x and y should be printed. Using these
in if-elif ladder does not serve the purpose. So in if-elif ladder
mutually exclusive values of same variables should be considered.
ix. True
x. True
Important terms: The statements in the else part are executed only of
all conditions in all if –elif statements are False.
xi. False, only one statement can be given.
xii. False, else part is mandatory
xiii. False, else part is mandatory
xiv. False, these can be used
xv. Invalid. All elif block should have statement(s)
xvi. Yes, the statement is out of if statement
xvii. True
xviii. False, elif should be used in place of first else
xix. True
xx. False, elif should be used in place of second if statement
CHAPTER 6
Loops
In this chapter you will be asked questions about for loop, while and do-
while loop in Python.

Key Points
There are three loop control statements in Python: for, while and do-while.
a. for loop
for variable1 in range(terminating_value):
for variable1 in range(initial_value, terminating_value):
for variable1 in range(initial_value, terminating_value,
update_value):
for variable1 in list:
b. while loop
var1 = initial_value
while var1 <= terminating_value:
while statement block
var1 + = update_value
c. do-while loop
var1 = initial_value
do:
do-while statement block
var1 + = update_value
while var1 <= terminating_value:

break statement is used to exit the loop in which it is present continue


statement is used to skip the loop for current iteration and continue to the
next iteration of the loop

Questions
Q.6.1 State what will be the output of the following programs?
(a) for i in range(4):
print(i)
(b) for i in range(4,7):
print(i)
(c) for i in range(14,28,4):
print(i)
(d) for i in range(24,18,-3):
print(i)
(e) sum=0
for i in range(20,10,2):
sum+=i
print(sum)
(f) sum=0
for i in range(10,20,2):
sum+=i
print(sum)
(g) sum=0
for i in range(10,20,2):
sum+=i
print(sum)
(h) i=10
for i in range(5):
print(i)
i = i+3
print(i)
(i) p=1
n=int(input(‘enter a number’))
for i in range(1,n+1):
p*=i
print(n, ‘! = ’, p)
(j) i=0
while i<=9:
if i%3==0:
print(i)
i=i+1
print(“Out of loop”)
(k) i=0
while i>=9:
if i%3==0:
print(i)
i=i+1
print(“Out of loop”)
(l) i=1
sum_e,sum_o=0,0
while i<=10:
if i%2==0:
sum_e+=i
else:
sum_o+=i
i=i+1
print(“Sum of even numbers: “, sum_e)
print(“Sum of odd numbers: “, sum_o)
(m) i=1
sum_e=0
sum_o=0
while i<=5:
n=int(input())
if n%2==0:
sum_e+=n
else:
sum_o+=n
i=i+1
print(“Sum of even numbers: ”, sum_e)
print(“Sum of odd numbers: ”, sum_o)
(n) for i in range(2):
for j in range(3):
print(i,j)
(o) i,j=0,0
while i<2:
while j<3:
print(i,j)
i+=1
j+=1
(p) for i in range(2):
sum_r=0
for j in range(3):
n = int(input(‘enter’))
sum_r+=n
print(sum_r)
(q) sum=0
for i in range(2): for
j in range(3):
n = int(input(‘enter’))
sum+=n
print(sum)
(r) z=10 w=-10
while(z<50):
if (z>0 and w<0):
print(z**2, w**3)
z = z+10
w=w+10
(s) z,w=10,-10
while(z<50):
if (z>0 or w<0):
print(z**2, w**3)
z = z+10
w=w+10
(t) for k in range(3, 21, 3):
if k%5==0:
break
print(k)
(u) for k in range(3, 21, 3):
if k%5==0:
continue
print(k)
(v) num=0
count=0
sum=0
while num>=0:
num = int(input(‘enter any number .. -1 to exit: ‘))
if num >= 0:
count = count + 1
sum = sum + num
avg = sum/count
print(‘Total numbers:’, count, ‘, Average: ’, avg)
(w) lastNumber = 6
for row in range(1, lastNumber):
for column in range(1, row + 1):
print(column, end=”)
print(“”)
(x) num = 786
count = 0
while num != 0:
num //= 10
count+= 1
print(“Total digits are: ”, count)
(y) num = 13786
sum = 0
while num != 0:
num //= 10
sum+= num%10
print(“sum of digits: ”, sum)
(z) i = 2
while(i < 20):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j) :
print (i, end=” “)
i = i + 1
Q.6.2 Give the output of the following loops with strings:
1. for char in ‘One’:
print (char)
2. b=5
while(b<9):
print(“G”)
b+=1
3. x=13
while(x==13):
print(“GuruJi”)
x=x-3
4. x = “25”
for i in x:
print(“1”)
5. x = “258s”
for i in x:
print(i,)
6. s = “Om Shanti 777”
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass # do nothing statement
print(“Letters”, l, “Digits”, d)
7. s = “Om Shanti 777”
d=l=len=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
len=len+1
print(“Letters”, l, “Digits”, d, “Length”, len)
8. i=6
while(i>0):
j=6
while(j>i):
print(“+”,end=’ ‘)
j-=1
i-=1
print()
9. for letter in “Oxford”:
if letter.islower():
print(letter, end=’’)
10. for letter in “UK”:
print(letter+’7’)
11. s = “HAPPINESS”
for i in range (2):
print(s[i], end=’’)
12. s = “WINNING”
for i in range (3,6):
print(s[i], end=’’)
13. s = “cba”
for index in range(len(s)-1, -1, -1):
print(s[index])
14. s = “GARIYASI”
rev = “”
for ch in s:
rev = ch + rev
print(rev)
15. name = input(“Enter your name: “)
while not name.isalpha():
print(“That is not a valid name.”)
name = input(“Enter your name: “)
print(name)
16. marks = input(“Enter your marks: “)
while not marks.isdigit():
print(“Marks invalid. Input again:”)
marks = input()
17. fullname = “Prakriti Garg “
for index in range(0, len(fullname)):
if fullname[index] == ‘ ‘:
space = index
break
firstname = fullname[0:space]
print(“First name is %s.” % firstname)
18. fullname = “Aradhana Goyal”
for index in range(0, len(fullname)):
if fullname[index] == ”:
space = index
break
lastname = fullname[space:]
print(“Last name is %s.” % lastname)
19.sentence = “for, while, do while”
word = “”
space = sentence.find(“ ”)
while space != -1:
word = sentence[0:space]
sentence = sentence[space+1:]
print(word, sentence)
space = sentence.find(“ ”)
20. for outer in “AB”:
for inner in “XY”:
print(outer, inner, end=’’)
21. for letter in ‘Papa’:
if letter == ‘p’:
continue
print(letter, end=’’)
22. for l in ‘Jesus’:
if l == ‘s’:
pass
print(l, end=“, ”)
23. for l in ‘Jesus’:
if l == ‘s’:
break
print(l, end=“, ”)
24. for l in ‘Jesus’:
if l == ‘s’:
continue
print(l, end=“, ”)
25. str1=“hello”
c=0
for x in str1:
if(x==‘e’ or x==‘o’):
pass
else:
c=c+1
print(c)
Q.6.3 State whether each of the following statement is True or False:
(i) We cannot nest one for loop inside another while loop.
(ii) Using a break statement causes the outermost loop to exit.
(iii) A continue statement skips the statements after it in the current
iteration of the loop.
(iv) The result of condition in for or while loop is True or False.
(v) Consider the loop below:
i=0
sum=0
while i>90:
if i%10==0:
sum=sum+i
i=i+5
print(“Sum = ”, sum)
The output will be 360.
(vi) Consider the loop below:
i=0
sum=0
while i<90:
if i%10==0:
sum=sum+i
i=i+5
print(“Sum = ”, sum)
The output will be 360.
vii. n1 = [0 for i in range(5)] creates a list n1 of numbers
from 0 to 5.
viii. Consider the code below:
l=[1,2,3,45,26]
max=0
for i in l:
if i>max:
max=i
print(max)
The output will be 45
ix. By default, the for loop iteration starts from 1.
x. The default update is increment by 1 in for loop.
xi. Consider the code below:
num = 5
while num <= 5:
if num < 5:
num = num + 1
print(num)
Is this an infinite loop?
xii. Consider the code below:
num = 5
while num <= 5:
if num < 5:
print(num)
break
Is this an infinite loop?
xiii. Consider the code below:
n = 5
answer = 1
while n > 0:
answer = answer + n
n = n + 1
print(answer)
Is this an infinite loop?
xiv. Consider the code below:
n = 5
answer = 1
while n > 0:
answer = answer + n
n = n - 1
print(answer)
Is this an infinite loop?
xv. Consider the code below:
for i in range(0,2,-1):
print(“Rama”)
Will error be thrown due to index?
xvi. Consider the code below:
for i in range(7, 0, -2):
print(i)
Will the output be 7 5 3 1 -1?
xvii. The statement written after loop executes when loop condition
becomes False. (True/False)
xviii. A while loop can be used for infinite iterations in Python.
(True/False)
xix. A while loop is used when multiple statements are to be executed
repeatedly until the given condition becomes true. (True/ False)
xx. Keyword ‘break’ can be used to bring control out of loop. (True/False)

ANSWERS

6.1
a. In the given for loop, the value of variable i will vary from 0 to 3. So
the output will be:
0
1
2
3
b. In the given for loop, the value of variable i will vary from 4 to 6. So
the output will be:
4
5
6
c. In the given for loop, the value of variable i will vary from 14 to 27
with an increment of 4. So the output will be:
14
18
22
26
d. In the given for loop, the value of variable i will vary from 24 to 19
with a decrement of 3. So the output will be:
24
21
e. In the given for loop, the value of variable i will vary from 20 to 11
with a decrement of 2. The values of i will be 20,18,16,14 and12. Each
value of i will be added to variable sum in each iteration.
So the output will be: 20+18+16+14+12 i.e. 80.
f. In the given for loop, the value of variable i will vary from 10 to 18
with an increment of 2. The values of i will be 10,12,14,16 and18.
Each value of i will be added to variable sum in each iteration.
So the output will be: 10+12+14+16+18 i.e. 70.
g. The value of sum will not be incremented as the update value is -2.
The output will be: 0
Important term: Please check the initial value and terminating value
and set update value accordingly
h. The given for loop is varying the value of i from 0 to 4. The print
statement prints the current value of i, increments it by 3 and prints it.
The value of variable i is unaffected in the loop.
The output will be:
0
3
1
4
2
5
3
6
4
7
Important term: The value of the index variable executes separately
as defined in the definition of the for loop
i. This given loop inputs an integer number and prints its factorial(!)
where n! = n*(n-1)*(n-2)*…*3*2*1. If input is 5, the output will be:
5! = 120
j. The given while loop executes till the value of i is less than or equal to
9. It is incrementing it by 1 inside the while loop. If it is divisible by 3,
it is printed. The loop exits when value of i becomes 10. Then the print
statement after the while loop is executed.
The output will be:
0
3
6
9
Out of loop
k. In the given loop, the condition in while is False. So no statement in
the loop will be executed. So the output will be: Out of loop
l. In the given loop, value of variable i varies from 1 to 10. The even
numbers are added in variable sum_e and the odd numbers are added
in variable sum_o. The output will be:
Sum of even numbers: 30
Sum of odd numbers: 25
m. The given loop inputs 5 integer values from user. The even values are
added in variable sum_e and the odd values are added in variable
sum_o. If the input is:
12
12
45
34
67
The output will be:
Sum of even numbers: 58
Sum of odd numbers: 112
n. The given for loop is a nested for loop. Variable i varies from 0 to 1
and variable j in inner loop varies from 0 to 2. So the output will be:
00
01
02
10
11
12
o. Given loop is a nested while loop. Variable i varies from 0 to 1 and
variable j in inner loop varies from 0 to 2. So the output will be:
0 0
0 1
0 2
1 0
1 1
1 2
p. The given nested for loop input values in a 2D matrix with 2 rows and
columns. It stores the sum of elements in each row in variable sum_r.
For the following matrix:
124
456
The output will be:
7
15
Important term: A 2 Dimensional matrix is stored row-wise in the
memory.
q. The given nested for loop reads elements of a 2D matrix of order 2X3.
The sum of all elements in the matrix is stored in variable sum. For the
following matrix:
1 2 3
4 5 6
The output will be: 21
r. In the given while loop, variables z and w are initialized to 10 and -10
respectively. Condition in if statement is True only once. The output
will be:
100 -1000
s. In the given while loop, variables z and w are initialized to 10 and -10
respectively. Condition in if statement is True 4 times. The output will
be:
100 -1000
400 0
900 1000
1600 8000
t. In the given for loop, variable k varies from 3 to 20 with an increment
of 3. If the value of k is divisible by 5, the loop exits, else the value of
k is printed.
The output will be:
3
6
9
12
u. In the given for loop, variable k varies from 3 to 20 with an increment
of 3. If the value of k is divisible by 5, the loop continues to next
iteration, else the value of k is printed.
3
6
9
12
18
The output will be:
v. Enters numbers till the user enters -1. Then the program prints the
count of numbers and the average.
w. The following pattern is printed:
1
12
123
1234
12345
x. The following pattern is printed:
5 4 3 2 1
5 4 3 2
5 4 3
5 4
5
y. Total digits are: 3
z. Sum of digits: 19
aa. Output: The program prints prime numbers between 2 to 10 each on
same line:
2357

6.2
1. String is printed with one character on each line
O
n
e
2. The loop executes for 4 times (b=5,6,7,8) and print G in newline
G
G
G
G
3. The loop executes one time when x=13, after than x is not equal to 13.
GuruJi is printed one time
GuruJi
4. The loop is executed for each character in string i.e. 2 times for “25”.
1 is printed two times on each on newline
1
1
5. The loop is executed for each character in string i.e. 4 times for
“258s”. Each character is printed on same line.
258s
6. The program counts the number of digits and letters in the given
string.
Letters 8 Digits 3
7. The program counts the number of digits, letters and total characters
i.e. length of the given string.
Letters 8 Digits 3 Length 15
8. The nested loop prints the following pattern:
+
++
+++
++++
+++++
9. The loop prints all lowercase letters in given string on the same line:
xford
10. The loop concatenates letter 7 to each character in the given string and
print on new line:
U7
K7
11. HA
12. NIN
13. The loop prints the string in reverse:
a
b
c
14. The loop stores the string in reverse in rev variable and prints:
ISAYIRAG
15. The program reads name from user till the user enters a valid
alphabetical name. Then it prints it:
Enter your name: S7
This is not a valid name.
Enter your name: abc1
This is not a valid name.
Enter your name: Lord
Lord
16. The program reads marks from user till the user enters valid marks.
Enter your marks:12.5
Marks invalid. Input again: 12
17. The program prints first name till first space in full name:
First name is Prakriti
18. The program prints last name: from space till end in full name:
Last name is Goyal
19. The program prints first word and rest as a sentence till the last space
in sentence in each iteration:
for, while, do while
while, do while
do while
20. The nested loop prints X and Y for A and B on the same line:
AX AY BX BY
21. The loop skips when letter is ‘p’: Paa
22. Pass is do nothing statement. So complete string will be printed:
J,e,s,u,s,
23. The loop breaks when letter is ‘s’: J,e,
24. The loop skips when letter is ‘s’: J,e,u,
25. The loop prints the count of letters other than ‘e’ and ‘o’: 3
6.3
i. False
It can be done.
ii. False
Using a break statement causes the innermost loop to exit.
iii. True
iv. True
v. False
This is because the condition i>90 is False. So no statement inside the
while loop is executed.
Sum = 0
vi. True
This is because the condition i<90 is True. So the values of i which are
divisible by 10 will be added to sum.
Sum = 10+20+30+40+50+60+70+80 = 360
vii. False
It creates a list n1 of 5 0’s i.e. [0,0,0,0,0].
viii. True
for loop assigns the largest value to variable max.
ix. False
By default, iteration in for loop starts from 0.
x. True
xi. Yes. 5 is printed infinite number of times because num is always 5.
xii. Yes. The value of num is 5 always. Nothing is printed.
xiii. Yes. The value of n is always greater than 0. It is incremented in each
iteration.
xiv. No. The value of n is decremented in the loop and result is 16
(1+5+4+3+2+1)
xv. No. The loop prints ‘Paa’. It skips only small ‘p’, not ‘P’.
xvi. True
xvii. True
xviii. True
xix. True
xx. True
CHAPTER 7
User-defined Functions
In this chapter you will be able to check how much you know about
defining new functions in Python.

Key Points
In Python, a user-defined function is defined as:
def function_name(arg1, arg2…):
Function-body
The function name should not be a keyword in Python, it can contain
numbers and underscore but should not contain space and it should start
with small letter. Any number of arguments can be passed to a function
specified as arg1, arg2,…These are called formal arguments since these are
only the placeholders for the values for which the function will actually be
executed. When the function is called, the values passed are the actual
arguments.
Default values can be use when the user can be allowed to skip the
arguments to be passed.
Variable number of arguments can be passed to a function by indicating it
with a *.
A variable-length argument list can be specified using **kwargs in
functions.
A recursive function is the one which calls itself from the same function
with different argument. The terminating condition is used to control the
number of iterations in a recursive function.
lambda [arguments] : expression
Anonymous functions can be defined using lambda keyword. It is meant
for on time use.
global variables: Variables defined outside a function block and
accessible to any functions after its declaration in the program.
globals() – built-in function to return a dictionary object of all global
variables and their corresponding values.
local variables Variables defined inside a function block.
NameError exception is thrown when variables are accessed outside the
scope.
Variables when passed with name as passed by reference in Python. Th
function id() can be used to verify the object.
A generator() is a function which returns an iterator object with a sequence
of values.

Questions
Q.7.1 State what will be the output/error in the following commands?
a. def welcome()
print(‘Welcome to Programming in Python!’)
b. def main():
print ‘Error finding in Python!’
c. def prn:
print(‘Syntax Error in Python!’)
d. def main():
print(‘Corrections for Errors in Python!)
e. def prnline():
print(“Be a Pythonist!’)
f. def indent():
print(“Sarah Beth is a swimming champion! “)
g. def Pyn():
print(“Be Positive! “)
h. def 1Pyn():
print(“Be Simple! “)
i. def break():
print(“Simple is better than complex! “)
j. def pep8(x y):
print(“Beautiful is better than ugly! “)
k. (lambda x): x+x
l. print(lambda x: x*x 10)
m. print(lambda x: x*x (10))
n. print((lambda x: x+x) (10))
o. print((lambda x,y: x+y) (10,2))
p. list1 = [11,12,3,40,5]
filter(lambda x: x%2==0, list1)
q. list1 = [10,20,30,4]
print(filter(lambda x: x%2==0, list1))
r. list1 = [1,2,3,4,5]
l=list(filter(lambda x: x%2==0, list1))
print(l)
s. import math
list1 = [2,3,7]
cubed = map(lambda x: pow(x,3), list1)
print(cubed)
t. import math
list1 = [2,3,7]
cubed = map(lambda x: pow(x,3), list1)
print(cubed)

Q.7.2 State the task/function performed by each of the following


functions in Python:
1. def f1(a,b,c):
return (a+b+c)
f1(20,b 40,60)
2. def f2(x,y,z):
return (x+y+z)//3
f2(20,41,60)
3. def f3(m,n):
if m>=n:
print(m)
else:
print(n)
f3(40,10)
4. def f4(n):
for i in range(1,n+1):
print(i)
f4(5)
5. def f5(a,b):
while b:
a,b = b, a%b
print (a)
f5(300,500)
6. def f6(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
print(f6(6))
7. def f7():
for v in range(8):
if v % 3 == 0 and v % 5 == 0:
print(“PythonPy”)
continue
elif v % 3 == 0:
print(“Python3”)
continue
elif v % 5 == 0:
print(“Python5”)
continue
print(v)
f7()
8. def f8(n): m = n
sum = 0
while m!=0:
x = m%10
sum = sum + x**3
m = m//10
if sum == n:
print(n, “ is an Armstrong number”)
else:
print(n, “ is not an Armstrong number”)
f8(153)
f8(125)
9. def f9(n,x):
i=2
j=2
t=1
sum = 0
while t<=n:
sum = sum + x**i * (-1)**j
a = i+2
b = j+1
t = t+1
print(sum)
f9(3,2)
10. def f10(n):
a=1
while i<=10:
print(i , “*”, n, “=”, n*i)
i=i+1
f10(5)
11. def f11(n):
if n == 2:
print(n, ‘ is a prime number’)
elif n%2 == 0:
print(n, ‘ is not a prime number’)
else:
for i in range(3, int(n/2) , 2):
if n % i == 0:
print(n, ‘is not a prime number’)
break
print(n, ‘ is a prime number’)
f11(29)
12. def f12(n):
sum = 0
while n!= 0:
k = n % 10
sum = sum + k
k = int(n / 10)
n = k
print(“Sum of digits: ”, sum)
f12(123)
13.def f13():
k = 1
sum = 0
multi = 1
print(“Enter a number: ”)
n = int(input())
print(“Enter the number of digits: ”)
nd = int(input())
print(“Reversed Number : ”)
while k <= nd:
k1 = n %10
print(k1)
sum = sum + k1
n = int(n / 10)
k = k + 1
print(“Sum of digits: ”, sum)
f13()
14.def f14( n ):
count = 0
print(‘Numbers from 1 to n not divisible by 2,3 and 5’)
for num in range(n+1):
if num%2 != 0 and num%3!=0 and num%5!=0:
print(num)
count=count+1 (no semicolon with two tabs, same as
print(num))
print('Total numbers:', count)
f14(30)
13. def f15(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(year, ‘ is a leap year’)
else:
print(year, ‘ is not a leap year’)
else:
print(year, ‘ is a leap year’)
else:
print(year, ‘ is not a leap year’)
f15(400)
f15(1981)
14. f1= lambda a : a + 10
print(f1(5))
print(f1(15))
15. f2 = lambda a, b : a * b
print(f2(5, 6))
18.f3= lambda a, b, c : a + b + c
print(f3(5, 6, 2))
19.import math
list1 = [2,3,4]
list2 = map(lambda x: pow(x,4), list1)
print(list(list2))
16. import math
list1 = [20,13,42,6]
list2 = filter(lambda x: x%3==0, list1)
print(list(list2))
17. def func(n):
return lambda a : a * n
mydoubler = func(2)
print(mydoubler(13))
22.def func(n):
return lambda a : a * n
mydoubler = func(5)
print(mydoubler(10))
18. def greet(name, msg=“Good morning!”):
print(“Hello”, name + ‘, ’ + msg)
greet(“Katrina”)
greet(“Bhawna”, “How are you?”)
19. def greet(name, msg= “ How do you do?”):
print(“Hello”, name + ‘, ’ + msg)
greet(name = “Obama”,msg = “How do you do?”)
greet(msg = “How do you do?”,name = “ModiJi”)
greet(“Bill”, msg = “How do you do?”)
20. def student(firstname, lastname =‘Garg’, year =‘First’):
print(firstname, lastname, ‘studies in’, year, ‘year’)
student(‘Sujay’)
21. def student(firstname, lastname =‘Garg’, year =‘First’):
print(firstname, lastname, ‘studies in’, year, ‘year’)
student(‘Bhavica’, ‘Bansal’)
22. def student(firstname, lastname =‘Garg’, year =‘First’):
print(firstname, lastname, ‘studies in’, year, ‘year’)
student(‘Monika’, ‘Goyal’, ‘Second’)
23. def power(integer1, integer2=3):
result = 1
for i in range(integer2):
result = result * integer1
return result
print(power(3))
print(power(3,2))
29.def counter(name, to_find=“an”):
c = name.count(to_find)
print(“{} has {} {}”.format(name, c, to_find))
counter(“Shivani”)
counter(“Mississippi”)
30.def counter(name, to_find=“an”):
c = name.count(to_find)
print(“{} has {} {}”.format(name, c, to_find))
counter(“Mississippi”,“is”)
24. def myFun(x):
print(“Value received:”, x, “id:”, id(x))
x = 13
print(“Value passed:”, x, “id:”, id(x))
myFun(x)
25. def myFun1(*argv):
for arg in argv:
print (arg)
def myFun2(**kwargs):
for key, value in kwargs.items():
print (“% s == % s” %(key, value))
print(“Result of * args: ”)
myFun1(‘Welcome’, ‘to’, ‘PythonandC’)
print(“\nResult of **kwargs”)
myFun2(first =‘Python’, mid =‘and’, last =‘C’)
26. def kungfu(*args):
fighters = []
for names in args:
fighters.append(names)
return fighters
print(kungfu(‘Po’,‘Shifu’,‘Oogway’))
27. t=50
def add(x, y):
global t
t=x+y
print (“in add() total=”,t)
add(10,20)
print (“global variable, t=”,t)
35.def append(list):
list.append(7)
return
numbers=[1,3,5]
print (“List before passing: ”, numbers)
append(numbers)
print (“List after function call: ”, numbers)
28. def add_binary(a, b):
binary_sum = bin(a+b)[2:]
return binary_sum
print(add_binary(5,4))
29. def same_initial(word1, word2):
if word1[0].lower() == word2[0].lower():
return True
else:
return False
print(same_initial(‘apple’, ‘orange’))
print(same_initial(‘apple’, ‘arrange’))
38.def in_both(wd1, wd2):
common = []
for c in wd1:
if c in wd2:
common.append(c)
return sorted(common)
print(in_both(‘online’, ‘offline’))
30. def in_both(wd1, wd2):
common = []
for c in wd1:
if c in wd2:
if c not in common:
common.append(c)
return (common)
print(in_both(‘online’, ‘offline’))
40.def in_both(list1, list2):
common = []
for c in list1:
if c in list2:
if c not in common:
common.append(c)
return (common)
print(in_both([1,2,5,5,3], [1,5,7]))

Q.7.3 State whether the given statements are True or False?


1. Names of actual and formal arguments should never be same.
2. There can be only one return statement in a function.
3. A variable used in a function can be accessed by any other function in
same program.
4. Name of the user-defined function can be same as the name of a built-
in function in some Python module not imported in current program.
5. Anonymous function created using lambda keyword is meant for one
time use only.
6. NameError is thrown when variables are accessed outside the scope.
7. Variables used outside any function block are accessible to ay function
after its first use in the program.
8. A recursive function can call itself atmost 10 times.
9. It is compulsory to name a function defined using lambda keyword.
10. Every function in Python must have one return statement.

ANSWERS

7.1
a. Whenever a function is defined using def, a colon(:) is placed after
the name of the function. So an invalid syntax will be reported in
Python IDLE here as Colon (:) is missing after welcome().
Correct statement:
def welcome() :
Important terms: A function is defined using the syntax
def function_name(arg1, arg2…):
Function-body
The function name should not be a keyword in Python, it can contain
numbers and underscore but should not contain space and it should
start with small letter.
b. The arguments to a print function are to be put inside a pair of
parentheses().So an invalid syntax will be reported in Python IDLE :
“Missing parentheses in call to ‘print’ “ here as set of parenthesis ()
are missing for print statement.
Correct statement:
print (‘Error finding in Python!’)
c. Every function name should include arguments inside a pair of
parentheses (). Without any arguments an empty parentheses should be
there to indicate that the variable name is name of a function. So an
invalid syntax will be reported in Python IDLE here as set of
parenthesis () are missing after function name prn.
Correct statement:
def prn():
d. The string to be printed using print function should be included in a
pair of either single quotation marks or double quotation marks. So an
invalid syntax will be reported in Python IDLE here as closing single
quote (’) missing in print statement.
Correct statement:
print (‘Corrections for Errors in Python!’)
e. The string to printed using print function should be included in a pair
of either single quotation marks or double quotation marks. But the
two types of quotation marks cannot be mixed together. So a syntax
error will be reported in Python IDLE : SyntaxError: “EOL while
scanning string literal” here as we cannot mix the two types of
quotation marks in print statement.
Correct statement:
print(“Be a Pythonist! “) or
print(‘Be a Pythonist!’)
f. Syntax error will be reported in Python IDLE : “expected an indented
block” here as the function body should be indented in next line by 4
spaces or a tab.
Correct statement: def indent():
print(“Sarah Beth is a swimming champion”)
Important terms: In Python, indentation is very important and
essential for every statement. All the statements in the body of the
function should be indented.
g. A function name in Python should start with a small letter or
underscore. However no syntax error will be reported.
Output: The contents of the print() will be printed on the screen. Be
Positive!
h. A function name in Python should start with a small letter or
underscore. So an invalid syntax error will be reported as a function
name cannot start with a numeric.
Correct statement: def pyn():
i. A function name in Python cannot be a keyword. ‘break’ is a keyword
which is used for breaking out of the current loop. So an invalid
syntax error will be reported as a function name cannot be a reserve
keyword. Correct statement:
def breakForFun(): or
def break1():
j. The arguments passed in a function should be separated by a comma.
So an invalid syntax will be reported as there should be a comma
between two arguments.
Correct statement: def pep8(x, y):
k. SyntaxError: closing parenthesis should not be placed before:
l. SyntaxError: Lambda expression should be in parenthesis( ). Closing
parenthesis should be placed after x*x. The argument i.e. 10 should be
enclosed in parenthesis.
m. SyntaxError: Lambda expression should be in parenthesis( ). Closing
parenthesis should be placed after x*x.
n. 20 : 10+10 is printed
o. 12: 10+2 is printed
p. Nothing is output, no error
q. <filter object at 0x7f5110045d30>: the address of filter object is
printed. The result of filter function should be converted into a list
using list() function. Please refer to chapter on Lists.
r. [2,4]: The function using lambda creates a list of even numbers from
given list of numbers
s. <map object at 0x7f5110045d30>: the address of map object is
printed. The result of map function should be converted into a list
using list() function. Please refer to chapter on Lists.
t. [8, 27, 343]: The cube of all elements in the list are printed.

7.2
1. Function f1 returns the sum of three numbers passed as arguments.
The output will be:
120
2. Function f2 returns the average of three numbers passed as arguments.
It returns the integer part of the average. The output will be:
40
3. Function f3 returns the larger of the two numbers passed as arguments.
The output will be:
40
4. Function f4 prints numbers from range 1 to n (passed as argument).
The output will be:
1
2
3
4
5
5. Function f5 finds the GCD of given two numbers. So for 300 and 500,
the output is 100.
6. Function f6 checks whether the given number is a perfect number or
not. For 6 it is True, so answer will be True.
7. For multiples of three, function f7 prints “Python3” instead of the
number and for the multiples of five the function prints “Python5”.
For numbers which are multiples of both three and five the function
prints “PythonPy”. The output will be:
1
2
Python3
4
Python5
Python3
7
8. Function f8 checks whether a number entered by the users is an
Armstrong number or not. A number is Armstrong if it is equal to the
sum of the cubes of its digits. The output will be:
153 is an Armstrong number as 153 = 13+53+33.
125 is not an Armstrong number because 125≠13+23+53.
9. Function f9 finds the sum of the series: x2-x4+x6-x8+…..upto n
terms. Here n is 3 and x is 2. So it prints the sum of the series 22-
24+26. The output will be:
-4
12
52
52
10. Function f10 prints the table of the given number(5) here. The output
will be:
1*5=5
2 * 5 = 10
3 * 5 = 15
4 * 5 = 20
5 * 5 = 25
6 * 5 = 30
7 * 5 = 35
8 * 5 = 40
9 * 5 = 45
10 * 5 = 50
11. Function f11 prints whether the given number is prime or not. A
number is prime if it is not divisible by any number other than 1 and
number itself. For 29, the output will be :
29 is a prime number
12. Function f12 prints the sum of the digits of the given number. For 6,
the output will be:
Sum of digits: 6
13. Function f13 prints the integer entered in reverse. For example, if
input is 147 and 3(for number of digits), the output will be:
Reversed Number :
7
4
1
Sum of digits: 12
14. Function f14 prints numbers from 1 to n which are not divisible by 2,3
and 5. The output will be:
Numbers from 1 to n not divisible by 2,3 and 5 1 7 11 13 17 19 23 29
Total numbers: 8
15. The function prints whether the given year is a leap year or not. The
output will be:
400 is a leap year
1981 is not a leap year
16. Function adds 10 to the value passed. The output will be:
15
25
17. Function returns multiplication of 2 arguments. The output will be:
30
18. Function returns addition of 3 arguments. The output will be:
13
19. The map function maps the given list of numbers to 4th power of each
number. The output will be: [16, 81, 256]
20. The filter function creates list2 with numbers divisible by 3 from list1.
The output will be: [42,6]
21. func() function calls lambda function to multiply number by given
number. Here it doubles the value. The output will be: 26
22. func() function calls lambda function to multiply number by given
number. Here it multiplies the value by 5. The output will be: 50
23. This function greets to the person with the provided message. If the
message is not provided, it defaults to “Good morning!”
Hello Katrina Good morning!
Hello Bhawna, How are you?
24. Hello Obama, How do you do?
Hello ModiJi, How do you do?
Hello Bill, How do you do?
25. There are 2 default arguments in function student. The default value
for second argument is ‘Garg’ and default value of third argument is
‘First’. The function is called with one argument, so default values for
second and third arguments will be used. The output will be: Sujay
Garg studies in First year
26. There are 2 default arguments in function student. The default value
for second argument is ‘Garg’ and default value of third argument is
‘First’. The function is called with two arguments, so default values
for third argument will be used. The output will be: Bhavica Bansal
studies in First year
27. There are 2 default arguments in function student. The default value
for second argument is ‘Garg’ and default value of third argument is
‘First’. The function is called with three arguments, so no default
value will be used. The output will be: Monika Goyal studies in
Second year
28. The function power() finds and returns the power of given number.
The default power retuned is 3, in case only number is passed as
argument. The output will be: 27
In second function call, power required is 2. So the output will be:
9
29. The function counter finds the substring given as default argument.
The output will be:
Shivani has 1 an
Missisippi has 0 an
30. The function counter finds the substring given as argument in function
call. The
output will be:
Missisippi has 2 is
31. When a variable is passed by name to a function, it is passed by
reference. This is indicated by the function id(). The output will be:
Value passed is 13 id: 10105440
Value received is 13 id: 10105440
32. The output will be:
Result of * args:
Welcome
To
Python
Result of * kwargs:
first==Python
last=C
mid==and
33. The function iterates over args tuple and returns fighters list. The
output will be:
[‘Po’, ‘Shifu’, “Oogway”]
34. Here t is a global variable with value 50. It is modified in function add
and its modified value is retained outside the function. The output will
be:
in add() t=30
global variable, t=30
35. The list is passed to a function and one element is appended to it.
Since it is passed by reference, the changed list is reflected after the
function. The output will be:
List before passing: [1,3,5]
List after function call: [1,3,5,7]
36. The function returns the sum of two decimal numbers in binary digits.
The output will be: 1001 (binary equivalent of 9)
37. The function tests if two words start with the same character and
returns True/False.
Case distinction is ignored. The output will be:
False
True
38. The function takes two strings as arguments and returns a list of
common characters in sorted order. The output will be:
[‘e’, ‘i’, ‘l’, ‘n’, ‘n’, ‘o’]
39. The function takes two strings, returns a list of common characters(in
the order of appearing in first and second strings), removing the
duplicate characters. The output will be:
[‘o’, ‘n’, ‘l’, ‘i’, ‘e’]
40. The function takes two lists, returns a list of common elements (in the
order of appearing in first and second lists), removing the duplicate
elements. The output will be:
[1,5]

7.3
1. False, names of actual and format arguments can be different.
2. False, any number of return statements can be included in a function
definition, but only one return will be executed based on the values in
the function.
3. False, a variable defined inside a function is local to that function only.
Hence not available to any other function in the same program.
4. True
5. True
6. True
7. True
8. False, a recursive function can be called any number of times in a
function.
9. False, anonymous function can be defined for one time use also.
10. False, it is not compulsory.
CHAPTER 8
Lists
In this chapter you will be able to check how much you know about lists in
Python.

Key Points
A list is a mutable sequence type. It contains one or more items of any data
types written in square brackets separated by commas.
Various operations on a list in Python are:
list.insert() – inserts an item at a given position in the list
list.append() – adds the given item to end of the given list
list.extend()- adds all elements to the end of the list.
list.index() – returns the index of the first occurrence of the specified
item. It returns ValueError if no item found.
list.remove() – removes the first occurrence of the specified item from
the list. It throws a ValueError when the specified item is not found.
list .pop() – returns an item form the specified index position and also
removes it from the list. By default, it removes last element from the list.
del list -
list.clear()- removes all items from the list and makes it empty.
list.copy()- returns a shallow copy of a list.
list.sort() – sorts the elements of the list in descending or ascending
order
list.reverse()- returns the elements in the list in reverse order.
list.count()- returns the number of times an element occurs in the list.
Operator + returns a list containing all elements of the first and second list
Operator * returns n number of copies of the same list.
Operator slice [ ] returns the item at the given index. The position is
counted from right in case of negative index.
Operator range slice[from_index: until index-1] returns a list of items
specified by the two index operands separated by : symbol. The range starts
from 0 if the from index is not specified. The range goes till end of the list
if index after : is omitted.

Collections module: import collections


collections.deque() - It is an object that appends and pops elements
from the last of the list.
deque1.append() – adds given element at the end of the list
deque1.appendleft() – adds given element in the beginning of the list
deque1.pop() – removes the last element in the list
deque1.popleft() – removes the first element from the list

Questions
8.1 What will be the output of the following commands?
>>> mywords = [‘Krishna’, ‘Rameshwar Dass’, ‘Usha’, ‘Ramesh’]
>>> for w in mywords:
print(w,)
8.2 What will be the output of the following commands?
>>> goodwords = [‘positive thinking’, ‘faith’,’hard work’]
>>> print(len(goodwords))
8.3 What will be the output of the following commands?
>>> success=[‘Hard work’,’Patience’,’Hope’,’Dreaming Big’]
>>> list(enumerate(success))
8.4 What will be the output of the following commands?
>>> good_luck = [‘Destiny’, ‘Opportunities’, ‘Devotion’]
>>> list(enumerate(good_luck, start = 1))
8.5 What will be the output of the following commands?
>>> x = [1,2,3]
>>> x = x + [9,10]
>>> x
8.6 What will be the output of the following commands?
>>> list1 = [5,50,’Five Hundred’]
>>> list2 = list(list1)
>>> list2
8.7 Consider the final list list2 in Q.6.6, what will be the output of the
following commands?
>>> list2[2:3] = [500, 5000]
>>> list2
8.8 What will be the output of the following commands?
>>> week = [‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘feb’, ‘thu’, ‘fri’,
‘sat’]
>>> week[4:5] = []
>>> week
8.9 Consider the final list week in Q. 8.8, what will be the output of the
following commands?
>>> week[5] = []
>>> week
8.10 What will be the output of the following commands?
>>> hobbies = [‘Painting’, ‘Creative Writing’, ‘Reading’]
>>> hobbies[:] = []
>>> hobbies
8.11 What will be the output of the following commands?
>>>list1= [10,20,30,4,4]
>>>print(list1.count(4))
8.12 What will be the output of the following commands?
>>>list1 = []
>>>if not list1:
print(“List is empty”)
8.13 What will be the output of the following commands?
>>> list1 = [14,19, 20, 21]
>>> list1.remove(19)
>>> list1
8.14 What will be the output of the following commands?
>>> list1=[22,33]
>>> list2= [11,22,13]
>>> print(list1<list2)
8.15 What will be the output of the following commands?
>>> m = [[x, y] for x in range(0, 3) for y in range(0, 4)]
>>>print(m)
8.16 What will be the output of the following commands?
>>> list1=[10,20]
>>> n= 30
>>> list1.insert(1,n)
>>> list1
8.17 What will be the output of the following commands?
>>> num=[10,20]
>>> n= 30
>>> num.append(n)
>>> m=40
>>> num.append(m)
>>> print(num)
8.18 What will be the output of the following commands?
>>> num=[100,200]
>>> num.extend([30,40,50])
>>> num
8.19 What will be the output of the following commands?
>>> num=[1,2,3,4,5]
>>> num.pop()
>>> num
>>> num.pop(1)
>>> num
8.20 What will be the output of the following code?
cities = [‘London’, ‘Paris’, ‘New York’]
print(“Before calling clear(): ”, cities)
cities.clear()
print(“After calling clear(): ”, cities)
8.21 What will be the output of the following commands?
randomList = [‘Mumbai’, 10, (1, 12, 3)]
print(“Before calling clear(): ”, randomList)
randomList.clear()
print(“After calling clear(): ”, randomList)
8.22 What will be the output of the following commands?
cities = [‘Mumbai’, ‘London’, ‘Paris’, ‘New York’]
pos = cities.index(‘Bangkok’)
print(‘The index of Bangkok is: ’, pos)
8.23 What will be the output of the following commands?
cities = [‘Mumbai’, ‘London’, ‘Paris’, ‘New York’]
pos = cities.index(‘Paris’)
print(‘The index of Paris is: ’, pos)
8.24 What will be the output of the following commands?
cities = [‘Mumbai’, ‘London’, ‘Paris’, ‘New York’]
print(cities[5])
8.25 What will be the output of the following commands?
cities = [‘Mumbai’, ‘London’, ‘Paris’, ‘New York’]
cities.remove(‘paris’)
print(cities)
8.26 What will be the output of the following commands?
nums = [1, 5, 3, 4, 2, 10, 7, 9]
nums.sort()
print(‘List in Ascending Order: ’, nums)
8.27 What will be the output of the following commands?
nums = [11, 50, 13, 4, 12, 10]
nums.sort(reverse= true)
print(‘List in descending Order: ’, nums)
8.28 What will be the output of the following commands?
cities = [‘Mumbai’, ‘Delhi’, ‘Pune’, ‘Noida’]
cities.sort(key=len)
print(‘List in Ascending Order of the length: ’, cities)
8.29 What will be the output of the following commands?
cities = ['Mumbai', 'Delhi', 'Pune', 'Noida']
cities.sort(key=len, reverse=True)
print('List in Descending Order of the length: ', cities)
8.30 What will be the output of the following commands?
nums = [10, 21, 43, 13, 52]
nums.reverse())
print(“Reversed List: ”, nums)
8.31 What will be the output of the following commands?
nums = [‘a’, ‘2’, ‘c’, ‘b’]
rev_nums = nums[::-1]
print(“Reversed List: ”, rev_nums)
8.32 What will be the output of the following commands? wing
commands?
nums = [‘a’, 20, ‘c’, ‘b’]
new_nums = nums.copy()
print(new_nums)
8.33 What will be the output of the following commands?
nums = [‘a’, 20, ‘c’, ‘b’, ‘a’, ‘a’]
print(nums.count())
8.34 What will be the output of the following commands?
cities = [‘Mumbai’, ‘Delhi’, ‘Pune’, ‘Noida’]
cities.insert(10, ‘Patiala’)
print(cities)
8.35 What will be the output of the following commands?
>>> pow2 = [2 ** x for x in range(10) if x %2 ==0]
>>> print(pow2)
8.36 What will be the output of the following code?
nums1 = [1, 2, 3]
nums2 = [4, 5]
nums=[(x,y) for x in nums1 for y in nums2]
print(nums)
8.37 What will be the output of the following code?
nums = [x for x in range(21) if x%2==0 if x%5==0]
print(nums)
8.38 What will be the output of the following code?
nums = [x for x in range(13) if x%2==0 if x%3==0]
print(nums)
8.39 What will be the output of the following code?
odd_even_list = [“Even” if i%2==0 else “Odd” for i in
range(7)]
print(odd_even_list)
odd_even_list = [str(i) + ‘=Even’ if i%2==0 else str(i) +
“=Odd” for i in range(7)]
print(odd_even_list)
8.40 What will be the output of the following code?
matrix=[[1, 2, 3], [4, 5], [7, 8]]
flatList=[num for row in matrix for num in row]
print(flatList)
8.41 What will be the output of the following code?
names = [‘Sarah’, ‘Ishaan’, ‘Vishal’, ‘Avni’]
names2 = [s for s in names if ‘a’ in s]
print(names2)
8.42 What will be the output of the following code?
names = [‘Sarah’, ‘Ishaan’, ‘Vishal’, ‘Avni’]
names2 = [s for s in names if ‘i’ in s]
print(names2)
8.43 What will be the output of the following code?
names = [‘Sarah’, ‘Ishaan’, ‘Vishal’, ‘Avni’]
names2 = [s for s in names if ‘is’ in s]
print(names2)
8.44 What will be the output of the following code?
names = [‘Sarah’, ‘ishaan’, ‘Vishal’, ‘Avni’]
names2 = [s for s in names if ‘is’ in s]
print(names2)
8.45 What will be the output of the following code?
div3_nums = []
for x in range(13):
if x%3 == 0:
div3_nums.append(x)
print(div3_nums)
8.46 What will be the output of the following code?
import collections
q=collections.deque([10,20,30,40])
q.appendleft(0)
print(q)
8.47 What will be the output of the following code?
import collections
q=collections.deque([10,20,30,40])
q.append(0)
print(q)
8.48 What will be the output of the following code?
import collections
q=collections.deque([10,20,30,40])
q.pop()
print(q)
8.49 What will be the output of the following code?
import collections
q=collections.deque([10,20,30,40])
q.popleft()
print(q)
8.50 What will be the output of the following code?
import collections
q=collections.deque([20,30,40])
q.popleft()
print(q)
Q. Select the appropriate answer for the following questions:
8.51 Which of the following method(s) can be used to add an item to the
end of a given list?
a. append( )
b. insert( )
c. extend( )
d. All of these
8.52 Which of the following method can be used to add more than one
items to a given list?
a. append( )
b. insert( )
c. extend( )
d. All of these
8.53 Which of the following method can be used to add an item at any
position in a given list?
a. append( )
b. insert( )
c. extend( )
d. All of these
8.54 Which of the following method returns the element removed from
a given position in the list?
a. remove( )
b. pop( )
c. clear( )
d. All of these
8.55 Which of the following method is used to remove all elements from
a given list?
a. remove( )
b. clear( )
c. pop( )
d. All of the above
8.56 Which item is removed from the list in case the index is not
specified in pop() method?
a. first
b. last
c. current
d. All
8.57 Which of the following statement/method is used to remove an
item from a list by giving its value?
a. pop( )
b. remove
c. clear( )
d. None of these
8.58 Which of the following statement/method is used to remove an
item from a list using index value?
a. pop( )
b. del
c. clear( )
d. None of these
8.59 What is the return type of methods sort( ), remove( ) and insert( )?
a. None
b. a list
c. an item
d. Any of these
8.60 Is list a mutable data structure in Python? State True or False.
a. True
b. False
8.61 Which of the following method can be used to sort the items in a
list in descending order?
a. append( )
b. sort( )
c. reverse( )
d. None of these
8.62 Which of the following method can be used to create a shallow
copy of a given list?
a. copy( )
b. insert( )
c. extend( )
d. All of these
8.63 Which of the following method can be used to remove first element
form a deque() ?
a. pop( )
b. remove( )
c. popleft( )
d. None of these
8.64 Which of the following method can be used to remove last element
form a deque() ?
a. pop( )
b. remove( )
c. popleft( )
d. None of these
8.65 Which of the following error is shown if no item is given in
function count() ?
a. ValueError
b. IndexError
c. NameError
d. None of these
8.66 At which of the index the given element in inserted in the list if the
index given in insert() function is more than the length of the list ?
a. Error
b. Beginning
c. End
d. None of these
8.67 Which of the following operators returns n copies of the given list?
a. +
b. *
c. copy()
d. None of these
8.68 Which of the following functions can be used to insert an element
at any index in the given deque?
a. insert()
b. extend()
c. append()
d. None of these
8.69 Which of the following functions can be used to insert an element
at last in the given deque?
a. insert()
b. extend()
c. append()
d. None of these
8.70 Which of the following functions can be used to insert an element
at the beginning of the given deque?
a. insert()
b. extend()
c. append()
d. appendleft()

ANSWERS
8.1 The for loop prints each element of the list. Since comma(,) is put in
print () function, all elements will be printed on same line:
Krishna, Rameshwar Dass, Usha, Ramesh
8.2 len() function returns the total number of elements in the given list: [3]
8.3 enumerate() function lists the elements of the list along with index
number which is 0 by default. The output is:
[(0, ‘Hard work’), (1, ‘Patience’), (2, ‘Hope’), (3, ‘Dreaming Big’)]
8.4 enumerate() function lists the elements of the list along with index
number which is 0 by default. Using the starting value with an
argument start, the index of all elements in the list can be changed:
[(1, ‘Destiny’), (2, ‘Opportunities’), (3, ‘Devotion’)]
8.5 The + operator works for lists as concatenation operator and returns a
list which is composed of first list followed by second list:
[1, 2, 3, 9, 10]
8.6 The list() function is used to create a new list be copying the contents of
the list passed as argument. Note that one list can contain any type of
data values.
The output is: [5, 50, ‘Five Hundred’]
8.7 The elements of a list are indexed starting from 0. Here the value ‘Five
Hundred’ exists at list2[2]. The command given replaces this with new
integer value 500 and also adds at the same time a new value 5000 at
index list2[3]. The output is:
[5, 50, 500, 5000]
8.8 The list elements at index 4 till 5 (not including 5) will be deleted from
the list. The rest of the elements will be moved forward in the list by
the number of elements deleted. The output is:
[‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’]
8.9 Replacing a particular element in a list deletes that from the list but
empty list [] is there to indicate the deletion. The output is:
[‘ sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, [], ‘sat’]
8.10 Using [:] in the list as an index indicates the entire list. As the
command replaces each element with a [], the entire list hobbies is
empty, [].
8.11 count() function returns the count of the given element in the given list.
As 4 appears 2 times in the list given, the output will be 2.
8.12 The list variable list1 is initialized to empty []. The if condition uses
not operator and prints “List is empty” because not list1 is True
because list1 is False.
The output will be List is empty
8.13 remove() function deletes the value 19 from given list [14,19,20,21].
The output will be:
[14,20,21]
8.14 list1<list2 returns True if all the elements of list1 are less than
elements of list2 which is not True here.
The output will be: False
8.15 It is a command to create a two dimensional list where x is varying
from 0 to 3 and y is varying from 0 to 3
The output will be the list:
[[0, 0], [0, 1], [0, 2], [0, 3], [1, 0], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2,
2], [2, 3]]
8.16 Here the program inserts number n=30 at index 1 i.e. second position
in given list [10,20].
The output will be : [10,30,20]
8.17 Here the program inserts number n=30 at the end of the given list
[10,20]. The list becomes [10,20,30]. Then m=40 is inserted at the end
of this list.
The output will be: [10,20, 30, 40]
8.18 The given list [100,200] will be extended by inserting all values at the
end of the list.
The output will be: [100,200,30,40,50]
8.19 pop() function removes and returns the last element of the given list
[1,2,3,4,5]
The output will be: 5 and the list will be [1,2,3,4].
pop(1) removes and returns the second element at index 1 in the list
[1,2,3,4].
The output will be: 2 and the list will be [1,3,4]
8.20 The list will be cleared:
Before calling clear(): [‘London’, ‘Paris’, ‘New York’]
After calling clear(): []
8.21 Before calling clear(): [‘Mumbai’, 10, (1, 12, 3)]
After calling clear(): []
8.22 ValueError: ‘Bangkok’ is not in the list
8.23 The index of Paris is : 2
8.24 IndexError: list index out of range because there are only 4 elements
in the list and index varies from 0 to 3.
8.25 ValueError: list.remove(x): x not in list because it is case-sensitive,
Paris is different from paris.
8.26 Returns the list sorted in ascending order:
List in ascending order: [1, 2, 3, 4, 5, 7, 9, 10]
8.27 returns a list sorted in descending order:
List in descending order: [50, 13, 12, 11, 10, 4]
8.28 Returns the list of strings sorted in ascending order based on length of
strings. The order of strings is preserved in case of equal length
‘List in Ascending Order of the length: [ ‘Pune’, ‘Delhi’, ‘Noida’,
‘Mumbai’]
8.29 Returns the list of strings sorted in ascending order based on length of
strings. The order of strings is preserved in case of equal length
‘List in descending Order of the length: [ ‘Mumbai’, ‘Delhi’,
‘Noida’, ‘Pune’]
8.30 Reverses the order of elements in the given list:
Reversed List is: [52, 13, 43, 21, 10]
8.31 Reverses the order of characters in the given list:
Reversed List is: [‘b’, ‘c’, ‘2’, ‘a’]
8.32 new_nums is copy of nums list: [‘a’, 20, ‘c’, ‘b’]
8.33 count() function raises an exception:
TypeError: count() takes exactly one argument (0 given)
8.34 If the index is given more than the length of the list, the element is
inserted at the end of the list: [‘Mumbai’, ‘Delhi’, ‘Pune’, ‘Noida’,
‘Patiala’]
8.35 The list comprehension will create a list of 2x where x varies from 0 to
9 and x is even.
The output will be:
[20,22,24,28] i.e. [1, 4, 16, 64, 256]
8.36 [(1, 4), (1, 5), (2, 4), (2, 5), (3, 4), (3, 5)]
8.37 Returns a list of numbers divisible by both 2 and 5: [0, 10, 20]
8.38 Returns a list of numbers divisible by both 2 and 3: [0,6,12]
8.39 [‘0=Even’, ‘1=’Odd’, ‘2=Even’, ‘3=Odd’, ‘4=Even’, ‘5=Odd’,
‘6=Even, ‘7-Odd’’]
8.40 Returns a flat list of the matrix row by row: [1,2,3,4,5,7,8]
8.41 Returns a list of strings having sub-string ‘a’: [‘Sarah’, ‘Ishaan’,
‘Vishal’]
8.42 Returns a list of strings having sub-string ‘i’: [‘Vishal’, ‘Avni’]
8.43 Returns a list of strings having sub-string ‘is’: [‘Vishal’]
8.44 Returns a list of strings having sub-string ‘is’: [‘ishaan’, ‘Vishal’]
8.45 Creates a list of numbers divisible by 3: [0,3,6,9,12]
8.46 A deque object will be created and 0 will be inserted in the beginning
of the list deque([0,10,20,30,40])
8.47 A deque object will be created and 0 will be inserted in the end of the
list deque([10,20,30,40,0])
8.48 A deque object will be created and last element will be removed from
the list deque([10,20,30])
8.49 A deque object will be created and first element will be removed from
the list deque([20,30,40])
8.50 A deque object will be created and first element will be removed from
the list deque ([30,40])
8.51 a and c
8.52 c
8.53 b
8.54 b
8.55 b
8.56 b
8.57 b
8.58 a
8.59 a
8.60 a
8.61 b
8.62 a
8.63 c
8.64 a
8.65 d
8.66 c
8.67 b
8.68 d (not possible)
8.69 c
8.70 d appendleft()
CHAPTER 9
Dictionaries
In this chapter you will be able to check how much you know about
dictionaries in Python.

Key Points
The dictionary is unordered collection that contains key:value pairs
separated by commas inside curly brackets {key1:value1, key2: value2..}.
The main operations on a dictionary are storing a value with some key and
extracting the value given the key, dict[key]= value
dict. fromkeys() – creates a new dictionary from the given iterable
(string, set, list, tuple) as keys and with specified values.
dict.items() – returns a dictionary view of object as ley-value pairs
dict.keys() – returns a dictionary view object that contains the list of
keys of the dictionary.
dict.values() – returns a dictionary view object that contains the list of
values of the dictionary.
dict.get() – returns the value of the specified key
dict.pop()- removes the key from the dictionary and returns its value. It
throws a KeyError if the key specified does not exist in the dictionary
dict.popitem()- removes and returns the a tuple of (key,value) from the
dictionary.
dict.clear()- removes all key-value pairs from the dictionary.
dict.copy() – creates a shallow copy of the dictionary
dict.len() – returns the number of key-value pairs in the dictionary
del dict – deletes the dictionary collections.OrderedDict() – creates a
dictionary object which remembers the order in which the key-value pairs
are added in the dictionary.
Questions
Q.9.1 What will be the output of the following commands?
1. >>> num = {1:‘One’, 2: ‘Two’, 3: ‘Three’}
>>> num
2. >>> prizes = {‘1st’: ‘Gold’, ‘2nd’ : ‘Silver’, ‘3rd’:
‘Bronze’} >>> list(prizes)
3. >>> levels = {1: ‘Easy’, 2 : ‘Medium’, 3: ‘Hard’}
list(levels. keys())
4. >>>auth={‘C’:‘Ritchie’,
‘Python’:‘Vassum’,‘Pascal’:‘Pascal’} >>> sorted(auth.
keys())
5. >>> a = {1:4, 2:7, 3:1}
>>> sorted(a.values())
6. >>dict([(1,‘mon’),(2,‘tues’),(3,‘wed’),(4,‘thu’),
(5,‘fri’)])
7. >>> dict(jan=1,feb=2)
8. >>> months = {1:‘jan’, 2:‘feb’, 3:‘mar’, 4:‘apr’, 5:‘may’}
>>> ‘nov’ in months
9. >>> world = {1: ‘war’, 2: ‘harmony’, 3: ‘peace’}
>>> del world[1]
>>>world
10. >>> {x: x**3 for x in (10, 20, 30)}
11. What will be the output of the following code ?
import collections
d1 = collections.OrderedDict()
d1[‘A’] = 65
d1[‘C’] = 67
d1[‘B’] = 66
d1[‘D’] = 68
for k,v in d1.items():
print (k,v)
12. roman = {‘I’:1, ‘II’:2, ‘III’:3 }
print(roman)
roman.clear()
print(roman)
13. roman = {1:‘I’, 2:‘II’, 3:‘III’}
newRoman = roman.copy()
print(newRoman)
14. roman = {1:‘I’, 2:‘II’, 3:‘III’}
newRoman = roman.copy()
del roman[‘I’]
print(roman)
15. roman = {1:‘I’, 2:‘II’, 3:‘III’}
newRoman = roman.copy()
del roman[1]
print(roman)
print(newRoman)
16. Nums = {1:‘First’, 2:‘Second’, 3:‘Third’}
N1 = Nums
del Nums[2]
print(“N1: ”, N1)
17. roman = {1:‘I’, 2:‘II’, 3:‘III’}
item=roman.pop(1)
print(roman)
print(“Popped item:”, item)
18. roman = {1:‘Gold’, 2:‘Silver’, 3:‘Bronze’}
item=roman.pop(4)
print(roman)
19. roman = {1:‘Gold’, 2:‘Silver’, 3:‘Bronze’}
item=roman.pop(4, “Invalid”)
print(“Popped item:”, item)
print(roman)
20. romanNums = {‘I’:101, ‘II’:201, ‘III’:301 }
print(romanNums.popitem())
print(romanNums.popitem())
21. romanNums = {‘I’:‘George’}
print(romanNums.popitem())
print(romanNums.popitem())
22. Nums = {‘I’:100, ‘II’:500 }
Dates= {1:‘13 Jul’, 2: ‘7 Jul’}
Nums.update(Dates)
print(Nums)
23. Nums = {‘I’:100, ‘II’:500 }
item=Nums.setdefault(‘I’)
print(item)
24. Nums = {‘I’:100, ‘II’:500 }
item=Nums.setdefault(‘V’)
print(item)
print(Nums)
25. keys = {‘Mumbai’,‘Bangalore’}
value = ‘city’
dict1 = dict.fromkeys(keys, value)
print(dict1)
26. keys = {‘Dubai’,‘Bangkok’}
dict1 = dict.fromkeys(keys)
print(dict1)
27. dict1 = {1:‘Mumbai’,2: ‘Bangalore’}
print(dict1.keys())
28. dict2={}
print(dict2.keys())
29. dict1 = {1:‘Mumbai’,2: ‘Bangalore’}
print(dict1.items())
30 romanNums = {}
dictview = romanNums.items()
print(dictview)
30. Names = {1:‘Shivani’, 2: ‘Gauri’}
value = Names.get(1)
print(value)
32.Names = {1:‘Shivani’, 2: ‘Gauri’}
value = Names.get(2)
print(value)
31. Names = {1:‘Shivani’, 2: ‘Gauri’}
value = Names.get(11)
print(value)
34.Names = {1:‘Nirmal’, 2: ‘Gauri’}
print(Names.values())
32. Names = {1:‘Nirma’, 2: ‘Surf’}
Names[3]= ‘Wheel’
print(len(Names))
33. print(any({‘1’:’’,’’:’’}))
34. print(any({False:False,’’:’’}))
35. print(any({True:False,””:””}))
36. print(all({1:2,2:’’,””:3}))
37. print(all({1:2,2:5,4:3}))
Q. Select the appropriate answer for the following questions:
1. Which of the following function can be used for removing and getting
a specific key value pair from a dictionary ?
a. del
b. pop()
c. popitem()
d. All of these
2. Which of the following function can be used for removing and getting
the value of a key from a dictionary?
a. del
b. pop()
c. popitem()
d. All of these
3. Which of the following function can be used to set one key as default
in a dictionary?
a. default()
b. intersection()
c. setdefault()
d. None of these
4. Which of the following function can be used to get the value for a
particular key for displaying in a dictionary?
a. get()
b. values()
c. items()
d. All of these
5. Which of the following function can be used for creating a dictionary
with keys having common value?
a. get()
b. keys()
c. fromkeys()
d. All of these
6. Which of the following function can be to add the content of other
dictionary into exiting one?
a. add()
b. update()
c. keys()
d. none of these
7. Which of the following can be used for creating a deep copy of the
set?
a. copy()
b. setdefault()
c. update
d. None of these
8. Which of the following can be used for creating a shallow copy of a
dictionary?
a. copy()
b. setdefault()
c. =
d. None of these
9. Which of the following function can be used for deleting all elements
in a dictionary?
a. del
b. pop()
c. clear()
d. All of these
10. Which of the following function can be used for checking whether
some of the elements of True are present in given dictionary?
a. any()
b. all()
c. unique()
d. None of these
Q.9.3 State whether the following statements are True or False:
i. {} can be used to create an empty set.
ii. All elements in a set are unordered.
iii. One set value can be assigned to another set value using = operator.
iv. The elements in a set cannot be changed.
v. del statement can be used to delete a set.
vi. Dictionaries are indexed by key which can be mutable.
vii. The keys in a dictionary should be unique.
viii. del statement can be used to delete a key:value pair in a
dictionary.
ix. Lists can be used as a key in the dictionary.
x. The function list(d.keys( )) on a dictionary d returns a list of all the
keys used in the dictionary in the sorted order of keys.
xi. The function keys() returns a list of all keys in the given dictionary.
xii. The function values() returns a tuple of (key,value) pairs for all
keys in the given dictionary.
xiii. The function items() returns a list of (key,value) pairs for all keys
in the given dictionary.
xiv. The function pop() throws an error when the dictionary is empty.
xv. The function fromkeys() creates a dictionary with a given value. In
case no value is specified, value ‘None’ is used for creating the
dictionary.
xvi. The function setdefault() returns the value of the key set as
default.
xvii. The function setdefault() throws an error in case the key specified
in not already present in the dictionary.
xviii. The function get() returns None in case there is no key specified
as argument.
xix. The function popitem() can be used to get any key-value pair of
the dictionary.
xx. The function fromkeys() places value as None if the value is not
specified for keys.

ANSWERS

9.1
1. {1: ‘One’, 2: ‘Two’, 3: ‘Three’}
Important terms: By giving a key : value pairs separated by commas
in a curly braces {}, ‘num’ is defined as a dictionary. Unlike a
sequence, the values are indexed by corresponding keys.
2. list(d) function returns the list of all keys in unsorted order in the
dictionary d .
[‘1st’, ‘2nd’, ‘3rd’] or [‘1st’, ‘3rd’, ‘2nd’]
3. list(d.keys()) function returns the list of all keys in unsorted order
in the dictionary d.
[1,2,3] or [3,1,2]
4. The function sorted(d.keys()) returns the list of all keys in the
dictionary d in the sorted order.
[‘C’, ‘Pascal’, ‘Python’]
5. The function sorted(d.values()) returns the list of all values in the
dictionary d in the sorted order.
[1, 4, 7]
6. The dict() construct is used to create an unnamed dictionary. The key
value pairs are to be given in pair of parentheses separated by a
comma.
{ 1: ‘mon’, 2: ‘tues’, 3: ‘wed’, 4: ‘thu’, 5: ‘fri’}
7. This is easy way to create an unnamed dictionary of the keys are
strings.
{‘jan’: 1, ‘feb’: 2}
8. The ‘in’ operator checks whether the value exists in the dictionary or
not. It returns True if the value exists in the dictionary and False if it
does not. Here, ‘nov’ is not present in any of the key value pairs in
dictionary ‘months’. The result is
False
9. del (d[key]) function deletes the key value pair with key value in
dictionary d:
{2: ‘harmony’, 3: ‘peace’}
10. The dictionary comprehensions are used and the keys are values of x
as 10,20 and 30. The corresponding values are cube of the keys.
{10: 1000, 20: 8000, 30: 27000}
11. The key-value pairs in the created dictionary will be displayed:
A 65
B 66
C 67
D 68
12. {‘I’:1, ‘II’:2, ‘III’:3 }
{}
The function clear() removes all elements from the dictionary.
13. {1:’I’, 2:’II’, 3:’III’}
The function copy() creates a shallow copy of the dictionary.
14. KeyError : ‘I’
The function del gives error if the key is invalid.
15. {1:’I’, 2:’II’, 3:’III’}
{ 2:’II’, 3:’III’}
The function copy() creates a shallow copy of the dictionary. So the
changes in original dictionary are not reflected in the copy.
16. N1: {1:’First’, 3:’Third’}
The operator = creates a deep copy of the dictionary. The changes in
the original dictionary are reflected in the copy as well. Here key-
value pair with value 2 is deleted from Nums and reflected in N1.
17. { 2:’II’, 3:’III’}
Popped item: I
The function pop() removes a given key and returns the value.
18. KeyError: 4
The function pop() removes a given key and returns the value. It
throws error if key in invalid.
19. Popped item: Invalid
{1:’Gold’, 2:’Silver’, 3:’Bronze’}
The function pop() removes a given key and returns the value. It
throws error if key in invalid. It prints the error message, if passed as
argument.
20. (‘II’, 201)
(‘III’, 301)
The function popitem () returns any key-value pair from the dictionary
and removes it from dictionary.
21. (‘I’:’George’)
KeyError: ‘popitem(): dictionary is empty’
The function popitem () returns any key-value pair from the dictionary
and removes it from dictionary. It throws error if popping from empty
dictionary.
22. {‘I’:100, 2: ‘7 Jul’, ‘II’:500, 1:’13 Jul’}
The function update() adds new key-value pairs from other
dictionaries.
23. 23. 100
The function setdefault() returns the value of the key set as default. F
it is not present,
None is returned and key-value pair is added to dictionary.
24. None
{‘I’:100, ‘II’:500, ‘V’:None}
The function setdefault() returns the value of the key set as default. If
it is not present,
None is returned and key-value pair is added to dictionary.
25. {‘Mumbai’: ‘city’, ‘Bangalore’: ‘city’}
The function fromkeys() creates a dictionary with a given value. Here
value is ‘city’ for all keys specified.
26. {‘Dubai’: None, ‘Bangkok’: None}
The function fromkeys() creates a dictionary with a given value. In
case no value is specified, value ‘None’ is used for creating the
dictionary.
27. dict_keys([1,2])
The function keys() returns a list of keys of the dictionary. It returns an
empty list for an empty dictionary.
28. dict_keys([])
The function keys() returns a list of keys of the dictionary. It returns an
empty list for an empty dictionary.
29. dict_items([(1:’Mumbai’),(2: ‘Bangalore’)])
The function items() returns a list of key-value pairs of the dictionary.
It returns an empty list for an empty dictionary.
30. dict_items([])
The function items() returns a list of key-value pairs of the dictionary.
It returns an empty list for an empty dictionary.
31. Shivani
The function get() returns the value of the key specified as argument.
It returns None if no such key found in the dictionary.
32. Gauri
The function get() returns the value of the key specified as argument.
It returns None if no such key found in the dictionary.
33. None
The function get() returns the value of the key specified as argument.
It returns None if no such key found in the dictionary.
34. dict_values([‘Nirmal’, ‘Gauri’])
The function dict_values() returns the list of all values in the
dictionary.
35. The function len() returns the number of key-value pairs in the
dictionary
36. True
The any() function returns True even if one key of the dictionary has
Boolean value True.
37. False
The any() function returns True even if one key of the dictionary has
Boolean value True.
38. True
The any() function returns True even if one key of the dictionary has
Boolean value True.
39. False
The all () function returns True if all keys of the dictionary has
Boolean value True.
40. True
The all () function returns True if all keys of the dictionary has
Boolean value True.

9.2
1. c popitem()
2. b pop()
3. c setdefault()
4. a get()
5. c fromkeys()
6. c update()
7. d None (=)
8. c (=)
9. c (clear())
10. a (any())

9.3
i. False
{} creates an empty dictionary. Only the function set( ) can be used
to create an empty set.
ii. True
iii. True
iv. False
The elements in a set can be changed by assignment to a new
value. For example, if there are two sets, a={1,2,3} and b= {2,3,4},
using a=a-b, a gets the value {1}.
v. True
vi. False
The keys which are used for indexing in dictionaries should be
immutable. For example, strings and numbers can be the keys in a
dictionary. Also the tuples with only immutable objects can be used
as keys in a dictionary.
vii. True
viii. True
It can be done by specifying the name of the key whose value if to
be deleted. del d[key] will delete the key:value pair from dictionary
d.
ix. False
A list is a mutable data structure. It can be modified using many list
manipulation methods and operations. So it cannot be used as a key
value in a dictionary.
x. False
The function list(d.keys( )) returns the list of all the keys used in
the dictionary in an arbitrary order. The function sorted(d.keys( ))
should be used to get the elements in the dictionary in the sorted
order.
xi. True
xii. False
Only list of values is returned
xiii. True
xiv. True
xv. True
xvi. True
xvii. False
The function setdefault() returns the value of the key set as default.
If it is not present, None is returned and key-value pair is added to
dictionary.
xviii. True
xix. True
xx. True
CHAPTER 10
Sets
In this chapter you will be able to check how much you know about sets in
Python.

Key Points
A set is a mutable collection of distinct, unordered collection of objects. A
set does not contain duplicate objects. Only one copy is held in the set even
if an object is added more than once inside the curly brackets. No indexing
or slicing operations are possible in sets.
The function set() converts a string, tuple or dictionary object into the set
object. The function set.union() returns a set with elements from both the
sets.
The function set.intersection() returns a set with elements common to both
the sets.
The function set.difference() returns a set with elements in first set but not
in second set.
The function set.symmetric_difference() returns a set with elements in both
sets, excluding the common elements.
The function set.add() adds an element to the set. It does not add the
element if it already exists in the set.
The function set.copy() returns a shallow copy of the set.
The function set.discard() removes a specific element from the set.
The function set.pop() removes and returns a random element from the set.
The function set.remove() removes a specific element from the set. It raises
an error is the specified element is not found in the set.
The function set.clear() removes all elements from the set.
The function set.issubset() returns true is the set contains every element of
the other set passed as an argument.
The function set.isdisjoint() returns true if the two sets have no element in
common.

Questions
Q.10.1 What will be the output of the following commands?
1. set_of_color = {‘red’, ‘blue’, ‘green’, ‘red’,
‘orange’}print(set_of_color)
2. set_of_dishes = {‘pasta’, ‘dosa’, ‘noodles’} print(‘poha’
in set_of_dishes)
3. breakfast = set(‘Parantha’)
print(breakfast)
4. breakfast = set(‘Parantha’)
dinner = set(‘Rice’)
print(breakfast – dinner)
5. breakfast = set(‘Parantha’)
dinner = set(‘rice’)
print(breakfast – dinner)
6. a = set(‘Happiness’)
b = set(‘Honesty’)
print(a | b)
7. a = set(‘Happiness’)
b = set(‘Honesty’)
print(a & b)
8. a = set(‘Happiness’)
b = set(‘Honesty’)
print(a ^ b)
9. a = {x for x in ‘mohanjadaro’ if x not in ‘mod’}
10. a = {1,2 , 3+4, 10*7}
b = {7,14,21}
print( a – b)
11. lang = {‘Python’, ‘C++’, ‘Java’, ‘C’}
lang.add(‘C##’)
print(lang)
12. lang = {‘Python’, ‘C++’, ‘Java’, ‘C’}
lang.add(‘C++’)
print(lang)
13. lang = {‘Python’, ‘C++’, ‘Java’, ‘C’}
lang.add(‘C++’, ‘FORTRAN’)
print(lang)
14. lang = {‘Python’, ‘C++’, ‘Java’, ‘C’}
lang1= (‘C++’, ‘FORTRAN’)
lang.add(lang1)
print(lang)
15. lang = {‘Punjabi’, ‘Hindi’, ‘Sanskrit’}
lang.clear()
print(lang)
16. lang1 = {‘Hindi’,‘Urdu’}
lang2= {‘Punjabi’}
print(“Original Set: ”, lang2)
lang2 = lang1.copy()
print(“Copied Set: ”, lang2)
17. lang1 = {‘Hindi’,‘Urdu’}
lang2= {‘Punjabi’}
lang2 = lang1.copy()
lang1.add(‘Spanish’)
print(“Copied Set: ”, lang2)
print(“Original Set: ”, lang1)
18. set1 = {‘Hindu’,‘Arab’}
set2= {‘Punjabi’}
set2 = set1
set1.add(‘Spanish’)
print(“Copied Set: ”, set2)
print(“Original Set: ”, set1)
19. nums1 = {1, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 9}
nums3 = nums1.difference(nums2)
print(“nums1 - nums2: ”, nums3)
20.nums1 = {1, 2, 3, 4, 5}
nums2 = {4, 5, 6, 7, 8, 9}
nums3 = nums2.difference(nums1)
print(“nums2 – nums1: ”, nums3)
20. set1 = {1, 2, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8, 8}
set3 = { 3, 5, 8, 9, 10}
diff = set1.difference(set2, set3)
print(diff)
21. set1 = {1,2,3,4,5}
set2 = {1,2,3}
set1.difference_update(set2)
print(“Updated set:”, set1)
22. indiancities = {‘Mumbai’,‘Chennai’,‘Haridwar’,‘New Delhi’}
otherCities = {‘Mumbai’,‘Chicago’}
indiancities.difference_update(otherCities)
print(“Updated cities: ”, indiancities)
23. indiancities = {‘Mumbai’,‘Chennai’,‘Haridwar’,‘New Delhi’}
indiancities.discard(‘Mumbai’)
24. indiancities = {‘Mumbai’,‘Chennai’,‘Haridwar’,‘New Delhi’}
otherCities = {‘Paris’,’Chennai’}
set1= indiancities.intersection(otherCities)
print(set1)
25. indiancities = {‘Mumbai’,‘Chennai’,‘Haridwar’,‘New Delhi’}
set1= indiancities.intersection()
print(set1)
26. num1 = {1, 20, 3, 14, 5 }
num2 = {1, 3, 5, 7, 9}
num3={1,5,7}
num1.intersection_update(num2,num3)
print(“Updated set: ”, num1)
27. num1 = {1, 12, 3, 14, 5 }
num2 = {1, 3, 5, 7, 90}
print(num1.isdisjoint(num2))
28. num1 = {1, 12, 13, 4, 50 }
primeNums = {7, 11, 13}
print(num1.isdisjoint(primeNums))
29. num1 = {1, 2, 3, 4, 5}
num2 = {1, 3, 5}
print(num1.issubset(num2))
30. num1 = {1, 2, 3, 4, 5 }
num2 = {1, 3, 5}
print(num2.issubset(num1))
31. num1 = {1, 2, 3, 4, 5 }
primeNums = {1, 3, 5, 7}
print(primeNums.issubset(num1))
32. cities = {‘Mumbai’,‘Chennai’,‘New Delhi’}
city = cities.pop()
print(‘Poped element 1: ’, city)
print(“Updated set: ”, cities)
33. num1={}
print(num1.pop())
34. cities = {‘Delhi’,‘Chicago’,‘New York’}
cities.remove(‘Delhi’)
print(cities)
35. cities = {‘Delhi’,‘Chicago’,‘New York’}
cities.remove(‘delhi’)
print(cities)
36. nums1 = {1,2,3,4,5}
nums2 = {4,5,6,7,8}
nums3 = nums1.symmetric_difference(nums2)
print(nums3)
37. nums = {1, 2, 3, 4, 5 }
oddNums = {1, 3, 5, 7, 9}
nums.intersection_update(oddNums)
print(nums)
38. nums1 = {1, 2, 2, 3, 4, 5}
nums2 = {4, 5, 6, 8}
nums3 = {9, 10}
distinct_nums = nums1.union(nums2, nums3)
print( distinct_nums)
39. nums = { 1, 2, 3 }
evenNums = { 2, 4, 6 }
primeNums = { 5, 7 }
nums.update(evenNums, primeNums)
print( nums)

Q.10.2 State whether the given statement is True/False?


1. The function copy() creates a deep copy of a set.
2. The changes done in main set are reflected in deep copy of the set.
3. Deep copy of a set can be created using = operator.
4. Any number of elements can be passed in function add().
5. We can use lists as arguments for adding more than one values in a set
using function add().
6. If the value given as argument in function add() is already existing in
the set, the function throws an error.
7. The function clear() can delete a set only when it is empty.
8. Only one set can be given as argument to function difference().
9. The common elements on both sets are returned in function
difference().
10. The function pop() returns last element from the set.
11. The function pop() returns the random element deleted from the set.
12. The function pop() cannot be used with an empty set.
13. The function remove() returns the set after removing the element
specified.
14. The function remove() throws an error if the element specified in not
found in the set.
15. More than one values can be deleted from the set using function
remove().
16. The function isdisjoint() returns True if all the elements in the sets are
different.
17. The function update() is used to change the contents of the given set
with more values from other sets.
18. The function union() is used to change the contents of the given set
with more values from other sets.
19. The function intersection_update() returns the elements from given set
which are common to both sets.
20. The function discard() throws an error in case value specified in not
found in the set.
Q10.3. Select the appropriate answer for the following questions:
1. Which of the following function can be used for removing a specific
element from a set without error?
a. remove()
b. pop()
c. discard()
d. All of these
2. Which of the following function can be used for removing a random
element from a set?
a. remove()
b. pop()
c. discard()
d. All of these
3. Which of the following function can be used to update the given set
with common elements between given set and any set?
a. union()
b. intersection()
c. intersection_update()
d. All of these
4. Which of the following function can be used to get common elements
between two or more sets?
a. union()
b. intersection()
c. intersection_update()
d. All of these
5. Which of the following function can be used for finding union of
elements from all sets passed as argument.
a. union()
b. intersection()
c. intersection_update()
d. All of these
6. Which of the following function can be to find whether the two sets
are different or have something in common?
a. isdisjoint()
b. issubset()
c. symmetric_difference()
d. none of these
7. Which of the following can be used for creating a deep copy of the
set?
a. copy()
b. intersection()
c. =
d. All of these
8. Which of the following can be used for creating a shallow copy of a
set?
a. copy()
b. union()
c. =
d. None of these
9. Which of the following function can be used for deleting all elements
in a set?
a. remove()
b. pop()
c. clear()
d. All of these
10. Which of the following function can be used for checking whether
some of the elements of a set are present in given set?
a. issubset()
b. issymmetric()
c. unique()
d. None of these

ANSWERS

10.1
1. The elements in a pair of curly braces indicate a set. The elements are
unordered in a set. There are total six values initialized in the set ‘set_
of_color’. The duplicate elements are removed from a set
automatically and the unordered output is:
{‘red’, ‘blue’, ‘orange’, ‘green’}
2. The ‘in’ operator is used to test membership of an element in given
set. It returns True if the element is a member of the set and returns
False if the member is not a member of the set. Since element ‘poha’
is not a member of the set ‘set_of_dishes’, output is:
False
3. A set can also be created using set() function. The expected output is
breakfast = {‘P’,‘a’,‘r’,‘a’,‘n’,‘t’,‘h’,‘a’}. Since it is a set, duplicate
elements are removed automatically and elements are unordered. The
value of breakfast is:
{‘h’,‘n’, ‘t’, ‘a’, ‘r’, ‘P’}
4. The ‘-’ operator returns the difference of the element as excluding the
elements on the set on right hand side from the set of elements on its
left hand side. Since there is nothing common in elements of
‘breakfast’ and ‘dinner’, the result is the elements of the set breakfast:
{‘h’,‘n’, ‘t’, ‘a’, ‘r’, ‘P’}
5. The ‘-’ operator returns the difference of the element as excluding the
elements on the set on right hand side from the set of elements on its
left hand side. Since there is only single element ‘r’ common in
elements of ‘breakfast’ and ‘dinner’, the result is the elements of the
set breakfast except ‘r’:
{‘a’, ‘P’, ‘t’, ‘h’, ‘n’}
6. The ‘|’ operator is used to perform the union of the two sets. It returns
the elements in two sets as its operands (set1 | set2) with duplicate
elements removed.
{‘n’, ‘y’, ‘p’, ‘a’, ‘t’, ‘H’, ‘i’, ‘e’, ‘s’, ‘o’}
7. The ‘&’ operator is used to perform the intersection of the two sets. It
returns the elements in two sets as its operands (set1 & set2 ) with
elements common in both sets.
{‘H’, ‘e’, ‘s’, ‘n’}
8. The ‘^’ operator is used to find the symmetric difference in the two
sets. It returns the elements in two sets as its operands (set1 ^ set2 )
with elements in set1 and set2 but not in both sets.
{‘a’, ‘i’, ‘p’, ‘y’, ‘t’, ‘o’}
9. List comprehensions can also be used in a set. The value of set ‘a’ is
the elements other than ‘m’, ‘o’ and ‘d’ in set {‘m’, ‘o’, ‘h’, ‘a’, ‘o’,
‘n’, ‘j’, ‘o’, ‘d’, ‘a’, ‘r’, ‘o’ }
{‘j’, ‘a’, ‘h’, ‘r’, ‘n’}
10. The elements present in set ‘a’ are returned after removing the
elements in the set ‘b’. The arithmetic expressions are first evaluated
and then compared.
{1, 2, 70}
11. {‘C##’,’Java’, ‘Python’, ‘C++’, ‘C’ }
The function add() adds the given element to the set in any order.
12. {’Java’, ‘Python’, ‘C++’, ‘C’ }
The function add() adds the given element to the set in any order.
Since ‘C++’ already exists in the set, it is not added in the set.
13. TypeError: add() takes exactly one argument (2 given)
The function add() adds the given element to the set in any order. Only
one element can be given. Tuple can be used to add more values in the
set.
{‘Python’, ‘C++’, (‘C++’, ‘FORTRAN’), ‘Java’, ‘C’}
14. The function add() adds the given element to the set in any order. Only
one element can be given. Tuple can be used to add more values in the
set.
15. set()
The function clear() removes all elements from the set and returns
empty set.
16. Original Set: {‘Punjabi’}
Copied Set: {‘Hindi’,’Urdu’}
The function copy() creates a shallow copy of the set. The previous
contents are overwritten.
17. Copied Set: {‘Hindi’,’Urdu’}
Original Set: {‘Hindi’,’Urdu’, ‘Spanish’}
The function copy() creates a shallow copy of the set. The previous
contents are overwritten. The changes in the original set are
independent of the copy.
18. Copied Set: {‘Hindu’, ‘Arab’, ‘Punjabi’}
Original Set: {‘Hindu’, ‘Arab’, ‘Punjabi’}
When a set is copied using = operator, a deep copy of the set is
created. The previous contents are overwritten. The changes in the
original set are reflected in the copy as well.
19. 19 nums1 - nums2: {1,2,3}
The function difference(*other) returns the unique elements (only one
copy in case of multiple occurrences) which are not present in one or
more sets passed as argument. Here 4,5 are present in both sets passed
as argument.
20. nums2 – nums1: {6,7,8, 9}
The function difference(*other) returns the unique elements (only one
copy in case of multiple occurrences) which are not present in one or
more sets passed as argument. Here 4,5 are present in both sets passed
as argument.
21. {1,2}
The function difference(*other) returns the unique elements (only one
copy in case of multiple occurrences) which are not present in one or
more sets passed as argument. Here 4,5 are present in set2, 3 is present
in set3.
22. {4,5}
The function difference_update() updates the set on which it is called
with the elements which are common in the set passed as argument.
Here elements 1,2,3 are common in set 1 and set 2, so removed from
set1.
23. Updated cities = {‘Chennai’,’Haridwar’,’New Delhi’}
The function difference_update() updates the set on which it is called
with the elements which are common in the set passed as argument.
Here element “Mumbai” is common in indiancities and othercities, so
removed from indiancities.
24. {‘Chennai’,’Haridwar’,’New Delhi’}
The function discard() removes the specifies element from the set. No
error is reported in case the element does not exist in the set.
25. {‘Mumbai’}
The function intersection() returns common elements in both sets. It
returns copy of the set with which the function is called in case no
argument is passed. Here, ‘Mumbai’ is common in both sets.
26. {‘Mumbai’,’Chennai’,’Haridwar’,’New Delhi’}
The function intersection() returns common elements in both sets. It
returns copy of the set with which the function is called in case no
argument is passed. Here, it returns a shallow copy of set indiancities.
27. {1,5}
The function intersection_update() returns common elements in given
set with other one or more sets passed as arguments. Here 1 and 5 are
common in all 3 sets.
28. False
The function isdisjoint() returns True if all the elements are different
in the two sets. Here 1,3 and 5 are common.
29. True
The function isdisjoint() returns True if all the elements are different
in the two sets. Here no element is common.
30. False
The function issubset() returns True if the set is subset of the set
passed as argument. Here it is not the case.
31. True
The function issubset() returns True if the set is subset of the set
passed as argument. Here num2 has elements 1,3,5 which are also in
num1.
32. False
The function issubset() returns True if the set is subset of the set
passed as argument. Here it is not the case.
33. Poped element 1: ‘Mumbai’
Updated set: {‘Chennai’,’New Delhi’}
The function pop() removes any one element randomly from the set
and returns.
34. KeyError: ‘pop from an empty set’
The function pop() removes any one element randomly from the set
and returns. It throws error when pop() is called on an empty set.
35. {‘Chicago’,’New York’}
The function remove() removes the specified element from the set. It
does not return the element removed like pop().
36. KeyError: ‘delhi’
The function remove() removes the specified element from the set. It
does not return the element removed like pop(). It throws an error in
case the element does not exist in the set.
37. {1,2,3,4,5,6,7,8}
The function symmetric_difference() returns a new set with distinct
elements from both sets.
38. {1,3,5}
The function intersection_update() returns the elements from given set
which are common to both sets.
39. {1,2,3,4,5,6,7,8,9,10}
The function union() returns all union elements from all sets passed as
argument.
40. {1,2,3,4,5,6,7}
The function update() adds the unique elements of all sets passed as
argument to given set.

Answers 10.2:
1. False
The function copy() creates a shallow copy of a set.
2. True
3. True
4. False
Only one element can be passed as argument to function add(). Tuple
can be used for adding more elements as a subset.
5. False
Lists cannot be passed as argument to function add().
6. False
Nothing will be added to the set and no error will be reported.
7. False
The function clear() deletes all elements from the set containing
elements.
8. False
More than one arguments can be given to function difference().
9. False
The function difference() returns the elements of the called set which
are not in set (s) passed as argument.
10. False
The function pop() returns any random element from the set.
11. True
12. True
13. True
14. True
15. False
Only one value can be removed from the set using function remove()
16. True
17. True
18. False
It returns a new set with elements common in all sets.
19. True
20. False
No error is thrown by function discard() . It returns the set unchanged.

Answers 10.3
1. c (discard()
2. b (pop())
3. c (intersection_update())
4. b (intersection)
5. a (union())
6. a (isdisjoint())
7. c (=)
8. a (copy())
9. c (clear())
10. a (issubset())
CHAPTER 11
Tuples
In this chapter you will be able to check how much you know about tuples
in Python.

Key Points
A tuple is an immutable collection of elements of same or different data
types. The order of the elements is preserved.
It is defined by enclosing elements in parentheses (), separated by a comma.
The function type( ) is used to check whether the given collection is a valid
tuple or not.
The function len( ) is used to print the number of elements of a tuple.
The constructor tuple() is used to convert any iterable to tuple type.
Operator ‘+’ returns a tuple containing all the elements of first and second
tuple objects.
Operator ‘*’ returns a tuple with concatenation of specified copies of the
same tuple.
Operator [] returns the item at the given index. The position is counted from
right side in case index value is negative.
Operator [:] returns the items in the range specified by 2 index operands. If
first operand is omitted, the range starts from 0. If second operand is
omitted, the range is upto end of the tuple.
Operator in returns True if the given item is in the tuple, False otherwise.
Operator not in returns True if the given item is not in the tuple, False
otherwise.
collections.namedtuple(tuple_name, field_list) – returns a tuple-like object
with field attributes.
len() gives the total length of the tuple.
max() returns item from the tuple with max value.
min() returns item from the tuple with min value.

Questions
Q.11.1 What will be the output of the following command(s)?
1. >>> data = 12,34,’Gariyasi’, ‘Prakriti’, 19, 20
2. Consider the tuple ‘data’ as defined in Q.1, what will be the output of
the following command?
>>>len(data)
3. >>> t = 1,2,‘3’
>>> x, y, z = t
>>>print(x, y, z, )
4. >>> empty = ()
>>> print(empty)
5. >>> one_value = ‘hello’
>>> len(one_value)
6. >>> one_value = ‘hello’,
>>> len(one_value)
7. >>> single_tuple = 1,2,3,4
>>> nested_tuple =single_tuple , (‘1st’, ‘2nd’, ‘3rd’,
‘4th’)
8. >>> single_tuple = 1,2,3,4
>>> nested_tuple = single_tuple , (‘1st’, ‘2nd’, ‘3rd’,
‘4th’) len(nested_tuple)
9. >>> tuple1 = 10, ‘Ten’, 100, ‘Hundred’
>>> x,y,z = tuple1
10. >>>u = ‘We’, ‘are’, ‘proud’, ‘to’, ‘be’, ‘an’, ‘Indian’
>>>u[0] = [1,2]
11. >>> item= (‘Hari’)
>>> print(type(item))
12. >>> item= (‘Harihar’, )
>>> print(type(item))
13. >>> t1= (10,20,30)
>>> for I in t1:
>>> print(I, end= ‘ ’)
14. >> names= (‘C’, ‘C++’, ‘Java’)
>>> print(names[-1])
>>> print(names[-2])
15.>> names= (‘C’, ‘C++’, ‘Java’)
>>> print(names[-4])
15. >> names= (‘C’, ‘C++’, ‘Java’)
>>>print(names[-2:])
16. >>> names= (‘C’, ‘C++’, ‘Java’)
>>>print(names[0:-2])
17. >>> names= (‘C’, ‘C++’, ‘Java’)
>>>print(names[0:-1])
18. >>> cities= (‘Mumbai’, ‘Chennai’)
>>> print(cities[:])
19. >>> cities= (‘Mumbai’, ‘Chennai’)
>>> del cities[0]
20. >>> cities= (‘Mumbai’, ‘Chennai’)
>>> del cities
21. >>> tpl = tuple({1,2,3,4,5,5,5})
>>> print(tpl)
22. >>> list1 = tuple([1,2,5,3,4,5,3,5])
>>> print(list1)
23. >>> s1 = tuple(“string”)
>>> print(s1)
24. >>> d1 = tuple({0:“string”, 1:“tuple”})
>>> print(d1)
25. >>> tpl = tuple({“One”:1,“Two”:2, “Three”:3, “Four”:4})
>>> print(tpl)
26. >>> t1 = tuple({“One”:1,“Two”:2, “Three”:3}) # converts
dictionary to tuple
>>> t2=(“Hi”, “Hello”)
>>> print(t1+t2)
27. >>> t1=tuple({1:“One”, 2:“Two”})
>>> t2=(“Hello”, “Hi”)
>>> t3=t2+t1
>>> print(t3)
28. >>> t1=tuple({1:“Gold”, 2:“Silver”})
>>> print(t1*2)
29. >>> t2=(“Hello”, (“Hi”, “Bye”))
>>> print(t2*2)
30. >>> t1=tuple({1:“Gold”, 2:“Silver”})
>>> t2=(“Hello”, (“Hi”, “Bye”))
>>> print(t1+ t2*2)
31. >>> t1=tuple({1:“Good”, 2:“Bad”})
>>> t2=(“Hello”)
>>> print((t1+ t2)*2)
32. >>> t1=tuple({1:“Great”, 2:“Stupid”})
>>> t2=(“Hi”,)
>>> print((t1+ t2)*2)
33. >>> t1=tuple(1,“Gold”, 2,“Silver”)
>>> print(1 in t1)
34. >>> t1=tuple(1,“Gold”, 2,“Silver”)
>>> print(11 in t1)
36.>>> t1=tuple(1,“Gold”, 2,“Silver”)
>>> print(13 not in t1)
35. >>> t1=tuple(1,“Gold”, 2,“Silver”)
>>> print(1 not in t1)
36. >>> t2=(“Hello”, (1,2),3,4)
>>> print(1 in t2)
37. >>> import collections
>>> person = collections.namedtuple(‘person’, [‘name’,
‘age’, ‘gender’])
>>> p1=person(‘Gauri’,’45’,’F’)
>>> print(p1[0])
38. >>> import collections
>>> person = collections.namedtuple(‘person’, [‘name’,
‘age’, ‘gender’])
>>> p1=person(‘Gauri’,’45’,’F’)
>>> print(p1.age, ‘ ’, p1.gender)

Q.11.2 State what task does the following functions perform?


1. def func(a=None, b=None):
print(“Value of a : ” + str(a))
print(“Value of b : ” + str(b))
x=7
y=13
func(x)
2. def func(a=None, b=None):
print(“Value of a : ” + str(a))
print(“Value of b : ” + str(b))
x=7
y=13
func((x,y))
3. def concat(a,b):
return tuple(str(a))+tuple(str(b))
a=10
b=20
print(concat(a,b))
4. def concat(a,b):
return tuple(str(a))*b
a=100
print(concat(a,2))
5. def find(tpl,item):
if item in tpl:
print(“Found”)
else:
print(“Not found”)
a=(1,2,13)
find((1,2,3),2)
6. def func(t1):
m=max(t1)
if m<100:
print(“Tuple has no 3 digit value”)
else:
print(“Tuple has 3 digit values”)
func((1,11,111))
7. def func(t1):
m=max(t1)
if m>100:
print(“Tuple has 3-digit values”)
elif m>10:
print(“Tuple has 2-digit values”)
else:
print(“Tuple has single-digit values”)
func((1,11,13))
8. def func(t1):
m=min(tuple(t1))
print(“Tuple has min value:”, m)
func([1,11,111])
9. def length(t1, n):
t2=t1*n
l=len(t2)
print(“Length of tuple ”, t2, “ is: ”, l)
length((‘1’,11),3)
10. def length(t1, n):
t2=t1*n
l=len(t2)
print(“Tuple {} has length: {}”, t2, l)
length((‘1’,(5,3)),2)

Q.11.3 State whether the following statements are True or False:


i. A tuple need not be parenthesized.
ii. A tuple is a sequence type data like lists.
iii. A tuple is mutable like a list.
iv. A tuple can contain mutable objects.
v. The elements of a tuple are heterogeneous while that of a list are
homogenous.
vi. An entire tuple can be deleted using del.
vii. The constructor tuple() can be used to convert only string to a tuple.
viii. A dictionary cannot be converted into a tuple.
ix. The tuple retains multiple copies of an element in the set when
converted to a tuple using constructor tuple()
x. Both the key and values are stored a tuple when a dictionary is
converted into a tuple using constructor tuple().
xi. The + operator adds the contents of all tuples in random order in
resulting tuple.
xii. The * operator creates a tuple by concatenating the content of the tuple
the n number of times specified in tuple*n.
xiii. The nested tuples are flattened in * operator.
xiv. IndexError is thrown when the index specified in [ ] operator is more
than the length of the tuple.
xv. A negative index in [ ] operator with tuple raises IndexError
exception.
xvi. The [:] operator takes default index as 0 if only value after : is
specified for a tuple.
xvii. The [:] operator takes default index as length of a tuple if only value
before : is specified for a tuple.
xviii. The [:] operator displays all the elements till the end of tuple in case
the second argument in tuple is more than the length of the tuple.
xix. We can search for only single element in a tuple.
xx. The value at any index can be changed in a tuple using assignment.

ANSWERS

11.1
1. The variable ‘data’ is defined as tuple in Python. All the values
separated by comma are packed together in the given sequence in
tuple ‘data’. The value of ‘data’ is:
(12, 34, ‘Gariyasi’, ‘Prakriti’, 19, 20)
2. The len() function returns the number of elements in the tuple:
6
3. When a tuple is packed with some values, it is called tuple packing. In
case the values are to be unpacked to different variable given in a
sequence, then it is called sequence unpacking. As tuple t has 3 values
in a sequence, so the three variables x,y,z get the values 1,2,’3’
respectively. The values of x, y and z will be printed on the same line
on the screen because there is one trailing comma in print():
1, 2, ‘3’
4. An empty tuple contains as empty set of parentheses (). Output will
be:
()
5. The variable one_value is assigned a string value ‘hello’......... Thus it
is considered as a string variable. The len() function returns the length
of the characters in the string ‘hello’:
5
6. The variable one_value is assigned a string value ‘hello’ followed by a
trailing comma(,). Thus it is considered as a tuple. The len() function
returns the number of the characters in the tuple which is only the
string ‘hello’:
1
7. Using a comma(,) operator causes nesting of two tuples. So the
contents of nested_tuple are:
((1,2,3,4), (‘1st’, ‘2nd’, ‘3rd’, ‘4th’))
8. The len() function returns the number of elements in the tuple ‘nested_
tuple’. As the elements are two tuples. So the output is: 2
9. The sequence unpacking takes place here. The values on left side of
the sequence should be the same as the values on right side. Single
‘tuple1’ is assigned 4 values while there are only 3 variables x,y and z,
following error is reported by Python IDLE:
ValueError: too many values to unpack (expected 3)
10. A tuple is used to store a sequence of any type of datatypes. But the
tuples are immutable i.e. we cannot change the values assigned to its
elements. So following error is reported by Python IDLE:
TypeError: ‘tuple’ object does not support item assignment
11. <class ‘string’>
12. <class ‘tuple’>
13. 10 20 30
All the elements of the tuple are printed on same line using a for loop.
14. Java
C++
[-1] indicates last value of the tuple. [-2] indicates second last value of
the tuple.
15. IndexError: index out of range
The negative value can be maximum upto length of a tuple
16. (‘C++’, ‘Java’)
The range is from second last element till end of the tuple
17. (‘C’)
The range is from first to -2 -1 i.e. -3 i.e. 3rd element from last.
18. (‘Mumbai’, ‘Chennai’)
[:] The range is complete tuple.
19. TypeError: ‘tuple’ object doesn’t support item deletion
Since tuple is immutable, the elements of the tuple cannot be changed
or deleted.
20. (‘C’, ‘C++’)
The range is from first to -1 -1 i.e. -2 i.e. 2nd element from last.
21. del is used to delete an entire tuple.
22. (1,2,3,4,5)
The set is converted to a tuple using constructor tuple(). Only one
instance of elements is stored due to set properties.
23. (1,2,5, 3,4,5,3,5)
The list is converted to a tuple using constructor tuple(). All duplicate
values are stored as such in tuple.
24. (‘s’, ‘t’, ‘r’, ‘i’, ‘n’, ‘g’)
The constructor tuple converts a string to a tuple.
25. (0,1)
The constructor tuple converts a dictionary to a tuple with key values
of dictionary.
26. (“One”, “Three”, “Four”, “Two”)
The constructor tuple converts a dictionary to a tuple with key values
of dictionary. The order of keys may not be in same order as specified
in dictionary.
27. (“One”, “Three”, “Two”, “Hi”, “Hello”)
The + operator concatenates second tuple at the end of the first.
28. (‘Hello’, ‘Hi’, 1,2)
The + operator concatenates second tuple at the end of the first.
29. (1,2,1,2)
The * operator concatenates the tuple n number of times.
30. (‘Hello’, (‘Hi’, ‘Bye’)), (‘Hello’, (‘Hi’, ‘Bye’))
31. (1,2, (‘Hello’, (‘Hi’, ‘Bye’)), (‘Hello’, (‘Hi’, ‘Bye’)))
The + operator adds second tuple at the end of the first tuple. The
second tuple is concatenated twice.
32. TypeError: can only concatenate tuple (not “str”) to tuple
Here, (“Hello”) takes “Hello” as a string, not a tuple.
33. (1,2, ‘Hi’, 1,2, ‘Hi’)
The tuple is concatenated and further concatenated 2 times
34. True
The in operator returns True if the given item exists in the tuple. Here
1 is present in the tuple.
35. False
The in operator returns True if the given item exists in the tuple. Here
11 is not present in the tuple.
36. True
The not in operator returns True if the given item does not exist in the
tuple. Here 13 is not present in the tuple
37. False
The not in operator returns True if the given item does not exist in the
tuple. Here 1 is present in the tuple
38. False
The in operator returns True if the given item exists in the tuple. Here
1 is not present in the tuple as an item, tuple (1,2) exists.
39. A tuple object will be created and first argument i.e name Gauri will
be printed.
40. A tuple object will be created and age and gender for pa will be
printed i.e. 45 F.

11.2
1. The function is reading values as string and printing the values, taking
given values of a and b. The output will be:
Value of a : 7
Value of b : 13
2. Here, (x,y) is passed as a tuple and it becomes value of a and b is
taken as None by default.
Value of a : (7, 13)
Value of b : None
3. The function is converting the values into strings, converting them
into tuples and concatenating.
(‘1’, ‘0’, ‘2’, ‘0’)
4. The function is converting the string into tuple and concatenating it b
number of times:
(‘1’, ‘0’, ‘0’, ‘1’, ‘0’, ‘0’, ‘1’, ‘0’, ‘0’)
5. The function takes one tuple and an item as argument and prints
Found, if item exists in the tuple, Not found, otherwise. Here, 1 is
present in tuple, so output will be:
Found
6. The function finds the largest value in the tuple using function max().
It checks whether the tuple has any 3-digit value (>100) or not. Here
111 is 3-digit number. The output will be:
Tuple has 3-digit values.
7. The function finds the largest value in the tuple using function max().
It checks whether the tuple has single-digit, 2 digit(>10) or 3-digit
values (>100) or not. Here maximum value 13 is 2-digit number. The
output will be:
Tuple has 2-digit values.
8. The function finds the smallest value in the tuple using function min().
It converts the list passed as argument to tuple. Here 1 is the minimum
value. The output will be:
Tuple has min value: 1
9. The function concatenates the tuple a given number of times and
prints the length of the resulting tuple. Here the output will be:
Length of tuple (‘1’,11, ‘1’,11, ‘1’,11) is 6.
10. The function concatenates the tuple a given number of times and
prints the length of the resulting tuple. Here the output will be:
Length of tuple (‘1’,(5,3), ‘1’,(5,3)) is 4.

11.3
i. False: Error will be shown if parentheses are missing.
ii. True
iii. False, a tuple is immutable
iv. True
v. False: It is not mandatory.
vi. True
vii. False. Constructor tuple() can be used to convert any list, string, set or
dictionary to a tuple.
viii. False, it can be converted to a tuple.
ix. False. Only one copy is retained in the tuple.
x. False. Tuple is created only with key values of the dictionary.
xi. False. The elements are added in the sequence.
xii. True
xiii. False. The nested tuples are concatenated as tuples, not flattened.
xiv. True
xv. False. The negative index indicates values from end of the tuple.
IndexError is thrown only when the negative index is more than the
length of the tuple-1.
xvi. True
xvii. True
xviii. True
xix. False. We can search for a tuple inside a tuple using in operator
because a tuple may have a nested tuple.
xx. False. The values in a tuple cannot be changed.
CHAPTER 12
Classes
In this chapter you will be able to check how much you know about
classes in Python.

Key Points
Class allows to create user-defined objects.
Every element in Python belongs to a class given by type().
A user-defined class is defined using keyword class class_name:
A class without any members is empty class
def __init__(self): is constructor of class
Any number of instances of a class can be created by calling constructor :
obj= class()
Attributes defined in class outside any function are class attributes and
accessed through class_name.attribute
Instance attributes are accessed using obj.attribute
class class_name(BaseClass): defines a class derived from BaseClass
super() method invokes constructor of base class in constructor of
derived class
Q.12.1 What will be the output after executing the following programs
in Python?
1. class Human:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print (“Name : ”, name, “, Age: ”, age)
e1 = Human(“Sandeep”, 30)
e1.display()
2. class Human:
def __init__(self, name, age):
self.name = name
self.salary = age
def display(self):
print (“Name : ”, self.name, “, Age: ”, self.age)
e1 = Human(“Ashu”, 30)
e1.display()
3. class Person:
def __init__(self, n, g):
self.name = n
self.gender = g
def display(self):
print (“Name : ”, self.n, “, Gender : ”, self.g)
e1 = Person(“Shikha”, “Female”)
e1.display()
4. class KGStudent:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display():
print (“Name : ”, self.name, “, Marks: ”, self.marks)
c1=KGStudent(“Ishaan”, 100)
c1.display()
5. class KGStudent:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def display(self):
print (“Name : ”, self.name, “, Marks: ”, self.marks)
c1=KGStudent(“Arnav”, 100)
c1.display()
6. class GovtEmployee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def displayEmp(self):
print (“Name : ”, self.name, “, Salary: ”, self.salary)
elist=[]
for i in range(3):
n=input(“Enter name of an employee: ”)
s=int(input(“Enter salary of an employee: ”))
e=GovtEmployee(n,s)
elist.append(e)
for e in elist:
e.displayEmp()
7. class PGStudent:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def displayS(self):
print (“Name : ”, self.name, “, Marks: ”, self.marks)
slist=[]
for i in range(3):
n=input(“Enter name of the student: ”)
m=int(input(“Enter marks of the student: ”))
s=PGStudent(n,m)
slist.append(s)
max=-1
s1= “”
for s in slist:
s.displayS()
if s.marks>max:
max=s.marks
s1=s.name
print(“Student with max marks:”, s1)
8. class Kid:
kidsCount = 0
def __init__(self, name, house):
self.name = name
self.house = house
Kid.kidsCount += 1
def displayCount(self):
print( “Total Kids: ”, Kid.kidsCount)
def displayKid(self):
print (“Name : ”, self.name, “, House: ”, self.house)
k1=Kid(“Ayushi”, “Air”)
k1.displayKid()
k1.displayCount()
n=input(“Enter name of a kid: ”)
h=int(input(“Enter house of a kid: ”))
k=Kids(n,h)
k.displayKid()
k.displayCount()
9. class Point3D:
counter=0
def __init__(self, x, y,z):
self.x = x
self.y = y
self.z = z
Point3D.counter+=1
def displayPoint3D(self):
print(“x= ”,self.x, “y= ”, self.y, “z=”, self.z)
def countPoints(self):
print(Point3D.counter)
p1=Point3D(12,10,10)
p1.displayPoint3D()
p2=Point3D(2,10,20)
p2.displayPoint3D()
p1.countPoints()
p2.countPoints()
10. class Faculty:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age=age
def displayInfo(self):
print(“Name: ”, self.firstname + “ ” + self.lastname)
print(“Age: “, self.age)
class Teacher():
def __init__(self, first, last, age, sttaffnum, subject):
super().__init__(first, last,age)
self.staffnumber = staffnum
self.subject= subject
def displayTeacher(self):
super().displayInfo()
print(“Staff no.= ”, self.staffnumber)
print(“Subject = ”, self.subject)
x = Faculty (“Usha”, “Goel”, 24)
y = Teacher (“Ramesh”, “Goel”, 34, 101, “Mathematics”)
x.displayInfo ()
y.displayTeacher ()
11. class Faculty:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age=age
def displayInfo(self):
print(“Name: ”, self.firstname, “ ”,self.lastname, “,
Age: ”, self.age)
class Teacher(Faculty):
def __init__(self, first, last, age, sttaffnum, subject):
super().__init__(first, last,age)
Classes 71
self.staffnumber = staffnum
self.subject= subject
def displayTeacher(self):
super().displayInfo()
print(“Staff no.= ”, self.staffnumber,“, Subject = ”,
self.subject)
x = Faculty (“Usha”, “Goel”, 24)
y = Teacher (“Ramesh”, “Goel”, 34, 101, “Mathematics”)
x.displayInfo ()
y.displayTeacher ()
12. class Book:
def get(self):
self.title = input(“Enter title: ”)
self.author = int(input(“Enter author: ”))
self.price=float (input(“Enter price: ”))
def displayBook(self):
print(“Title:”, self.title,“, Author: ”, self.author)
print(“Price: ”, self.price)
class Novel(Book):
def getInfo(self):
super().get()
self.genre = input(“Enter genre: ”)
def displayNovel(self):
super().displayBook()
print(“Genre= ”, self.genre)
x1 = Book()
x1.get()
y1 = Novel()
y1.getInfo()
x1.displayBook()
y1.displayNovel()
13. class Quad:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print(“perimeter=”,p)
class Rectangle(Quad):
def __init__(self, s1, s2):
super().__init__(s1, s2, s1, s2)
r1=Rectangle(3, 7)
r1.perimeter()
14. class Quad:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print(“perimeter=”,p)
class Polygon(Quad):
def __init__(self, s1, s2, s3, s4):
super().__init__(s1, s2, s3, s4)
p1=Polygon(3, 7, 5, 2)
p1.perimeter()
15. class Quad:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print(“perimeter=”,p)
class Rectangle(Quad):
def __init__(self, a,b):
super().__init__(a, b, a, b)
def area(self):
a = self.side1 * self.side2
print(“area of rectangle=”, a)
p1=Rectangle(5, 2)
p1.perimeter()
p1.area()
16. class Quad:
def __init__(self, a, b, c, d):
self.side1=a
self.side2=b
self.side3=c
self.side4=d
def perimeter(self):
p=self.side1 + self.side2 + self.side3 + self.side4
print(“perimeter=”,p)
class Rectangle(Quad):
def __init__(self, a,b):
super().__init__(a, b, a, b)
def area(self):
a = self.side1 * self.side2
print(“area of rectangle=”, a)
class Square(Rectangle):
def __init__(self, a):
super().__init__(a, a)
def area(self):
a=pow(self.side1, 2)
print(‘Area of Square: ’, a)
p1=Square(5)
p1.perimeter()
p1.area()
17. class Student:
_school = ‘Life School’
def __init__(self, name, standard):
self.name=name
self.std=standard
class UGStudent(Student):
def __init__(self, name, standard,age):
super().__init__(name, standard)
self.age= age
s1 = Student(“Steve”, 7)
print(“Details s1:”)
print(‘School: ’,s1._school)
print(‘Name: ’,s1.name)
print(‘Standard: ’,s1.standard)
s2= UGStudent(“Smith”, 7, 22)
print(“Details s2:”)
print(‘School: ’,s2._school)
print(‘Name: ’,s2.name) print(‘Standard: ’,s2.standard)
print(‘Age: ’,s2.age)
18. class Student:
_school = ‘Life School’
count=0
def __init__(self, name, standard):
self.name=name
self.std=standard
Student.count+=1
class UGStudent(Student):
def __init__(self, name, standard,age):
super().__init__(name, standard)
self.age=age
s1 = Student(“Steve”, 7)
print(“Count:”, s1.count)
s2= UGStudent(“Smith”, 7, 22)
print(“Count:”, s2.count)
19. class Student:
_school = ‘Life School’
count=0
def __init__(self, name, standard):
self.name=name
self.std=standard
Student.count+=1
class UGStudent(Student):
def __init__(self, name, standard,age):
super().__init__(name, standard)
self.age=age
Student.count+=1
s1 = Student(“Steve”, 7)
print(“Count:”, s1.count)
s2= UGStudent(“Smith”, 7, 22)
print(“Count:”, s2.count)
20. class Actor:
def __init__(self):
self.__name=’’
def setname(self, name):
print(‘setname() called’)
self.__name=name
def getname(self):
print(‘getname() called’)
return self.__name
name=property(getname, setname)
actor1 = Actor()
actor1.name=“Salman”
print(actor1.name)

Q.12.2 State whether the following statements are True or False:


i. If the name of the methods are display(self) in both - the base class
and derived class in inheritance, then this is called method
overloading.
ii. Method overloading is not supported in Python.
iii. We can access a class variable with any method in the class.
iv. self can be used as the name for any of the argument in a method
inside a class.
v. The convention lower_case_with_underscores is used for functions,
methods and classes in Python.
vi. All exceptions in Python should be derived from class ‘Exception’.
vii. When an __init__() method is defined inside a class, class
instantiation automatically invokes it for the newly-created class
instance.
viii. Base classes may override methods of their derived classes.
ix. “Private” instance variables exist in Python that cannot be accessed
except from inside an object.
x. Any data variable/member should be accessed using self except class
variable.

ANSWERS

12.1
1. NameError: name ‘name’ is not defined will be displayed. This is
because name and age should be referred by self.name and self. age
instead of name and age.
2. Name : Ashu , Age : 30
3. AttributeError: ‘Person’ object has no attribute ‘n’. This is
because the variables inside __init__ function are the actual data
members while the ones which are passed to it are formal arguments.
self.name and self.gender should be used instead of self.n and self.g.
4. TypeError: display() takes 0 positional arguments but 1 was
given. This is because keyword self is missing in definition of
display() function.
5. Name: Arnav, Marks: 100
6. The program input values for 3 GovtEmployees and appends them in a
list, elist. Then it displays the details about these in given format:
Name : Gautam , Salary: 100000
Name : Sunil , Salary: 200000
Name : Anil , Salary: 300000
7. The program input values for 3 PGStudents and prints the name of the
student with highest marks:
Name : Jayanti , Marks: 99
Name : Aradhana , Marks: 99
Name : Vineeta , Marks: 100
Student with max marks: Vineeta
8. The program creates a class Kid to store name and house of a child. A
class variable kidsCount is initialized to 0. It is used to display the
count of number of Kid objects created in the program.
Name : Ayushi , House: Air
Total Kids: 1
Enter name of a kid: [Kriti]
Enter house of a kid: [Water]
Name : Kriti , House: Water
Total Kids: 2
9. The program creates a class for representing 3D point objects and
displays the total count using class variable counter. The value of
counter is displayed as same by both the objects.
x= 12 y=10 z=10
x= 2 y= 10 z=20
2
2
10. The program gives error because the base class from which Teacher
class is derived is not defined while defining it.
TypeError: object.__init__() takes no parameters
11. The program creates a class Faculty and derives a class Teacher from
it. The methods of base class are called from derived class using the
keyword super(). One object of type Faculty and one of type Teacher
are created and details are displayed using their respective display
methods:
Name: Usha Goel, Age: 24
Name: Ramesh Goel, Age: 34
Staff no.= 101, Subject = Mathematics
12. The program creates a class Book and derives a class Novel from
Book. The methods of base class are called from derived class using
the keyword super(). One object of type Novel is created. There is no
__init__() function here. So no value is passed while creating object of
this class. The values are read from user using getInfo() method and
details are displayed using displayNovel() method.
Enter title: The God of Small Things
Enter author: Arundhati Roy Enter price= 400
Enter genre: Literature fiction
Title: The God of Small Things, Author: Arundhati Roy
Price:400
Genre: Literature fiction
13. Perimeter: 20
There are 2 classes namely Quad and Rectangle. The class Rectangle
is inherited from class Quad. Since there is no perimeter method in
class Rectangle, it is called from class Quad. The sides of Quad are
taken as 3,7,3,7 due to inheritance for calculating the perimeter.
14. Perimeter: 17
There are 2 classes namely Quad and Polygon. The class Polygon is
inherited from class Quad. Since there is no perimeter method in class
Polygon, it is called from class Quad. The sides of Quad are taken as
3,7,5,2 due to inheritance for calculating the perimeter.
15. Perimeter: 14
Area of rectangle: 10
There are 2 classes namely Quad and Rectangle. The class
Rectangle is inherited from class Quad. Since there is no perimeter
method in class Rectangle, it is called from class Quad. The sides of
Quad are taken as 5,2,5,2 due to inheritance for calculating the
perimeter. The method area is called from class Rectangle with
side1 as 5 and side2 as 2.
16. Perimeter: 20
Area of square: 25
There are 3 classes namely Quad, Rectangle and Square. The class
Rectangle is inherited from class Quad. The class Square is inherited
from class Rectangle. Since there is no perimeter method in class
Rectangle, it is called from class Quad for object of class Square. The
sides of Quad are taken as 5,5,5,5 due to inheritance for calculating
the perimeter. The method area is overridden from class Rectangle in
class Square with side1 as 5.
17. Details s1:
School: Life school
Name: Steve
Standard: 7
Details s2:
School: Life school
Name: Smith
Standard: 7
Age: 22
There are 2 classes namely Student and UGStudent. The class
UGStudent is inherited from class Student. The attribute _school is
class attribute, common to all instances of class while name and std
are local to class Student and name, std and age are local to class
UGStudent.
18. Student count: 1
Student count: 2
There are 2 classes namely Student and UGStudent. The class
UGStudent is inherited from class Student. The attribute count is class
attribute, common to all instances of class while name and std are
local to class Student and name, std and age are local to class
UGStudent. The class attribute is accessed with class name as
Student.count and incremented by 1 in constructor of class Student. It
is incremented whenever a derived class object is created because then
parent class constructor is also called.
19. Student count: 1
Student count: 3
There are 2 classes namely Student and UGStudent. The class
UGStudent is inherited from class Student. The attribute count is class
attribute, common to all instances of class while name and std are
local to class Student and name, std and age are local to class
UGStudent. The class attribute is accessed with class name as
Student.count and incremented by 1 in constructor of class Student. It
is incremented in constructor of class UGStudent as well. Whenever a
derived class object is created, it is incremented twice because then
parent class constructor is also called.
20. setname() called
getname() called
‘Salman’
The function property(getname, setname) returns the property object
and assign it to variable name. The attribute __name is private
instance attribute of the class. It is accessed directly using variable
name, but it is accessed through getname() and setname() methods.

12.2
i. False
if the name of the methods are display(self) in both - the base class
and derived class, then this is called method overriding.
ii. True
iii. True
iv. False
self should always use as the name for the first method argument
v. False
The convention is to use CamelCase for classes and lower_case_with_
underscores is used for functions and methods.
vi. True
vii. True
viii. False
Derived classes may override methods of their base classes.
ix. False
Such concept does not exist in Python.
x. True
CHAPTER 13
Files
In this chapter you will be able to check how much you know about file
handling in Python.

Key Points
Open(filename, mode)- It is used to create a file object for reading or
writing.
Mode: r (for reading only, w- for writing only, a- for appending the contents
to existing contents of the file, r+ for reading and writing both, w+ for
writing and reading both, a+ for appending and reading both. The file must
exist for r modes. It will be created for w and a modes if not existing. ‘rb’,
‘wb’ are used for binary files.
close() - It is used to free the file object.
write() – It is used to write text or binary content to file.
writelines()- It is used to write multiple lines or binary content to file.
read() – It is used to read specific number of characters from the file.
readline() – It is used to read one line at a time from the file, i.e from
current reading position to newline character.
readlines() – It is used to read all lines in the file and returns a list of lines.
seek() – It is used to set the position for reading or writing in a file.
13.1 Consider using open function for opening a file:
filename = input(‘Enter a filename : ’)
f1 = open(filename, ‘mode’)
Which of the following modes is used when a file is to be opened for
writing only?
a. w
b. w+
c. a
d. All of these
13.2 Consider using open function for opening a file:
filename = input(‘Enter a filename : ’)
f1 = open(filename, ‘mode’)
Which of the following modes is used when a file is to be opened for both
reading and writing?
a. rw
b. w+
c. r+
d. w
13.3 Consider using open function for opening a file:
filename = input(‘Enter a filename : ’)
f1 = open(filename, ‘mode’)
Which of the following modes is used when a file is to be opened for
writing to an existing file without overwriting the existing contents?
a. wr
b. w+
c. a
d. None of these
13.4 Consider using open function for opening a file:
filename1 = input(‘Enter a filename : ’)
file1 = open(filename1, ‘mode’)
Which of the following modes is used when a file is to be opened for
reading only?
a. r
b. w
c. a
d. None of these
13.5 What happens when the file with specified filename in the function
open() does not already exist in the system using the command:
file1=open(filename, ‘w’)?
a. file1 gets a NULL value
b. a new file is created with given filename
c. an error message is shown “file does not exist”
d. None of these
13.6 What happens when the file with specified filename in the function
open does not already exist in the system using the command:
file1=open(filename, ‘r’)?
a. an error message is shown “file does not exist”
b. file1 gets a NULL value
c. a new file is created with given filename
d. None of these
13.7 Consider the program given:
name1 = input(‘Enter a filename : ’)
f1 = open(name1, “w”)
t1=“This is content of the file”
f1.write(t1)
x1=f1.read()
print(x1)
f1.close()
What happens when a file name1 is opened for the writing in “w” mode and
a read operation is performed?
a. read operation is successfully performed
b. an error message : “io.UnsupportedOperation: not readable”
c. read operation returns blank
d. None of these
13.8 Consider the program given:
name1 = input(‘Enter a filename : ’)
f1 = open(name1, “w+”)
t1=“This is content of the file”
f1.write(t1)
x1=f1.read()
print(x1)
f1.close()
What happens when a file name1 is opened for the writing in “w+” mode
and a read operation is performed?
a. read operation is successfully performed
b. an error message : “io.UnsupportedOperation: not readable”
c. read operation returns blank
d. None of these
13.9 Consider the program given:
name1 = input(‘Enter a filename : ’)
f1 = open(name1, “r+”)
f1.write(“Hello this is written in a file.”)
x1=f1.read()
print(x1)
f1.close()
What happens when an already existing file is opened for the writing and
reading in “r+” mode and a read operation is performed?
a. read operation is successfully performed and “Hello this is written in a
file.” is printed on the screen
b. an error message : “FileNotFoundError: No such file or directory:
name1”
c. blank is returned from read operation
d. None of these
13.10 Consider the program given:
name1 = input(‘Enter a filename : ’)
f1 = open(name1, “r+”)
f1.write(“Hello this is written in a file.”)
x1=f1.read()
print(x1)
f1.close()
What happens when a file which does not already exist is opened for the
writing and reading in “r+” mode and a read operation is performed?
a. read operation is successfully performed and “Hello this is written in a
file.” is printed on the screen
b. an error message :“FileNotFoundError: No such file or directory:
name1”
c. blank is returned from read operation
d. None of these
13.11 What happens when the following program code in Python is
executed?
name1 = input(‘Enter a filename : ’)
f1 = open(name1, “w”)
t1=int(input(‘Enter your age:’))
f1.write(t1)
1.close()

a. Value of t1 will be written in file as integer


b. Value of t1 will be written in file as a string
c. An error message :TypeError: write() argument must be str, not int
d. None of these
13.12 Consider the following program in Python:
name1 = input(‘Enter a filename : ’)
f1 = open(name1, “w+”)
t1=int(input(‘Enter your age:’))
f1.write(t1)
r1=f1.read()
print(r1)
f1.close()
What happens when the following program code in Python is executed and
given input is entered by the user?
Enter a filename: a.dat
Enter your age: 40
a. File ‘a.dat’ will be opened for writing and reading and error will be
reported if ‘a.dat’ does not already exists. 40 will be written in ‘a.dat’
and also printed on screen.
b. File ‘a.dat’ will be opened for writing and reading and if ‘a.dat’ does
not already exists, it will be created. 40 will be written in ‘a.dat’ and
also printed on screen.
c. File ‘a.dat’ will be opened for writing and reading and if ‘a.dat’ does
not already exists, it will be created. 40 will be written in ‘a.dat’ but
will not be printed on screen.
d. None of these
13.13 Consider the following program in Python:
name1 = input(‘Enter a filename : ’)
f1 = open(name1, “w+”)
t1=int(input(‘Enter your age:’))
f1.write(t1)
r1=f1.read()
f1.seek(0)
print(r1)
f1.close()
What happens when the following program code in Python is executed and
given input is entered by the user?
Enter a filename: a.dat
Enter your age: 40

a. File ‘a.dat’ will be opened for writing and reading and error will be
reported if ‘a.dat’ does not already exists. 40 will be written in ‘a.dat’
and also printed on screen.
b. File ‘a.dat’ will be opened for writing and reading and if ‘a.dat’ does
not already exists, it will be created. 40 will be written in ‘a.dat’ and
also printed on screen.
c. File ‘a.dat’ will be opened for writing and reading and if ‘a.dat’ does
not already exists, it will be created. 40 will be written in ‘a.dat’ but
will not be printed on screen.
d. None of these
13.14 Consider that file ‘myfile.dat’ has the contents:
This is a new file where we are writing. There are seven days in a week.
There are twelve months in a year.
What will be the output of the following program in Python?
# readFile1.py
def readFile1(name):
f1 = open(name, “r”)
while True:
text = f1.read(50)
if text == “”:
break
print(text)
f1.close()
readFile1(‘myfile.dat ’)

a. Entire text will be read in variable text and printing on screen


b. 50 characters will be read in variable ‘text’ and printing on screen
c. An error message will be shown as: wrong input to read()
d. None of these
13.15 Consider the program given below:
def copyFile(old, new):
f1 = open( old, “r”)
f2 = open(new, “w”)
while True:
text = f1.read()
if text == “”:
break
f2.write(text)
f1.close()
f2.close()
Assume that file ‘source.dat’ has the contents:
This is a new file where we are writing.
%There are seven days in a week.
There are twelve months in a year.
What will be the output of the following command in Python?
copyFile(‘source.dat’, ‘destination.dat’)
a. contents of file ‘source.dat’ will be copied to ‘destination.dat’.
b. contents of ‘sourec.dat’ will be printed on the screen
c. Error message will be shown that two files cannot be opened
d. None of these
Q.13.16 What will be the output of the following code?
1. f = open(‘filename1’, ‘w’)
f.read()
2. f = open(‘a.dat’, ‘w’)
f.write(‘Welcome to first line of my file’)
3. f = open(‘a.dat’, ‘w’)
f.write(‘Welcome to first line of my file’)
list(f)
4. f = open(‘a.dat’, ‘r’)
f.close()
f.read()
5. f = open(‘a.dat’, ‘w+’)
f.write(‘Welcome to first line of my file. ’)
f.write(‘Here comes the second line of my file. ’)
f.write(‘Third line. ’)
f.seek(0)
t=f.readlines()
print(t)
6. f = open(‘a.dat’, ‘a+’)
f.write(‘Welcome to first line of my file. ’)
f.write(‘Here comes the second line of my file. ’)
f.write(‘Third line. ’)
f.seek(0)
t=f.readlines()
print(t)
7. lines=[“Hello Everyone!\n”, “Welcome to File Handling.\n”]
f=open(“myfile.txt”, “w”)
f.writelines(lines)
f.close()
8. f=open(“file.bin”,“wb”)
num=[5, 10, 15, 20, 25]
arr=bytearray(num)
f.write(arr)
f.close()
9. f = open(‘file.bin’, ‘rb’)
content = f.read()
print(content)
f.close()
10. f=open(“file.bin”,“wb”)
f.write(“This content is for binary file”)
f.close()
f = open(‘file.bin’, ‘rb’)
content = f.read()
print(content)
f.close()
11. f=open(“file.bin”,“wb”)
f.write(b”This content is for binary file”)
f.close()
f = open(‘file.bin’, ‘rb’)
content = f.read()
print(content)
f.close()
12. with open(‘file1.bin’, ‘wb’) as fl:
fl.write(b’Hello Python’)
fl.write(b’Quiz 1:’)
with open(‘file1.bin’, ‘rb’) as fl:
data = fl.read()
print(data)
13. with open(‘myfile.bin’, ‘wb’) as fl:
text = ‘You are amazing!’
fl.write(text.encode(‘utf-8’))
with open(‘myfile.bin’, ‘rb’) as fl:
data = fl.read(128)
text = data.decode(‘utf-8’)
print(text)
14.f=open(‘file1.txt’)
while True:
try:
line=next(f)
print(line)
except StopIteration:
break
f.close()
14. f=open(‘file1.txt’, ‘w’)
f.write(“First Line.\nSecond Line.”)
f.close()
f=open(‘file1.txt’)
while True:
try:
line=next(f)
print(line)
except StopIteration:
break
f.close()

Q.13.17 State whether the given statements are True/ False:


i. The file can be opened in read mode when it is not exiting in the
system.
ii. The file must exist to be opened in write and read modes using ‘r+’.
iii. The file must exist to be opened in write and read modes using ‘w+’.
iv. The file must exist to be opened in write and read modes using ‘a+’.
v. The string can be written directly in a binary file while integer needs
to be converted into binary.
vi. The function readlines() read all lines of a text file together.
vii. Multiple lines can be written in a file using function writelines().
viii. The function seek() takes the file cursor for reading or writing to a
specific position in the file.
ix. The number of characters read can be restricted using read() function.
x. Lines are separated by ‘\n’ in a file.
ANSWERS
13.1 a
13.2 b and c
Important terms: Mode “w+” means writing and reading and mode
“r+” means reading and writing. File should be already existing when
it is opened in “r+” mode while it will be created in “w+” mode if not
existing already.
13.3 c
13.4 a
13.5 b
Since a file is opened for writing, a new file is created with given
filename if it not already exists.
13.6 a
(an error message is shown “file does not exist”)
13.7 b
(an error message is shown “io.UnsupportedOperation: not readable”
Here, the file is opened in “w” mode which means only writing. So
system gives an error message when read operation is asked.
13.8 c
(blank is returned from read operation)
Here, read operation is performed successfully because the file is
opened in “w+” mode which means writing and reading both. When
the contents of t1 are written to the file, the position is at the end of the
file. Hence, when read operation is performed, it reads end of file and
returns blank.
13.9 c
(blank is returned from read operation)
Here, read operation is performed successfully because the already
existing file is opened in “r+” mode which means writing and reading
both. When the contents of t1 are written to the file, the position is at
the end of the file. Hence, when read operation is performed, it reads
end of file and returns blank.
13.10 b
(an error message is shown “FileNotFoundError: No such file or
directory: name1”)
Here, the file is opened in “r+” mode which requires a file to exist
already. So a FileNotFoundError will be printed on the screen.
13.11 c
Here the contents are stored as string in files. So the integer value
needs to be converted to a string using str(t1) before storing to the file.
13.12 c
File ‘a.dat’ will be opened for writing and reading and if ‘a.dat’ does
not already exists, it will be created. 40 will be written in ‘a.dat’ but
will not be printed on screen. This is because after writing the file
object location is at the end of the file.
13.13 b
File ‘a.dat’ will be opened for writing and reading and if ‘a.dat’ does
not already exists, it will be created. 40 will be written in ‘a.dat’ and
also printed on the screen. This is because after writing f1.seek(0), the
file object location is at the beginning of the file.
13.14 b
The contents of the file ‘myfile.dat’ will read 50 characters at a time
and printed on the screen in three lines.
This is a new file where we are writing. There are seven days in a
week. There are twelve months in year.
13.15 a
The program copies the contents of file ‘source.dat’ to
‘destination.dat’.
13.16
1. Whenever a text file ‘filename’ is opened using open, it can be opened
it many modes: ‘r’ for only reading, ‘w’ for only writing, ‘a’ for
appending to existing file and creating if a file is not already existing,
‘r+’ for reading and writing and ‘r’ is the default mode. Since file is
opened here for writing mode, read() function is not permitted and
following error message is shown.
io.UnsupportedOperation: not readable
2. File with name ‘a.dat’ is created and opened in writing mode as it does
not exist before. One line is written to it using f.write(). This function
returns the total number of characters written in this file:
32
3. The list(f) function reads and prints all the contents of the file. Since
file is opened here for writing mode, list(f) function is not permitted
and following error message is shown.
io.UnsupportedOperation: not readable
Important terms: The file should be closed using f.close() for writing
and opened again for reading to use list(f) function.
4. The file ‘a.dat’ is opened for reading. The function f.read() is called
when it is closed. So no read can take place and the following error is
reported:
ValueError: I/O operation on closed file
5. Three lines are written to file ‘a.dat’ using f.write() as it is opened for
both writing and reading using ‘w+’ mode. f.readlines() will read all
the lines in the file ‘a.dat’.
[‘Welcome to first line of my file. Here comes the second line of my
file. Third line’]
6. Three lines are written to file ‘a.dat’ using f.write() as it is opened for
both appending and reading using ‘a+’ mode. Suppose the existing
contents of the file were: Exiting Contents.
f.readlines() will read all the lines in the file ‘a.dat’.
[‘Exiting Contents. Welcome to first line of my file. Here comes
the second line of my file. Third line’]
7. Myfile.txt will be opened for writing and the 2 lines will be written in
the file using function writelines(). The contents of the file will be:
Hello everyone!
Welcome to file handling.
8. The code stores a list of integer numbers in binary form in a binary file
file.bin. The bytearray() function returns the byte representation of the
object.
9. The code reads the data from the binary file and prints on the screen.
It is in binary format (hexadecimal equivalents).
b’\x05\n\xof\x14\x19
10. TypeError: ‘str’ does not support the buffer interface
The string cannot be written directly to a binary file using write()
function. It needs to be converted into binary.
11. b”This content is for binary file”
The contents of the binary file will be displayed.
12. b’Hello PythonQuiz 1:’
The contents are written to a binary file using write() and read using
read() function. These are printed as binary on the screen.
13. You are amazing!
The text is converted to binary for writing to a binary file using
decode() function. It is converted to string after reading from the
binary file.
14. FileNotFoundError: No such file or directory: ‘file.txt’
The error is thrown in case file is not already created and written
15. First Line.
Second Line.
The inbuilt iterator reads the given file line by line until StopIteration
is raised. It is raised when end of file is reached.

13.17
i. False
The file must exist when it is to be opened in read mode.
ii. True
iii. False
The file will be created if it already does not exist.
iv. False
The file will be created if it already does not exist.
v. False
It needs to be written as a binary value by prefixing with character b.
vi. True
vii. True
viii.True
viii. True
ix. True
CHAPTER 14
Graphics
In this chapter you will be able to check how much you know about
graphics in Python using TKinter.

Key Points
Tkinter module has many functions for creating a GUI import tkinter
Frame()
window()=Tk() creates a top-level window(root)
window.title() sets the title of the window
window.geometry() defines the width, height and coordinates of top left
corner of the frame.
window. mainloop() sets the event listening loop
Button() creates a button for pressing with a label
Label() creates a static text
Entry() creates a single-line text field
Text() creates a multi-line text field
Pack() puts a widget inside a frame
Bind() associates an event to a callback function which is called when
event occurs

Questions
Q. Select the most appropriate answer for the following questions:
14.1 Which of the following is used to create a top level window?
a. title()
b. Tk()
c. main()
d. All of these
14.2 Which of the following is used to set the window title?
a. title()
b. Tk()
c. geometry()
d. None of these
14.3 Which of the following is used to create a window icon?
a. geometry()
b. root()
c. wm_iconbitmap()
d. None of these
14.4 Which of the following is used to set window size?
a. geometry()
b. root()
c. wm_iconbitmap()
d. None of these
14.5 Which of the following is used to display window and wait for any
events?
a. root()
b. wait()
c. mainloop()
d. None of these
14.6 Which of the following is the datatype of a font in tkinter?
a. a list
b. an integer
c. a tuple
d. None of these
14.7 Which of the following represents red color?
a. #000000
b. #0000ff
c. #ff0000
d. None of these
14.8 Which of the following represents the shape of a canvas?
a. rectangular
b. oval
c. circle
d. None of these
14.9 Which of the following is used to add the canvas to the root
window?
a. pack()
b. add()
c. join()
d. Any of these
14.10 Which of the following is used to create an arc in a window?
a. arc()
b. createArc()
c. create_Arc()
d. create_arc()
14.11 Which of the following is used to display an image in the canvas?
a. draw_image()
b. create_image()
c. display_image()
d. None of these
14.12 Which of the following represents the direction of the image in a
canvas?
a. anchor
b. dir
c. source
d. None of these
14.13 Which of the following is a widget?
a. Button
b. Label
c. Scrollbar
d. All of these
14.14 Which of the following is an event handler?
a. action()
b. bind()
c. pack()
d. None of these
14.15 Which of the following is not a layout manager for arranging the
widgets in a frame?
a. pack layout manager
b. grid layout manager
c. place layout manager
d. None of these
14.16 Which of the following is used to add a scrollbar to the Text
widget?
a. scrollbar()
b. ScrollBar()
c. Scrollbar()
d. None of these
14.17 Which of the following is used to set the orientation of the
scrollbar in a Text widget?
a. orientation
b. Orientation
c. orient
d. None of these
14.18 Which of the following widget allows the user to select values
from a given set of values?
a. Entry
b. Spinbox
c. Radiobutton
d. None of these
14.19 Which of the following is not an option in “selectmode” in
Listbox widget?
a. browse
b. single
c. multiple
d. None of these
14.20 Which of the following is used to add menu items to a menu?
a. add_command()
b. add_value()
c. add_item()
d. None of these
14.21 Which of the following is used to install tkinter?
a. install tkinter
b. pip install tkinter
c. tkinter pip install
d. None of these
14.22 Which of the following is used to import tkinter in Python
program?
a. import tkinter
b. from tkinter import *
c. import tkinter as tk
d. All of these
14.23 Which of the following is used by function place() to put widget
on the screen?
a. row and column wise
b. according to x y coordinate
c. according to left, right, up, down
d. None of these
14.24 In which of the following a button cannot be placed?
a. Frame
b. Window
c. Both of these
d. None of these
14.25 Which of the following is correct number of arguments we can
pass in a function to create a rectangle using canvas tkinter?
a. 4
b. 3
c. 2
d. None of these
14.26 Which of the following allows one screen inside another screen?
a. Frames
b. Labels
c. Buttons
d. None of these
14.27 Which of the following is provided by tkinter in Python
program?
a. Database
b. GUI
c. File handling
d. None of these
14.28 Which of the following is used to change the property of a
widget?
a. pack()
b. config()
c. title()
d. None of these
14.29 Which of the following is used to get multiline input from user?
a. label
b. frame
c. text
d. None of these
14.30 Which of the following is correct syntax of destroy() function ?
a. object.destroy()
b. destroy(object)
c. object(destroy)
d. None of these
14.31 State whether the following statements are True or False:
i. Tk is a class whose object is to be created for creating a root window.
ii. A font represents a type of displaying only letters in a window.
iii. A frame is a container that is used to draw shapes like lines and
curves.
iv. A canvas is a container that is used to display widgets like buttons and
menus.
v. pack() method is used to add a canvas to the root window.
vi. create_message() is used to display some text in the canvas.
vii. Checkbutton widget is used to allow the user to select one or more
options from available group of options.
viii. Radiobutton widget allows the user to select only one option from a
group of available options.
ix. Entry widget is used to create a rectangular box to enter or display one
line of text.
x. The bind() method is used to bind an event with an event handler
function.
xi. Widgets can be placed on the screen using function place().
xii. An entry widget is used to create user data entry field.
xiii. The format for creating a frame is:: win.Frame(options).
xiv. The format to set the title of the window is: win.title(mytitle)
xv. The function pause() is used to hold a screen we are using.
xvi. Any widget can be deleted from the screen using function delete().
xvii. The function pack() is used to pack a widget to the screen.
xviii. A widget in tkinter GUI is shown on the screen.
xix. The data from data entry field in Python tkinker can be retrieved using
function get().
xx. Button and checkboxes both are clickable.

ANSWERS
14.1 b
14.2 a
14.3 c
14.4 a
14.5 c
14.6 c
14.7 c
14.8 a
14.9 a
14.10 d
14.11 b
14.12 a
14.13 d
14.14 b
14.15 d
14.16 c
14.17 c
14.18 b
14.19 d
14.20 a
14.21 b
14.22 d
14.23 b
14.24 d
14.25 a
14.26 a
14.27 b
14.28 b
14.29 c
14.30 a
14.31
i. True
ii. False
It represents a type of displaying letters and numbers.
iii. False
A frame is a container that is used to display widgets like buttons and
menus.
iv. True
v. True
vi. False
create_text() is used to display some text in the canvas.
vii. True
viii. True
ix. True
x. True
xi. True
xii. True
xiii. False. Frame(window,options)
xiv. True
xv. False. mainloop() function is used
xvi. False. destroy() function is used
xvii. True
xviii. True
xix. True
xx. True
CHAPTER 15
Arrays: NumPy
In this chapter you will be able to check how much you know about arrays
in Python.

Key Points
Arrays can be created in Python using package NumPy.
import numpy
numpy.empty(row, column, dtype) creates an array of given datatype(dtype)
and size
rowXcolumn with garbage values
numpy.full(row, column, x, dtype) creates an array of given datatype(dtype)
and size
rowXcolumn with values x
numpy.ones(row, column, x, dtype) creates an array of given
datatype(dtype) and size
rowXcolumn with values 1
numpy.zeros(row, column, x, dtype) creates an array of given
datatype(dtype) and size rowXcolumn with values 0
nparray.shape returns the size of the array i.e (row,col)
nparray.ndim returns the number of dimensions of the array.
nparray.size returns the number of elements of the array.
nparray.delete() function is used to delete the list of elements given as
arguments.
nparray.max() returns largest value in the array
nparray.min() returns the smallest value in the array
nparray.sum() returns the sum of the elements in the array
nparray.count() returns the count of frequency of occurrence of a particular
element or pattern given as string
nparray.bincount() returns the list of count of frequency of occurrence of a
particular element in ascending order.
nparray.flatten() flattens a two-dimensional array into one dimensional list.
in operator can be used to check for presence of a given value in the array
operators > >= < <= == can be used to compare each element of two arrays
and return corresponding True and False.
The result can be combined for the complete array using
comparison_operator.all( ).

Questions
Q.15.1 State what will be the output of the following code in Python?
1. import numpy as np
arr1 = np.empty(2, dtype=int)
print(“Empty 1D Array”)
print(arr1)
2. import numpy as np
arr1 = np.empty(2, dtype=float)
print(“Empty 1D Array”)
print(arr1)
3. import numpy as np
arr1 = np.empty(2, dtype=bool)
print(“Empty 1D Array”)
print(arr1)
4. import numpy as np
arr1 = np.empty([2, 3], dtype=int)
print(“Empty 2D Array”)
print(arr1)
5. import numpy as np
arr1 = np.empty((3,2), dtype=float)
print(“Empty 1D Array”)
print(arr1)
6. import numpy as np
arr1 = np.empty((2,2), dtype=bool)
print(“Empty 1D Array”)
print(arr1)
7. import numpy as np
arr1 = np.full(3, 10, dtype=int)
print(“Full 1D Array”)
print(arr1)
8. import numpy as np
arr1 = np.full (2, 10.5)
print(“Full 1D Array”)
print(arr1)
9. import numpy as np
arr1 = np.full (2, True)
print(“Full 1D Array”)
print(arr1)
print(arr1.ndim)
10. import numpy as np
arr1 = np.full ([2, 3], 5 dtype=int)
print(“Full 2D Array”)
print(arr1)
11. import numpy as np
arr1 = np.full ((3,2), 7.5, dtype=float)
print(“Full 2D Array”)
print(arr1)
12. import numpy as np
arr1 = np.full ((2,2), True, dtype=bool)
print(“Full 2D Array”)
print(arr1)
13. import numpy as np
arr1 = np.zeros(2, dtype=int)
print(“1D Array with zeroes”)
print(arr1)
14. import numpy as np
arr1 = np.zeros(2, dtype=float)
print(“1D Array with zeroes “)
print(arr1)
15. import numpy as np
arr1 = np.zeros ((2, dtype=bool)
print(“1D Array with zeros”)
print(arr1)
16. import numpy as np
arr1 = np.zeros([2, 3], dtype=int)
print(“2D Array with zeroes “)
print(arr1)
17. import numpy as np
arr1 = np.zeros((3,2), dtype=float)
print(“2D Array with zeroes “)
print(arr1)
18. import numpy as np
arr1 = np.zeros((2,2), dtype=bool)
print(“2D Array with zeros”)
print(arr1)
19. import numpy as np
arr1 = np.ones(2, dtype=int)
print(“1D Array with ones”)
print(arr1)
20. import numpy as np
arr1 = np.ones (2, dtype=float)
print(“1D Array with ones “)
print(arr1)
21. import numpy as np
arr1 = np.ones ((2, dtype=bool)
print(“1D Array with ones “)
print(arr1)
22. import numpy as np
arr1 = np.ones ([2, 3], dtype=int)
print(“2D Array with ones “)
print(arr1)
23. import numpy as np
arr1 = np.ones((3,2), dtype=float)
print(“2D Array with ones “)
print(arr1)
24. import numpy as np
arr1 = np.ones ((2,2), dtype=bool)
print(“2D Array with ones “)
print(arr1)
25. import numpy
arr1 = numpy.array([[1, 2, 3, 4],
[9, 4, 9, 4],
[4, 5, 9, 7],
[2, 5, 4, 3]])
print(arr1)
print(arr1.size)
26. import numpy
arr1 = numpy.array([[2, 8, 9, 4],
[9, 4, 9, 4],
[4, 5, 9, 7],
[2, 9, 4, 3]])
print(repr(arr1).count(“2”))
27. import numpy
arr1 = numpy.array([[2, 2, 9, 4],
[9, 4, 9, 4],
[4, 5, 9, 7],
[2, 9, 4, 3]])
print(repr(arr1).count(“2,9”))
28. import numpy
arr1 = numpy.array([[2, 2, 9, 4],
[9, 4, 9, 4],
[4, 5, 9, 7],
[2, 9, 4, 3]])
print(repr(arr1).count(“2, 9”))
29. import numpy
arr1 = numpy.array([[2, 8, 9, 4],
[9, 4, 9, 4],
[4, 5, 9, 7],
[2, 9, 4, 3]])
print(repr(arr1).count(“2, 9, 4, 3”))
30. import numpy
arr1 = numpy.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print([1, 2, 3, 4] in arr1.tolist())
print([1, 2, 3] in arr1.tolist())
31. import numpy as np
arr1 = np.array([1, 2, 3,4,5,5,5])
print(np.bincount(arr1).argmax())
32. import numpy as np
arr1 = np.array([11, 12, 3,4,5])
print(np.bincount(arr1).argmax())
33. import numpy as np
arr1 = np.array([11, 12, 3,4,5])
freq=np.bincount(arr1)
maximum = max(freq)
for i in range(len(freq)):
if freq[i] == maximum:
print(i, end=” “)
34. import numpy as np
n_array = np.array([[2, 3, 10],
[4, 1, 6]])
print(2 in n_array)
print(0 in n_array)
35. import numpy as np
n_array = np.array([[2, 3, 10],
[4, 1, 6]])
print(n_array.flatten())
36. import numpy as np
a1 = np.array([[1, 2], [3, 4]])
a2 = np.array([[1, 2], [3, 4]])
comparison = a1 == a2
print(comparison)
37. import numpy as np
a1 = np.array([[1, 2], [3, 4]])
a2 = np.array([[1, 2], [3, 4]])
comparison = a1 == a2
equal_arrays = comparison.all()
print(equal_arrays)
38. import numpy as np
a1 = np.array([[11, 2], [3, 4]])
a2 = np.array([[1, 2], [13, 4]])
print(np.greater(a1,a2))
39. import numpy as np
a1 = np.array([[11, 2], [3, 4]])
print(a1.sum())
40. mport numpy as np
a1 = np.array([[11, 2], [3, 4]])
print(a1.shape)
41. import numpy as np
matrix= np.arange(1,9).reshape((3, 3))
print(matrix)
print(matrix.shape)
42. import numpy as np
matrix= np.arange(1,10).reshape((3, 3))
print(matrix)
print(matrix.shape)
43. import numpy as np
n_arr = np.array([75.42, 42.45, 60.0])
n_arr[n_arr > 50.] = 100.50
print(n_arr)
44. import numpy as np
n_arr = np.array([-75.4, 42.45, 60.0])
n_arr[n_arr < 0] = 0
print(n_arr)
a2=np.delete(n_arr,[0])
print(a2)
45. import numpy as np
n_arr = np.array([-75.4, 42.45, 60.0])
print(n_arr[::-1])
46. import numpy as np
n_array = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
diag = np.diagonal(n_array)
print(“Diagonal elements:”, end= ‘’)
print(diag)
print(“Sum of diagonal elements:” , end= ‘’)
print(sum(diag))
47. import numpy as np
n_array = np.array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
print(“Numpy Matrix is:”)
trace = np.trace(n_array)
print(“\nTrace of given 3X3 matrix:”)
print(trace)
48. import numpy as np
arr1 = np.array([[1, 2, 3],
[4, 0, 6],
[7, 0, 9]])
print(np.count_nonzero(arr1))
49. import numpy as np
# Create 3D-numpy array of 2 rows and 2 columns
arr1 = np.arange(3 * 2 * 2).reshape(3, 2, 2)
print(“Original 3D array:\n”, arr1)
# Create 2D diagonal array
diag_arr1 = np.diagonal(arr1, axis1 = 1, axis2 = 2)
print(“2D diagonal array:\n”, diag_arr1)
50. import numpy as np
# Create 3D-numpy array of 2 rows and 2 columns
arr3 = np.arange(3 * 2 * 3).reshape(3, 2, 3)
print(“Original 3D array:\n”, arr3)
# Create 2D diagonal array
diag_arr3 = np.diagonal(arr3, axis1 = 1, axis2 = 2)
print(“2D diagonal array:\n”, diag_arr3)
15.2 Select the most appropriate answer for the following questions:
1. Which of the following is correct for full form of NumPy?
a. Numbers in Python
b. Numbering in Python
c. Numerical Python
d. None of these
2. Which of the following is most important object defined in NumPy?
a. array
b. ndarray
c. nd_array
d. None of these
3. Which of the following is used to find the largest element in NumPy
array?
a. nparray.maximum()
b. nparray.max()
c. max(nparray)
d. None of these
4. Which of the following can be used to change the shape of a NumPy
array?
a. shape()
b. reshape()
c. shape
d. None of these
5. Which of the following is used to display the number of rows and
columns of a NumPy array?
a. shape
b. shape()
c. reshape()
d. None of these
6. Which of the following can be used to change NumPy array into a
list?
a. list(nparray)
b. list.nparray
c. nparray.list()
d. None of these
7. Which of the following is the correct number of minimum number of
arguments to be passed in empty() function for NumPy arrays?
a. 2
b. 3
c. 4
d. None of these
8. Which of the following is returned by size() function in Numpy?
a. Shape of the array
b. Number of elements in the array
c. Dimensions of the array
d. None of these
9. Which of the following is the function of NumPy.array(list)?
a. Convert a list into array
b. Convert an array into list
c. Invalid function
d. None of these
10. Which of the following is used to print the dimensions of a NumPy
array?
a. size
b. shape
c. ndim
d. None of these
Q. 15.3 State whether the statements give below are True or False:
i. dtype can be used to find the dayatype of the numpy array.
ii. comparison.all() function returns the result of the overall comparison
of 2 numpy arrays.
iii. It is compulsory to specify the datatype of numpy array in full()
function.
iv. Corresponding elements of 2 numpy arrays can be added using +
operator.
v. The function greater() returns the True False values for each element
of the 2 arrays compared.
vi. The number of elements of numpy array of only 2 dimensional array
can be found by size.
vii. A 3D array can be created only using reshape() function in NumPy.
viii. nparray + n will increment all element of nparray by n.
ix. nparray.diagonal(array) is used to print the list of diagonal elements in
the array.
x. A numpy array cannot be flattened.

Answers: 15.1
1. Empty 1D Array
[35446 47374]
An array of 2 integer elements will be created. The 2 values will be
garbage.
2. Empty 1D Array
[3.5446e-11 4.7374e-34]
An array of 2 floating-point elements will be created. The 2 values
will be garbage.
3. Empty 1D Array
[True True]
An array of 2 boolean elements will be created. The 2 values will be
either True or False.
4. Empty 2D Array
[[35446 47374374 26356353]
[436432 34343434 332334]]
A two-dimensional array of size 2X3 of integer elements will be
created. The array values will be garbage.
5. Empty 2D Array
[[3.5446e-11 4.7374e-34]
[3.9436e-10 5.7374e-31]
[5.5346e-18 2.7874e-34]]
A two-dimensional array of size 3X2 of floating-point elements will
be created. The array values will be garbage.
6. Empty 2D Array
[[True True]
[False True]]
A two-dimensional array of size 2X2 of boolean elements will be
created. The array values will be garbage.
7. Full 1D Array
[10 10 10]
An array of 3 integer elements will be created. The value of each
element will be 10.
8. Full 1D Array
[10.5 10.5]
An array of 2 floating-point elements will be created. The value of
each element will be 10.5. There is no to explicitly mention dtype as
float.
9. Full 1D Array
[True True]
1
An array of 2 boolean elements will be created. The 2 values will be
True. There is no to explicitly mention dtype as bool.
ndim prints the dimensions of the array i.e. 1D.
10. Full 2D Array
[[5 5 5]
[5 5 5]]
A two-dimensional array of size 2X3 of integer elements will be
created. The value of each element will be 5.
11. Full 2D Array
[[7.5 7.5]
[7.5 7.5 ]
[7.5 7.5]]
A two-dimensional array of size 3X2 of floating-point elements will
be created. The value of each element will be 7.5.
12. Full 2D Array
[[True True]
[True True]]
A two-dimensional array of size 2X2 of boolean elements will be
created. The value of each element will be True.
13. 1D Array with zeroes
[0 0 0]
An array of 3 integer elements will be created. The value of each
element will be zero.
14. 1D Array with zeroes
[0. 0.]
An array of 2 floating-point elements will be created. The value of
each element will be 0.0.
15. 1D Array with zeroes
[False False]
An array of 2 boolean elements will be created. The 2 values will be
False (zero).
16. 2D Array with zeroes
[[0 0 0]
[0 0 0]]
A two-dimensional array of size 2X3 of integer elements will be
created. The value of each element will be 0.
17. 2D Array with zeroes
[[0. 0.]
[0. 0. ]
[0. 0.]]
A two-dimensional array of size 3X2 of floating-point elements will
be created. The value of each element will be 0.0.
18. 2D Array with zeroes
[[False False]
[False False]]
A two-dimensional array of size 2X2 of boolean elements will be
created. The value of each element will be False.
19. 1D Array with ones
[1 1 1]
An array of 3 integer elements will be created. The value of each
element will be 1.
20. 1D Array with ones
[1. 1.]
An array of 2 floating-point elements will be created. The value of
each element will be 1.0.
21. 1D Array with ones
[True True]
An array of 2 boolean elements will be created. The 2 values will be
True (1).
22. 2D Array with ones
[[1 1 1]
[1 1 1]]
A two-dimensional array of size 2X3 of integer elements will be
created. The value of each element will be 1.
23. 2D Array with ones
[[1. 1.]
[1. 1. ]
[1. 1.]]
A two-dimensional array of size 3X2 of floating-point elements will
be created. The value of each element will be 1.0.
24. 2D Array with ones
[[True True]
[True True]]
A two-dimensional array of size 2X2 of boolean elements will be
created. The value of each element will be True.
25. [[2, 8, 9, 4],
[9, 4, 9, 4],
[4, 5, 9, 7],
[2, 9, 4, 3]]
16
numpy.array() function creates an array with given elements.
The arr1.size prints the number of elements in the array.
26. 2
The count() function returns the count of 2 in the array.
27. 0
The count() function should return the count of 2,9 in the array. But
there is space after, so the result is 0.
28. 2
The count() function returns the count of 2, 9 in the array.
29. 1
The count() function returns the count of 2, 9, 4, 3 in the array.
30. False
True
The tolist() function checks whether a particular row exists in the
given array or not. [1, 2, 3] exists in arr1 here while [1, 2, 3, 4] does
not exist in arr1.
31. 5
The argmax(array) function returns the argument which is having
maximum frequency of occurrence. Here 5 has highest frequency of 3.
32. 3
The argmax(array) function returns the argument which is having
maximum frequency of occurrence. Here all have same frequency. So
smallest element is returned as answer.
33. 3 4 5 11 12
The argmax(array) function returns the argument which is having
maximum frequency of occurrence. Here all having the same
frequency are given in sorted order. So here all elements with
maximum frequency are printed using for loop.
34. True
False
The in operator can be used to check whether the given element is
present in the array or not. Here 2 is present while 10 is not present in
array.
35. [2 3 10 4 1 6]
The 2D array is flattened to one dimensional arrays using function
flatten().
36. [[True True]
[True True]]
The == compares each element of the array and returns True or False.
37. True
The == compares each element of the array and returns True or False.
The comparison.all() function compares all values and returns True if
all values are same, False otherwise.
38. [[True False]
[False False]]
The greater function compares each element of the array and returns
True if element of first argument is True, False otherwise.
39. 20
The function sum() returns the sum of all elements of the array.
40. (2,2)
The attribute shape of the array returns the number of rows and
columns of the array.
41. ValueError: total size of array must be unchanged
Here numbers are to be generated using function arrange() and an
array is to be created with 3 rows and 3 columns using reshape()
function. The number of rows and columns are printed using shape
attribute.
Here the numbers generated are 8 while size of the array is specified
as 3X3 i.e.9.
42. [[1,2,3],
[4,5,6],
[7,8,9]]
(3,3)
Here numbers are to be generated using function arange() and an array
is to be created with 3 rows and 3 columns using reshape() function.
The number of rows and columns are printed using shape attribute.
Here 9 numbers are generated and corresponding array and size are
printed.
43. [100.5 42.5 100.5]
The values of elements greater than 50.5 are replaced with 100.5.
44. [0. 42.5 60.5]
[0. 60.5]
The values of negative elements are replaced with 0. Then it is deleted
using delete() function and the resultant array is stored in array a2. It
can be stored in same array n_arr as well. The delete() function takes
elements as a list to be removed. It removes only first occurrence of
the given elements.
45. [60.5, 42.5, -75.0]
The array is printed in reverse.
46. Diagonal elements: [1 5 9]
Sum of diagonal elements: 15
The function diagonal() returns the diagonal elements as a list.
The function sum() is used to find sum of the elements of the list of
diagonals.
47. 15
The function trace() returns the sum of diagonal elements of a matrix.
Here diagonal elements are 1, 5 and 9.
48. 7
The function count_nonzero() returns the number of non-zero values
of arr1.
49. Original 3D array:
[[[ 0 1]
[2 3]]
[[4 5]
[6 7]]
[[8 9]
[10 11]]]
2D diagonal array:
[[0 3]
[ 4 7]
[8 11]]
Here a 3 dimensional array of size 3X2X2 is created using numbers
from 0 to 11, i.e total 12. The array is printed and the diagonals of the
arrays for each 2 dimensions are printed.
50. Original 3D array:
[[[ 0 1 2]
[ 3 4 5]]
[[ 6 7 8]
[9 10 11]]
[[ 12 13 14]
[15 1617]]]
2D diagonal array:
[[ 0 4]
[6 10]
[12 16]]
Here a 3 dimensional array of size 3X2X3 is created using numbers
from 0 to 17, i.e total 18. The array is printed and the diagonals of the
arrays for each 2 dimensions are printed.
15.2
1. c
2. b
3. c
4. b
5. a
6. a
7. a
8. b
9. a
10. c
15.3
i. True
ii. True
iii. False
As the value specified indicate s the datatype, no need to explicitly
mention the datatype in function full().
iv. True
v. True
vi. False
Size returns the total number of elements of a numpy array of any
dimension.
vii. False
A 3D array can be specified using nparray() directly as well.
Reshape() function is used when the elements are to be generated.
viii. True
ix. True
x. False
A numpy array can be flattened using function flatten().
CHAPTER 16
Databases
In this chapter you will be able to check how much you know about
Databases in Python.

Key Points
SQLite3 is used to handle databases on local system.
It is written in ANSI-C and has zero configuration cost.
It is self-contained database. There is no need to use a server.
It follows ACID transactions.
It supports data types as text, integer, real, null and BLOB.
CONNECT command is used to create and open a database.
CREATE command is used to create a table in the database.
SELECT command is used to retrieve specific rows of a table.
UPDATE command is used to change some values in the rows of the table.
DELETE command is used to delete rows from the table.
DROP command is used to drop a table from a particular database.
QUIT is used to end the session.
DUMP is used to save the content of the database to a text file.

Questions
16.1 What will be the output of the following commands in SQLite3?
1. sqlite3> studentDB.db
2. sqlite3> .quit
3. sqlite3 > studentDB.db.dump > savedb.sql
4. sqlite3> attach database studentDB.db as ‘Student’;
5. sqlite3> detach database ‘Student’ from studentDB.db;
6. sqlite3> .tables
7. sqlite3> create table result (roll int primary key not null, name text not
null, subject text not null, marks real not null );
8. sqlite3> drop table studentDB.result;
9. sqlite3> insert into result values (101, ‘Vikas’, ‘Maths’, 99);
10. sqlite3> select * from result;
11. sqlite3> select marks from result;
12. sqlite3> update result set marks=100 where roll=201;
13. sqlite3> update result set marks=100;
14. sqlite3> delete from result where roll=101;
15. sqlite3> delete from result;
16. sqlite3> delete from result where marks<10;
17. sqlite3> select name from result where marks>=60 and name like
‘v%’;
18. sqlite3> select * from result where roll in (101, 110);
19. sqlite3> select count(*) as ‘First class’ from result where marks>60;
20. sqlite3> select name, count(*) as ‘First class’ from result where
marks>60 group by name;
16.2 Select the most appropriate answer for the following:
1. Which of the following is the correct full form of BLOB in SQLite3?
a. Binary Large Object
b. Bitwise Logical Object Blog
c. Bitwise Large Object
d. None of these
2. Which of the following is not a storage class in SQLite3?
a. text
b. null
c. blob
d. None of these
3. In which of the following conditions the index should be avoided in
SQLite3?
a. for tables that change frequently
b. for small tables
c. columns with high number of NULL values
d. All of these
4. Which of the following is used for recovering data in SQLite3?
a. SQLITE DELETE
b. SQLITE SECURE DELETE
c. Both of these
d. None of these
5. Which of the following is true about SQLite3?
a. It is written in ANSI-C
b. It is serverless
c. It has zero configuration cost
d. All of these
6. Which of the following is not true about SQLite3?
a. It is heavy weight
b. It is a self-contained database
c. It follows ACID
d. None of these
7. Which of the following command is used to insert data into a database
in SQLite3?
a. INSERT
b. INSERT INTO
c. INSERT FOR
d. None of these
8. Which of the following is not a command in SQLite3?
a. SELECT
b. UPDATE
c. DELETE
d. CHANGE
9. Which of the following operator can be used for combining the results
of queries in SQLite3?
a. COMBINE
b. +
c. UNION
d. All of these
10. Which of the following operator does not ignore duplicate values in
result of the queries in SQLite3?
a. UNION
b. UNION ALL
c. Both of these
d. None of these
16.3 State whether the given statements are True or False?
i. Using SQLite3, data cannot be stored on local system
ii. The function close()in SQLite3 is used for closing the current query.
iii. The function connect() is used only for connecting to the database.
iv. A query in SQLite3 can be executed using sqlite3.execute(query).
v. The function execute(query) fetches the data related to the query from
the database.
vi. A database can be disconnected using function disconnect() in
SQLite3.
vii. SQLite3 is used for both front end and back end for databases in
Python.
viii. Rollback; is a valid command in SQLite3.
ix. SQLite3 is case insensitive.
x. SQLite3 does not have Boolean datatype.

ANSWERS

16.1
1. A database named studentDB.db will be created.
2. quit command is used to come out of the SQLite3 prompt.
3. The complete studentDB is exported to file savedb.sql using dump
command.
4. It creates an alias for studentDB as Student.
5. It detaches the alias name Student from the database StudentDB.
6. It displays all the tables in the current open database.
7. It creates a table result with columns as roll, name, subject, marks.
8. It drops the table result from database stuentDB.
9. It inserts a row with given values in table result.
10. It returns all the rows from table result.
11. It returns the marks from all rows from table result.
12. It changes the marks to 100 in the row where roll number is 201 in
table result.
13. It changes marks in all the rows to 100 in table result.
14. It deletes the row from table result where roll number is 101.
15. It deletes all rows of table result.
16. It deletes the rows from table result where marks are less than 10.
17. It returns the rows of the table where name starts from letter v and
marks>60.
18. It returns all the rows of table result where roll number is not either
101 or 110.
19. It returns the count of number of students in result table where
marks>60.
20. It returns the name of students in table result where marks are greater
than 60.

16.2
1. a
2. d
3. d
4. b
5. d
6. a
7. b
8. d
9. c
10. b

16.3
i. False, it can be stored on local system.
ii. False, the function close()is used for closing the database.
iii. False, the function connect() is used for opening, creating and
connecting to the database.
iv. True
v. True
vi. False. The function close() disconnects the database in SQLite3.
vii. False. It provides only back end.
viii. True
ix. True
x. True. True and False are stored a integers 1 and 0 respectively
Appendix A: Python keywords and
their use
Table 1
Keyword Meaning with example

and It is a binary logical operator which returns False if any one of the
operand is False and returns the value of the last operand if all its
operands are True.
>>> 47 and 56
>>>56
as It is used to create a user defined name called alias while importing
a module.
>>> import math as m
>>>print(m.cos(0))
>>>1.0
assert It is used to debug the internal state of some assumptions. It is
followed by a condition. Nothing happens if the condition is True
but AssertionError is raised if the condition is False.
>>> x=10
>>>assert x>=10
>>>assert x<10
Traceback (most recent call last):
File “string”, line 1, in <module>
assert x<10
AssertionError
An error message can also be passed with assert to be printed
with Assertionerror.
>>>assert x<10, “x is not less than 10”
Traceback (most recent call last):
File “string”, line 1, in <module>
assert x<10
AssertionError: x is not less than 10

break It is a statement which ends the current loop and takes the control
out of the current loop.
for i in range(10):
if i%3==0:
break
else:
print(i)
The loop is to vary from 0 to 9. But 3 is divisible by 3 and hence
break causes the loop to exit. So only 0 1 2 are printed.
class It is used to create a class with related data members and methods
to operate on that data.
class C1:
def __init__():
…..
def _method1():
….

continue It is used to control the flow in a loop. Wherever continue appears,


the current iteration of the loop is ended and loop continues to
next iteration.
for i in range(10):
if i%3==0:
continue
else:
print(i)
The loop is to vary from 0 to 9. But 3, 6 and 9 are divisible by 3
and hence continue skips printing 3, 6 and 9. So only 0 1 2 4 5 7
8 are printed.
def It is used to define a user-defined function.
def sum(a,b):
print(a**2+b**2)
del Everything is an object in Python. del is used to delete the
reference to an object.
>>>x=10
>>>del x
>>>x
Traceback (most recent call last):
File “<string>”, line 1, in <module>
x
NameError: name ‘x’ is not defined
if These are used in if-elif-else ladder.
else a1= 10
elif if a>0:
print(“a is positive”)
elif a==0:
print(“a is zero”)
else:
print(“a is negative”)
Output will be “a is positive”

except These are used in handling exceptions in Python. The statements


raise which can cause exceptions or errors are placed inside a try.. except
try block. The exception is raised using raise.
finally try:
a = int(input())
b= a-5
c=a/b
raise ZeroDivisionError(“cannot divide”)

raise ValueError(“Wrong input”)


except ZeroDivisionError:
raise
except ValueError:
raise
finally:
print(c)
When value of a is input as 5:
Traceback (most recent call last):
File “<string>”, line 1, in <module>
c=a/b
ZeroDivisionError: cannot divide
When value of a is input as a string:
Traceback (most recent call last):
File “<string>”, line 1, in <module>
A=int(input())
ValueError: wrong input

False It is a truth value in Python. A boolean(or logical) operation or


comparison operation may result in a False value. It means 0.
>>> 5>7
>>> False
for It is a statement which allows us to repeat a set of statements
together for a number of times.
for i in range(1,6,2):
print(i)
The loop variable i varies from 1 to 5 (6 not included) and is
incremented by 2. It prints 1,3 and 5.

global It is used to declare that a variable inside the function is global


i.e. outside the local scope of function.
g_var = 20
def fun_read():
print(g_var)
def fun_write():
global g_var
g_var =200
fun_read()
fun_write()
fun_read()
The output will be:
20
200
from import is used to import all attributes of modules into the current
import namespace.
>>>import math
We need to use name of module with evry attribute for using:
>>>print(math.pi)
If we want to import only specific attribute from the module, we
can use from..import
>>> from math import pi
Then we can directly write only the name of the attribute
>>> print(pi)

in It is used to test if a value is contained in a sequence (list, tuple,


string etc.). It returns True if the value is present and False if it is
not.
>>> 6 in [1,3]
>>> False
is It is used in Python to test identity of an object. It returns True if two
variables are referring to the same object.
>>> 5 is 6
>>> False
>>> True is True
>>> True
lambda It is used to create a function with no name and return statement.
It contains only only expression for evaluation:
>>> a = lambda a1: a1*2
>>> for i in range(1,3):
>>> print(a(i))
It will print
1
4
6

None It is a special constant in Python. It represents that the value is


either null or is missing. It is not False i.e. 0 or an empty list,
dictionary, string etc.
A function returns None if there is no return statement in it.
We can assign a particular variable a value None:
x=None

nonlocal It is used to declare a variable inside a nested function which is


not local to it.
def fun_outer():
x= 10
def fun_inner():
nonlocal x
x =20
print(“Inner function value of x: ”, x)
fun_inner()
print(“Outer function value of x: ”, x)
fun_outer()
The output will be:
Inner function value of x: 20
Outer function value of x: 20

not It is a unary logical operator which returns False if the operand is


True and returns True if the operand is False.
>>> not(47 or 56)
>>>False
or It is a binary logical operator which returns False if all of the
operands are False and returns the value of the first True operand
and does not evaluates rest.
>>> 47 or 56
>>>47
pass It is a null statement in Python. It is just a placeholder. It is used
in creating empty function or class:
def f1():
pass
class C:
pass
return It is used inside a function. The function returns the value and exits
when there is a return statement.
def f(a,b):
c = a+b
if c>100:
return c
c = a-b
print(c)
>>> f(34,90) will return after printing 124.

True It is a truth value in Python. A boolean(or logical) operation or


comparison operation may result in a True value. It means 1.
>>> 5<7
>>> True
while It is a statement which allows us to repeat a set of statements
together for a number of times.
i=1
while a<6:
print(i)
i=i+2
The loop variable i varies from 1 to 5 (6 not included) and is
incremented by 2. It prints 1,3 and 5.

with It is used to wrap the execution of a block of code within


methods defined by the context manager. In a nested block, one
needs to execute the methods __exit__ and __enter__. These are
implemented in class called context manager.
with open(“a.txt”, ‘w’) as file1:
file1.write(‘Writing in the file’)
It automatically closes the file after the nested block of code.

yield It is used inside a function like a return statement and it returns a


generator which generates one item at a time. Thus it saves a lot of
memory.
def gen():
for i in range(3):
yield i*i
g=gen()
for a in g:
print(a)
This will print
0
1
4
Appendix B: Operators in Python and
their precedence
Table 2
Operator Description No. of operands Example

** Exponentiation (raise to the power) 2 2**3=23=8

~ Complement 1 ~(42) = False

+ Unary plus 1 +45


- Unary minus 1 -67

* Multiply 2 5*4=20
/ Divide 2 40/6=6.66

% Modulo 2 40%3= 1

// Floor division 2 40//6=6

+ Binary addition 2 78+10=88


- Binary subtraction 2 78-10=68

>> Bitwise Right shift 2 4>>1 = 2

<< Bitwise Left shift 2 4<<1= 8


& Bitwise ‘AND’ 2 4&1 = 0

^ Bitwise exclusive ‘OR’ 2 4^1 = 5

| Logical ‘OR’ 2 4|1 = 5

Comparison operators
<= Less than or equal to 2 5<=8 = True

< Less than 2 8 <7 = False

> More than 2 7 >8 = False

>= More than or equal to 2 9>=8 = True

Equality operators
== Equal to 2 6==6 True

!= Not equal to 2 6!=7 False

Assignment operators

= Assignment 2 x=5 →x=5


%= 2 x%=2 →x=1

*= 2 x*=3 → x= 3

**= 2 x**=3 → x=27

/= 2 x/=2 → x=13.5

//= 2 x//=3 → x=4

-= 2 x-=1 → x=3
+= 2 x+=2 → x=5

is Identity operators 2
2

is not in Membership operators 2


2

not or and Logical operators 1


1
2
Appendix C: Libraries in Python &
common functions
Table 3
Library Common functions

BeautifulSoup It provides functions for xml and html parsing

IPython It is a python prompt on steroids


matplotlib It is a numerical plotting library

nltk It helps in string manipulation (Natural Language Toolkit)

Nose It is a testing framework for Python


NumPy It provides advances mathematical functions

Pillow It provides functions for handling images

Pygame It provides functions for 2 dimensional programs for games


Pyglet It is a 3 dimensional animation and gaming creation engine

pyGtk It is a GUI toolkit

pyQT It is a GUI toolkit


pywin32 It provides some useful methods and classes for interacting

with windows

Requests It is library which provides functions for http

Scapy It is a packet sniffer and analyser for python

SciPy It is a library of algorithms and mathematical tools


Scrapy It provides functions for webscraping

SQLAlchemy It is a database library

SymPy It provides functions for algebraic evaluation, differentiation,


expansion, complex numbers, etc.

Twisted It deals with network application development


wxPython It is a GUI toolkit
Bibliography
Following books/websites have been referred for learning Python along
with
Python documentation:
www.python.org
www.learnpython.org
www.javapoint.com
www.pynative.com
www.sqlitetutorial.net/
www.realpython.com
www.tutorialpoints.com/python
www.w3resource.com/python
Learning with Python by Jeffrey Elkner, Dreamtech publications
Core Python Programming by R Nageswara Rao, Dreamtech publications
Computation and Programming Using Python, by John V. Guttag, Prentice
Hall of India
MODEL TEST PAPER 1
Attempt all questions
Maximum Marks 100 Time allowed : 3 Hrs
Q.1(a) Explain various forms of ‘for’ loop in Python with suitable
examples. (5)
Q.1(b) Explain various operations which can be performed on a dictionary
in Python. (5)
Q.2(a) Explain various bitwise operators in Python. Explain the functioning
of each with suitable examples. (5)
Q.2(b) Explain differences between a list and a tuple in Python. (5)
Q.3. Write and explain the output of the following commands in Python:
(4×5=20)
a. >>>20+5|2>>2**2%3
b. n=0
q= “What is the result of 2*10, 4*5?”
while n!= “20”:
n=input(q)
print("Correct answer:")
c. >>>list1= [4,2,3,4,5,4,6,7]
>>>print(list1.count(4))
d. >>>n= [“Aamir” , “ Salman” , “ Shahrukh” ]
>>>print(n[-1][-2])

Q.4 Find out errors in the following programs in Python: (4×5=20)


a. >>> n = [1, 2, 3, 0, Red]
b. enum = []
for n in l:
if n % 2 == 0
enum.append(n)
return enum
c. >>> n = [1, 2, 3, 4]
>>> for i in range(1,5):
>>> print(n[i])
d. >>>print(hello how are you?)
Q.5 (4×10=40)
a. Write a program in Python to divide the contents of a list into two lists
with even and odd numbers separately.
b. Write a program in Python which inputs distance in feet and prints it
in inches, yards and miles.
c. Write a program in Python to find sum of series: x1 + x2+....+xn.
d. A prime number is an integer greater than 1 that is divisible only by 1
and itself. For example, 2 and 7 are prime numbers. Write a program
in Python which inputs a number from user and then displays a
message indicating whether the number is prime or not.
Answers Model Test Paper 1:
1(a) There are many forms in which we can use for loop. First form is:
for variable1 in range(terminating_value):
Here the initial value of loop variable variable1 is zero(0) by default
and the loop variable changes value from 0 upto terminating_value
(not including terminating_value). The value of loop variable is
incremented by 1.
For example, to find the sum of the series: 0+1+2+3 for loop will be:
sum=0
for i in range(4):
sum+=i
print(sum)
The second form is:
for variable1 in range(initial_value, terminating_value):
Here the initial value of loop variable variable1 can be specified by the
user and the loop variable changes value from initial_value upto
terminating_value (not including terminating_value). The value of
loop variable is incremented by 1.
For example, to print the numbers from 101 to 105, for loop will be:
for i in range(101,106):
print(i)
Third form is:
for variable1 in range(initial_value, terminating_value,
update_value):
Here the initial value of loop variable variable1 can be specified by the
user and the loop variable changes value from initial_value upto
terminating_value (not including terminating_value). The value of
loop variable is updated by given update_value.
For example, to find the sum: 2+4+6+8+10, for loop will be:
sum=0
for i in range(2,11,2):
sum+=i
print(sum)
Fourth form is:
for variable1 in list:
This is for accessing each value in the list one by one.
For example, to find the sum of all elements in a given list, for loop
will be:
sum=0
list1= [11,20,13,47]
for element in list1:
sum+=element
print(sum)
(b) In a dictionary, many {key:value} pairs are stored. For example
>>>dict= {‘First’:1, ‘Second’:2, ‘Third’:3}
This means in dictionary dict, value is 1 for key ‘First’, value is 2 for
key ‘Second’ and value is 3 for key ‘Third’.
The main operations on a dictionary are storing a value with some key
and extracting the value given the key.
>>>dict[‘First’]
1
We can also change the value associated with a key:
dict[‘First’]= 13
>>>dict[‘First’]
13
We can print all keys of a dictionary in a list using list(dict.keys())
>>>print(list(dict.keys()))
[“First”, “Second”, “Third”]
We can sort the keys using sorted(dict.keys())
>>>print(sorted(dict.keys()))
[‘First’, ‘Second’, ‘Third’]
We can also check whether the value is present in the dictionary:
>>>“First” in dict
True
A key-value pair can be deleted using del dict[key]
>>>del dict[‘Second’]
>>>dict
{‘First’:1, ‘Third’:3}
2(a) Various bitwise operators in Python are:
&: It returns bitwise ANDing of two numbers: 3&4 means 011 & 100,
gives 000 i.e.0
| : It returns bitwise ORing of two numbers: 3|4 means 011 | 100, gives
111 i.e. 7
^: It returns bitwise XORing of two numbers 3^4 means 011 ^ 100,
gives 111 i.e. 7
>>: It shifts the number right by n bits. 4>>1 gives 010 i.e. 2.
<<: It shifts the number left by n bits. 4<<1 gives 1000 i.e. 8
2(b) In a list the elements are separated by comma and enclosed in square
brackets while in a tuple, the elements are not enclosed in square
brackets but separated by comma. A list is mutable, i.e. we can change
the contents of a list while the contents of a tuple cannot be changed.
3(a) 25
3(b) The loop asks the user a question “What is the result of 2*20 and 4*5”
until the user enters 20 as correct answer. The input is taken as a string,
so written in “”.
3(c) 3 (4 appears three times in given list)
3(d) k (Last string is ‘Shahrukh’ and second last character in it is ‘k’)
4(a) Since Red is a string, so it should be put in single or double quotes.
4(b) Semicolon(:) is missing after if condition
4(c) The index of list elements vary from 0 to length of list-1. So i should
vary from 0 to 3 instead of 1 to 4.
4(d) The string arguments to print function should be in pair of parentheses
enclosed in single or double quotes.
5(a) # A program to divide a list into even and odd lists separately
l=[1,2,3,4]
e=[]
o=[]
for i in l:
if i%2==0:
e.append(i)
else:
o.append(i)
print(e)
print(o)
The output will be:
[2,4]
[1,3]
5(b) # A program to convert distance in feet to inches, yards and miles
d_ft = int(input(“Input distance in feet: “))
d_inches = d_ft * 12
d_yards = d_ft / 3.0
d_miles = d_ft / 5280.0
print(“The distance in inches is %i inches.” % d_inches)
print(“The distance in yards is %.2f yards.” % d_yards)
print(“The distance in miles is %.2f miles.” % d_miles)
Output:
Input distance in feet: 5
The distance in inches is 60 inches.
The distance in yards is 1.67 yards.
The distance in miles is 0.00 miles.
5(c) # A program to find sum of series: x1+x2+....+xn.
n = int(input(“Enter terms: “))
x = int(input(“Enter x: “))
t=1
sum = 0
while t<=n:
sum = sum + x**t
t = t+1
print(sum)
Output:
Enter terms: 3
Enter x: 2
12
5(d) # A program to check whether the number is prime or not.
n = int(input(‘ Enter a number’))
if n == 2:
print(n, “ is a prime number”)
elif n%2 == 0:
print(n, “ is not a prime number”)
else:
prime=1
i =3
while i<= n/2:
if n % i == 0:
print(n, ‘is not a prime number’)
prime =0
break
i = i+2
if prime==1:
print(n, ‘ is a prime number’)
Output:
Enter a number: [2]
2 is a prime number
Enter a number: 40
40 is not a prime number
MODEL TEST PAPER 2
Attempt all questions
Maximum Marks 100 Time allowed : 3 Hrs
Q.1(a) Explain various forms of ‘if’ statement in Python with suitable
examples. (5)
Q.1(b) Explain any 5 operations which can be performed on a list in Python
with suitable examples. (5)
Q.2(a) Explain various relational operators in Python. Explain the
functioning of each with suitable examples. (5)
Q.2(b) Explain difference between break and continue in Python. (5)
Q.3 Write and explain the output of the following commands in Python:
(4×5=20)
a. >>> lst = [20,31,42]
>>> lst[1:2] =[3,4,5,6]
>>> print(lst)
b. >>>8^4<<3%2
c. >>> “how was your exam ?”. split()
d. >>> value=-100
if value1:
print(“True”)
else:
print(“False”)

Q.4 Select the most appropriate answer for the following in Python:
(5×2=10)
a. Which of the following function returns the hash value of an
object?
i. hash()
ii. id()
iii. ord()
iv. None of these
b. Which of the following function returns a floating-point number
constructed from a number or a string?
i. eval()
ii. float()
iii. bin()
iv. None of these
c. Consider using open function for opening a file:
filename = input(‘Enter a filename : ‘)
f1 = open(filename, ‘mode’)
Which of the following modes is used when a file is to be opened for
reading and writing?
i. rw
ii. w+
iii. r+
iv. w
d. Which of the following is not an option in “selectmode” in Listbox
widget?
i. browse
ii. single
iii. multiple
iv. None of these
e. Which of the following is an event handler?
i. action()
ii. bind()
iii. pack()
iv. None of these
Q.5 (5×10=50)
a. Write a function in Python which removes duplicate elements from a
given list.
b. Write a program to check whether the given number is an Armstrong
number or not. A number is an Armstrong number if the number is
equal to the sum of the cube of its digits.
c. Write a recursive function in Python which finds the number of digits
in a positive integer.
d. Write a program which writes text into a file and prints the total
number of characters after reading from the file.
e. Write a function in Python to count the number of elements in a list
within a specified range.
Answers Model Test Paper 2:
1(a) Various forms of ‘if’ statement in Python:
Simple if condition:
if condition:
if statement block
The statements in if statement block are executed only of the condition
is True.
Example: To print the number only if it is less than 100.
n=int(input())
if n<100:
print(n)
Output:
For n = 40, 40 will be printed.
For n=101, nothing will be printed.
if-else condition:
if condition:
if statement block
else:
else statement block
The statements in if statement block are executed only if the condition
is True. Otherwise, the statement block in else part is executed.
Example: To print the square of a number if it is more than 10, cube of
the number otherwise.
n=int(input())
if n>10:
print(n**2)
else:
print(n**3)
Output:
For n=11, output will be: 121
For n=3, output will be: 27
if-elif ladder
It is also possible that there are many different values of a single
variable based on which different set of statements are to be executed
which are mutually exclusive, then if-elif ladder is used.
if condition1:
if statement block 1
elif condition2:
elif statement block 2
elif condition3:
elif statement block 3
…..
else:
else statement block
Example: To print the position (1st, 2nd 3rd) based on a given number,
error otherwise.
n=int(input())
if n==1:
print(‘1st’)
elif n==2:
print(‘2nd’)
elif n==3:
print(‘3rd’)
else:
print(‘error’)
Output:
For n=1, output ill be: 1st
For n=9, output will be: error
1(b) Various operations on a list in Python are:
i. list.append : It is used to append the value at the end of the given list.
>>>list1 = [1,12,3]
>>>list1.append(5)
>>>list1
[1,12,3,5]
ii. list.sort() to sort the elements in the increasing order.
>>>list1.sort()
>>>list1
[1,3,5,12]
iii. We can also reverse the order of the elements of the list using the
function list.reverse().
>>>list1.reverse()
>>>list1
[12,5,3,1]
iv. We can insert a value in the list at a particular index using the function
list.insert (index1,value1). Value value1 will be inserted at given index
index1 in given list1.
>>>list1.insert(1,7)
>>>list1
[12,7,5,3,1]
v. We can use the function list.index(value1) to know the index of a
particular value. It will return the index of value1.
For example, to find the index of 12 we need to use:
>>>list1.index(12)
0

2(a) In Python, there are many relational operators :


< (less than) : x<y which returns True if value of x is less than value of
y.
For example, 4<5 returns True while 13<4 returns False.
<=(less than or equal to) : x<=y which returns True if value of x is less
than or equal to the value of y.
For example, 4<=4 returns True while 13<=4 returns False.
(greater than): x>y which returns True if value of x is greater than
value of y.
For example, 14>5 returns True while 3>14 returns False.
>= (greater than or equal to): x>=y which returns True if value of x is
greater than or equal to the value of y.
For example, 14>=14 returns True while 13>=4 returns False.
(equality): x==y which returns True if value of x is equal to value of y.
For example, 40==40 returns True while 13==4 returns False.
!= (inequality): x!=y which returns True if value of x is not equal to
value of y.
For example, 4!=5 returns True while 4!=4 returns False.
2(b) These both are used in any loop control statement: while or for. break
terminates the loop and comes out of the current loop while continue
skips the statements in the current loop and moves to execution of the
loop with next iteration. For example:
for a in range(1,6):
if a%4==0:
break
else:
print(a,)
Output: 1 2 3 since the loop breaks when a is 4.
for a in range(1,6):
if a%4==0:
continue
else:
print(a,)
Output: 1 2 3 5 since loop statement print(a,) is skipped when a is 4.
3(a) [20, 3, 4, 5, 6, 42]
3(b) 0
3(c) [‘how’, ‘was’, ‘your’, ‘exam’, ‘?’]
3(d) True
4(a) (i)
4(b) (ii)
4(c) (iii)
4(d) (iv)
4(e) (ii)
5(a) # A function which removes duplicate elements from a given list.
def dup(L):
u=[ ]
for i in l:
if i not in U:
u.append(i)
l=u
print(l)
>>>dup([1,2,2,2,3])
[1,2,3]
5(b) # A program to check for Armstrong number
n = int(input(“Enter n: “))
m = n
sum = 0
while m!=0:
x = m%10
sum = sum + x**3
m = m//10
if sum == n:
print(n, “ is an Armstrong number”)
else:
print(n, “ is not an Armstrong number”)
Output:
For n=153, output will be : 153 is an Armstrong number.
For n=123, output will be : 123 is not an Armstrong number.
5 (c) # A recursive function to find number of digits in a positive integer
def recur_sum(n):
if n <= 1:
return n
else:
return n + recur_sum(n-1)
>>>recur_sum(123)
6.
5(d) # A program for writing text in a file, finding number of characters.
name1 = input(‘Enter a filename : ‘)
f1 = open(name1, “w+”)
t1=“Hello this is to be written in a file:”
f1.write(t1)
f1.close()
s=0
f1 = open(name1, “r+”)
while True:
x1=f1.read()
if x1==””:
print(“Size = “, s)
break
else:
print(x1)
s+=len(x1)
f1.close()
Output:
Size = 39
5(e) # A function to find number of elements in a list within a range.
def count_range_in_list(li, min, max):
ctr = 0
for x in li:
if min <= x <= max:
ctr += 1
return ctr
>>>list1 = [10,20,30,40,40,40,70,80,99]
>>>print(count_range_in_list(list1, 40, 100))
6
>>>list2 = [‘a’,’b’,’c’,’d’,’e’,’f’]
>>>print(count_range_in_list(list2, ‘a’, ‘e’))
5
MODEL TEST PAPER 3
Attempt all questions
Maximum Marks 100 Time allowed : 3 Hrs
Q.1(a) Explain any three functions from math module in Python with
suitable examples. (5)
Q.1(b) Explain various logical operators in Python with suitable examples.
Q.2(a) Explain difference between for and while loop in Python. (5)(5)
Q.2(b) Explain difference between formal and actual arguments in a
function in Python. (5)
Q.3 Write and explain the output of the following commands in Python:
(4×5=20)
a. >>>(20>>3)/8+5%10
b. >>>x,y=3,4
>>>print(y<x)
c. x = 5
def func(x):
>>> print(‘x is’, x)
>>> x = 2
>>> print(‘Changed local x to’, x)
func(x)
d. s = ‘listen&understand&query&learn&apply’
delimiter = ‘&’
print(s.split(delimiter))
print(s)

Q.4 Find out errors in the following commands in Python: (4×5=20)


a. >>> “How is weather today?
b. >>>Def func1():
Print(“Error”)
>>> (5/(6-5+1))
c. >>> value1 = ‘24’
>>> y = value1+10

Q.5 (4×10=40)
a. Write a program in Python which finds and prints the largest of three
numbers input by user.
b. Define a class in Python named Cabin which stores number and
location of a cabin. Write a program in Python which inputs data about
3 cabins and display the number of the cabins in the given location.
c. Write a program in Python which prints all the elements in the list who
are equal to smallest value.
d. Write a program in Python which inputs the name of a month and
prints the quarter of the year.
Answers to Model Test Paper 3
1(a) math.ceil(23.5) returns the ceiling value 24
math.floor(23.5) returns the floor value 23
math.sqrt(25) returns square root of 25 in double 5.0
1(b) There are three logical operators in Python: and, or and not.
Logical ‘and’ is a binary operator which returns False if any one of the
operand is False, otherwise, it returns the value of the last True
operand or expression. For example, 3 and (4+5) returns 9 since both 3
and (4+5) are True and last one evaluated is (4+5). 45 and (10-10)
returns False because 45 is True while (10-10) is zero.
Logical ‘or’ is a binary operator which returns False if all the operands
are False, otherwise it returns the value of the first True operand or
expression. For example, 3 or (4+5) returns 3 since this is first operand
which is True. It does not evaluate the next operand(s). (10-10) or 45
returns True because 45 is one operand which is True after (10-10)
which is zero.
Logical ‘not’ is a unary operator which returns the negation of the
operand. If the operand is True, it returns False and if the operand is
False, it returns True. For example, not(45) returns False since 45 is
True. not(0) returns True since 0 is False.
2(a) The syntax of for loop is:
for var1 in range (initial_value, terminating_value,
update_value)
if statement block
Corresponding syntax of while loop is:
var1 = initial_value
while var1 <= terminating_value:
while statement block
var1 + = update_value
Here the loop variable variable1 is initialized before while loop. The
condition for terminating the loop is given after keyword while. The
loop variable is updated within the while loop.
2(b) In Python, a function is defined as:
def function_name(arg1, arg2…):
Function-body
The function name should not be a keyword in Python, it can contain
numbers and underscore but should not contain space and it should
start with small letter. Any number of arguments can be passed to a
function specified as arg1, arg2,…These are called formal arguments
since these are only the placeholders for the values for which the
function will actually be executed. When the function is called, the
values passed are the actual arguments.
For example, a and b are formal arguments in function sum:
def sum(a,b):
print(a+b)
When we call this function as sum(30,40), 30 and 40 are actual
arguments.
3(a) 5.25
3(b) False, since 4<3 is False.
3(c) x is 5
Changed local x to 2
(Because within the function, value of x has been changed to 2)
3(d) The delimiter for separating the words using split( ) function is ‘&’
here.
The output will be:
[‘listen’, ‘understand’, ‘query’, ‘learn’, ‘apply’]
4(a) Closing double quotes are missing at the end of given string.
4(b) A function is defined using keyword ‘def’, ‘Def’ is wrong. The
statements in the body of the function should be written with
indentation which is missing here in print statement. The print()
function is written incorrectly as Print().
4(c) No error. Output will be 2.5.
4(d) Since value1 has a string value. It cannot be added to an integer.
TypeError: Can’t convert ‘int’ object to str implicitly
5(a) # A program in Python which finds and prints the largest of three
numbers input by user.
num1= int(input(‘Enter first number: ’))
num2= int(input(‘Enter second number: ’))
num3= int(input(‘Enter third number: ’))
if num1 > num2:
if num1 > num3:
largest= num1
else:
largest= num3
else:
if num2 > num3:
largest= num2
else:
largest= num3
print(‘Largest = ’, largest)
Output:
Enter first number: 34
Enter second number: 43
Enter third number: 134
Largest = 134
5(b) # Class Cabin
class Cabin:
def __init__(self, number, location):
self.number = number
self.location = location
def display(self):
print (“Number : ”, self.number, “, Location: ”,
self.location)
clist=[]
for var in range(3):
n=input(“Enter number of cabin: ”)
loc=input(“Enter location of cabin: ”)
c=Cabin(n,loc)
clist.append(c)
input1=input(“Enter a location: ”)
s1= []
for s in clist:
if s.location==input1:
s1.append (s.number)
print(s1)
Output:
Enter number of cabin: A1
Enter location of cabin: A block
Enter number of cabin: A2
Enter location of cabin: A block
Enter number of cabin: B3
Enter location of cabin: B block
Enter a location: A block
Output:
[‘A1’ , ‘A2’ ]
5(c) # A program in Python which prints all the elements in the list who are
equal to smallest value.
list1= [1,2,3,1,1,4]
n=min(list1)
for value in list1:
if value==n:
print(value )
The output will be all 1s, each on a separate line.
5(d) # a program in Python which inputs the name of a month and prints the
quarter of the year.
name= input(‘Enter 3 letters for name of month:’)
if name==‘Jan’ or name== ‘Feb’ or name== ‘Mar’ :’
quarter=1
elif: name== ‘Apr’ or name== ‘May’ or name== ‘Jun’ :
quarter=2
elif: name== ‘Jul’ or name== ‘Aug’ or name== ‘Sep’ :
quarter=3
elif: name==‘Oct’ or name== ‘Nov’ or name==‘Dec’ :
quarter=4
else:
print(‘error in input’)
print(‘Quarter : ’, quarter)
Output:
Enter 3 letters for name of month: Nov
Quarter: 4
MODEL TEST PAPER 4
Attempt all questions
Maximum Marks 100 Time allowed : 3 Hrs
Q.1(a) Explain nested ‘for’ statement in Python with a suitable example. (5)
Q.1(b) Explain various uses and characteristics of a tuple in Python. (5)
Q.2 (a) Explain the precedence of all arithmetic operators in Python. (5)
Q.2(b) Explain use of any five reserved words in Python with suitable
examples. (5)
Q.3 Write and explain the output of the following commands in Python:
(4×5=20)
a. def f(values):
values[0] = 4
v = [1, 2, 3]
f(v)
print(v)
b. >>> mywords = [‘i am happy’, ‘i am blessed’,’i am capable’]
>>> for w in mywords[:]:
if len(w)>9:
mywords.insert(0,w)
>>> mywords
c. list1 = [1, 2, 3, 0]
list2 = [‘Red’, ‘Green’, ‘Black’]
final_list = list1 + list2
print(final_list)
d. a,b = 30, 50
while b:
a,b = b,a%b print (a)

Q.4 Select the most appropriate answer for the following in Python:
(5×2=10)
a. Which of the following statement/method is used to remove an item
from a list using index value?
i. pop( )
ii. del
iii. clear( )
iv. None of these
b. What is the return type of methods sort() and remove()?
i. None
ii. a list
iii. an item
iv. Any of these
c. Which of the following is used to add menu items to a menu?
i. add_command()
ii. add_value()
iii. add_item()
iv. None of these
d. Which of the following is used to set the orientation of the scrollbar in
a Text widget?
i. orientation
ii. Orientation
iii. orient
iv. None of these
e. Which of the following is a widget?
i. Button
ii. Label
iii. Scrollbar
iv. All of these
Q.5 (5×10=50)
a. Write a program in Python which prints a given list after reversing it
without using reverse() function.
b. Define a function in Python to get the largest element of the list.
c. Define a function in Python to check whether the given string is a
palindrome or not.
d. Write a program in Python to display the names of the days of the
week.
e. Write a program in Python to write some text and integer values into a
file. The filename should be entered by the user. The file should be
created if not existing already. If already exists, it should be
overwritten.
Answers to Model Test Paper 4
1(a) When one ‘for’ statement is one of the statement in body of another
‘for’ statement, it is called nested ‘for’ statement. For example to
create a 2 dimensional array of order 2X3, we need to use nested for
statement:
list1=[]
for row in range(2):
for col in range(3):
m= int(input())
list1.append(m)
print(list1)
If the input is 1 2 3 4 5 6. The 2 dimensional list1 is a list [[1,2,3],
[4,5,6]]
1(b) All the values separated by comma are packed together in the given
sequence in tuple ‘data’.
data = 12, 34, ‘Googly’
The len() function returns the number of elements in the tuple: 3
When a tuple is packed with some values, it is called tuple packing. In
case the values are to be unpacked to different variable given in a
sequence, then it is called sequence unpacking. For example,

x,y,z = data

The three variables x,y,z get the values 12,34,’Googly’ respectively.


2(a) Please refer to Appendix B
2(b) Please refer to Appendix A
3(a) List v is initialized to [1,2,3]. Function f() changes the 1st value of v to
4.
The output will be: [4,2,3]
3(b) The given for loop will execute for all values of list mywords. If the
length of the string in the list mywords is found to be more than 9, that
string is inserted in the beginning of the list mywords. Thus, first ‘i am
happy’ is inserted in list of mywords in first iteration of the loop
because the total length of ‘i am happy’ is 10(>9). In the next iteration,
‘i am blessed’ is inserted in the beginning of the recently updated list
mywords because the total length of ‘i am blessed’ is 12(>9). In the
next iteration, ‘i am capable’ is inserted in the beginning of the
recently updated list mywords because the total length of ‘i am
capable’ is 12(>9). The output will be:
[’i am capable’,‘i am blessed’ ,‘i am happy’ , ‘i am happy’,
‘i am blessed’,’i am capable’]
3(c) [1, 2, 3, 0,‘Red’, ‘Green’, ‘Black’]
3(d) 10 (The greatest common divisior of 30 and 50)
4(a) (i)
4()b (i)
4(c) (iv)
4(d) (iii)
4(e) (iv)
5(a) # A program in Python which prints a given list after reversing it.
list1 = [13, 68, 19, 40]
list2= []
for index in range (len(list1)-1, -1, -1):
list2.append(list1[index])
list1 = list2
print(list1)
Here, the index varies from 4-1, i.e. 3 to 0 and the elements are
appended in list2 in reverse order from list1. In the end, list1 gets the
elements of list2.
The output will be: [40, 19, 68, 13]
(b) # A function in Python to get the largest element of the list
def maxlist(mylist):
return max(mylist)
print(maxlist([12,56,29,70]))
The output will be 70
(c) #A function in Python to check whether the given string is a palindrome
or not.
def isPalindrome(str):
left_pos = 0
right_pos = len(str) - 1
while right_pos >= left_pos:
if not str[left_pos] == str[right_pos]:
return False
left_pos += 1
right_pos -= 1
return True
Output:
print(isPalindrome(‘madam’))
The output will be True
print(isPalindrome(‘sir’))
The output will be False
(d) Write a program in Python to display the names of the days of the week.
x=int(input(‘Enter a number between 1-7:’))
if x==7:
print (‘sunday’)
elif x==6:
print(‘monday’)
elif x==5:
print(‘tuesday’)
elif x==4:
print(‘wednesday’)
elif x==3:
print(‘thursday’)
elif x==2:
print(‘friday’)
elif x==1:
print(‘saturday’)
else:
print(‘invalid entry’)
Output:
Enter a number between 1-7: 6
monday
(e) #A program in Python to write some text and integer values into a file.
The filename should be entered by the user. The file should be created
if not existing already. If already exists, it should be overwritten.
filename = input(‘Enter a filename : ‘)
f1 = open(filename, ‘w’)
t1= input(‘Enter some text:’)
f1.write(t1)
t2=int(input(‘Enter some integer:’))
f1.write(str(t2))
f1.close()
MODEL TEST PAPER 5
Attempt all questions
Maximum Marks 100 Time allowed : 3 Hrs
Q.1 (a) Explain the function to copy an array in Python with a suitable
example. (5)
Q.1(b) Explain nested for loop in Python with a suitable example. (5)
Q.2 (a) Explain the use of pass in Python. (5)
Q.2(b) Name the main operations in a database which can be performed on
a table in Python. (5)
Q.3 Write and explain the output of the following commands in Python: (30)
a. >>> print(arr.count([1,2]))
Assume arr is a numpy array
b. >>> print(“This is titlecase”. istitle())
c. >>> r = lambda a : a + 10
>>> print(r(20))
d. >>> tuplex = (“w”, 3, “r”, 2, “s”)
>>> print(“r” in tuplex)
e. >>> s1 = {1,2,3,4,5}
>>> s2 = {4,5,8}
>>> s1.difference_update(s2)
>>> print(s1)
f. >>> def ismember(data, n):
for value in data:
if n == value:
return True
return False
>>> print(ismember([1, 2, 3, 4], 3))

Q.4. (5X10=50)
a. Write a program in Python to multiply all the items in the dictionary.
b. Write a program to count the number of upper case and lower case
letters in a given string.
c. Write a program in Python to check whether a given set is a subset of
the other.
d. Write a program in Python to convert degrees to radian.
e. Write a program in Python which reverses a given tuple.
Answers to Model Test Paper 5
1(a) import numpy
a=numpy.array([2,3,5], [1,2,3])
b= numpy.copy(a)
print(b)
1(b) Nested for loop contains one for loop inside the other. Example is
given here where marks for 2 students in 3 subjects are read from the
user and sum of marks for each student are printed.
for i in range (2):
sum=0.0
for j in range(3):
print(“Enter marks:”)
marks=float(input())
sum=sum+marks
print(“Sum=”, sum)
2(a) pass is an empty statement. It can be used anywhere like is-else, for,
functions or classes:
if (x>20):
pass # do nothing is x>20 is True
for i in range (10):
if i%2==0:
pass # It does nothing if when i is even
def f1():
pass # empty function
class C1:
pass # empty class
2(b) The operations which can be performed on a table are: CREATE,
INSERT, DELETE, DROP, UPDATE, SELECT.
3(a) It returns the count of pattern [1, 2] found in the array arr.
3(b) True because Only first letter is in capital and rest are in small letters
3(c) 30 The lambda function adds 10 to given value i.e. 20.
3(d) True as ‘r’ is present in tuple1
3(e) {1,2}. The values 3,4,5 are deleted from s1 as these are present in s2.
3(f) True. The function returns True if the element is present in the list,
False otherwise. Here, 3 is a member of list [1,2,3,4].
4(a) my_dict = {1:10,2:20,3:2}
result=1
for key in my_dict:
result=result * my_dict[key]
print(result) # 400 , product of the values
4(b)
def string_test(s):
d={“UCASE”:0, “LCASE”:0}
for c in s:
if c.isupper():
d[“UCASE”]+=1
elif c.islower():
d[“LCASE”]+=1
else:
pass
print (“Ucase: “, d[“UCASE”])
print (“Lcase: “, d[“LCASE”])
string_test(“This is a TEST String”)
Output will be:
Ucase: 6
Lcase: 11
4(c) set1 = set([“apple”, “lenovo”])
set2 = set([“dell”, “apple”, “lenovo”])
print(set1.issubset(set2))
The output is True because all items from set1 are present
in set2 as well.
set3 = set([“dell”, “lenovo”])
print(set1.issubset(set3))
The output is False because all items from set1 are not
present in set3 as well.
4(d) pi=22/7
degree = float(input(“Input degrees: “))
radian = degree*(pi/180)
print(radian)
Output will be:
Input degrees: 70
1.22222222222
4(e) x = (“No.1”)
y = reversed(x)
print(tuple(y)) # (‘1’, ‘.’, ‘o’, ‘N’)
The reversed function returns the string in reverse and it
is converted to a tuple using function tuple().
MODEL TEST PAPER 6
Attempt all questions
Maximum Marks 100 Time allowed : 3 Hrs
Q.1 (a) Explain various functions to initialize arrays in Python with a
suitable example. (5)
Q.1 (b) Explain membership operators in Python with a suitable example.
Q.2 (a) Explain any three string handling function in Python. (5)(5)
Q.2 (b) Explain median() and mode() functions in statistical module in
Python. (5)
Q.3 Write and explain the output of the following commands in Python: (30)
a. >>> print(“Array stores elements of type:”, arr.dtype)
Assume array is a numpy array
b. >>> (200>>3)/8+5%20
c. >>> my_dict = {‘1’:10,‘2’:50,‘3’:20}
>>> print(sum(my_dict.values()))
d. set1 = set([“red”, “blue”])
set2 = set([“blue”, “yellow”])
set3 = set1.union(set2)
print(set3)
e. sqlite3> SELECT tbl_name FROM database WHERE type
= ‘table’;
f. tuple1 = (“w”, 3, “r”, 2, “s”)
print(“t” in tuple1)

Q. 4 (5×10=50)
a. Write a Python program to create an array object using numpy, print
the type, dimensions, number of rows and columns and total number
of elements of the array.
b. Write a program in Python to add a button to your application in
Tkinter.
c. Write a program in Python to concatenate dictionaries into one.
d. Write a program in Python to delete an element from a set.
e. Write a program in Python which prints all prime numbers between x
and y which are given by the user.
Answers to Model Test Paper 6
1.(a) a=numpy.zeros([2,3], dtype=int) initializes an array of integers with
size 2X3 with 0.
[[0 0 0], [0 0 0]]
a=numpy.ones([2,2], dtype=float) initializes an array of
floating-point values with size 2X2 with 1.
[[1. 1. ], [1. 1.]]
a=numpy.full((3,2), 5) initializes an array of integers with
size 3X2 with value 5.
[[5 5 ], [5 5 ], [5 5]]
1.(b) There are two membership operators in Python: in and not in.
Operator in returns True if the element is present in given list, False
otherwise. print( 4 in [1,2,3,4] returns True while print(4,[10,11,12])
returns False. not in returns True if the element is not present in given
list, False otherwise.
print( ‘are’ not in “array” returns True while print(“ar”
not in “array” returns False.
2.(a) string.isupper()- returns True if all characters in the string are in
uppercase, False otherwise.
print(“Hello”.isupper()) returns False
string.islower()- returns True if all characters in the
string are in lowercase, False otherwise.
print(“Hello”.islower()) returns False
string.istitle()- returns True if all characters in the
string are in title case, False otherwise.
print(“Hello”.istitle()) returns True
2. (b) The function mode returns the most frequently occurring item in the
given list.
import statistics
data1 = [12, 71, 12, 13, 10, 7, 13, 13]
print(statistics.mode(data1)) # 13 is the most frequently
occurring item
data2 = [1, 7, 2, 13, 10]
print(statistics.mode(data2))
#statistics.StatisticsError: No unique mode; found 5 equally
common values
The function median returns the middle value of the given list (when
arranged in ascending order). In case of even number of values in the
list, it returns the average of the 2 values in the middle (when arranged
in ascending order).
import statistics
data1 = [12, 71, 11, 10, 13]
print(statistics.median(data1)) # 12 is the median
here[10,11,12,13,71]
data2 = [1, 7, 2, 13, 10, 3]
print(statistics.median(data2)) # 5.0 is the median from 3
and 7 [1,2,3,7,10,13]
3.(a) Prints the type of elements in array
3.(b) 8.25 (200>>3=25; 5%20=5; 25/8 = 3.25 + 5)
3.(c) 80 # sum of all dictionary values
3.(d) {‘red’, ‘yellow’, ‘blue’} # union of 2 sets
3.(e) Lists the names of all tables in the current database.
3.(f) False, as t is not a member of the tuple tuple1
4.(a) import numpy as np
arr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] ) # Creating array
object
print(“Array is of type: “, type(arr)) # Printing type of
arr object
print(“No. of dimensions: “, arr.ndim) # Printing array
dimensions (axes)
print(“Shape of array: “, arr.shape) # Printing shape of
array
print(“Size of array: “, arr.size) # Printing size (total
number of elements) of array
4. (b) import tkinter as tk
parent = tk.Tk()
parent.title(‘Title - button’)
my_button = tk.Button(parent, text=’Quit’, height=1,
width=35, command=parent.destroy)
my_button.pack()
4(c) dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:60,6:70}
dic4 = {}
for d in (dic1, dic2, dic3):
dic4.update(d)
print(dic4) # {1:10, 2:20, 3:30, 4:40, 5:60, 6:70}
4(d) set1 = set([2, 3, 4, 5])
set1.discard(4)
print(set1) # [2,3,5]
4(e) x=int(input())
y=int(input())
i = x
while(i <= y):
j = 2
while(j <= (i/j)):
if not(i%j):
break
j=j+1
if (j > i/j) :
print (i, end=” “)
i = i + 1
Suppose x=30, y= 40, Output will be: 31 37
MODEL TEST PAPER 7
Attempt all questions
Maximum Marks 100 Time allowed : 3 Hrs
Q.1 (a) Explain nested ‘if’ statement in Python with a suitable example. (5)
Q.1 (b) Explain recursive function in Python with a suitable example. (5)
Q.2.(a) Explain the precedence of all operators in Python. (5)
Q.2 (b) Explain any five functions of re module in Python. (5)
Q.3. Write and explain the output of the following commands in Python:
(30)
a. >>>chr(70)
b. >>>any(x > 0 for x in [-1,-2,-3,-4])
c. >>>globals()
d. >>>list(enumerate([1,2,3]))
e. >>>mylist=[23,67,90]
f. >>>mylist.pop( 2)
g. >>>len([[1,2],3,4,[5,6]])
Q.4. (5X10=50)
a. Write a Python program to find numbers between 10 and 25(both
included) where each digit of a number is an even number.
b. Write a program in Python to display the names of the month of the
year based on the number of the month.
c. Write a program which creates a dictionary of 5 key, value pairs and
performs a search for a given key.
d. Define a class in Python named City which stores name and state of a
city. Write a program in Python which inputs data about 5 cities and
display the number of the cities in the given state.
e. Write a program in Python which counts and prints the total number of
blank spaces in the given text file.

You might also like