Python Study Material
Python Study Material
Python is a simple, interactive object oriented programming language which is robust, elegant and powerful. This
programming language not only used in scripting but also for general purpose programming. The development of
python was started in the year 1989 by Guido Van Rossum. Modules in python play an important role as they store
piece of python code which can be shared by other python programs. Python provides a wide range of standard
exceptions, but programmers would need to use their own exceptions that provide more detailed information.
It has been designed in such a way that the programmer does not need to look after the low level details such as
memory management. The applications of python are Zope, Google search engine, Inktomi search software, etc.
This book provides theoretical and practical knowledge to the student about “Python-1” for B.Sc [Computer Science]
V-Sem and B.A & B.Sc [Computer Applications] III-Sem. It covers the complete syllabus of the subject prescribed
by O.U. The content written in this book is presented in a consistently readable and student friendly format so that
student can prepare well for their both mid and final exams. This book is beneficial because it gives complete up-
to-date information about each topic and the questions to be asked in the exams. This helps the student in getting a
clear idea about the important questions in each topic. This book has been prepared keeping student’s views, ideas
and suggestions in mind. The main motivation behind the publication of this book is to help the student to gain good
marks and knowledge in the subject.
According to the examination pattern of B.Sc students, this book provides the following features:
v List of Definitions are provided before the units for easy reference.
v Every unit is structured into two main sections viz. Short Questions and Essay Questions with solutions
along with Learning Objectives and Introduction.
v Objective Type along with Very Short Answers are also given at the end of each unit.
v Three Model Papers are provided in order to help students to understand the paper pattern in the end examination.
v Including Latest Exams Question Papers with Solutions for B.A & B.Sc [Computer Applications] III-Sem. These
question papers help the students in understanding the way of asking question in the examination.
v Important Questions are included to help the students to prepare for Internal and External Assessment.
The table below gives complete idea about the subject, which will be helpful to plan and score good marks in their
exams.
Unit
Unit Name Description
No.
This unit includes topics like Python, Features of Python, Execution of
a Python Program, Viewing the Byte Code, Flavors of Python, Python
Virtual Machine, Frozen Binaries, Memory Management in Python,
Garbage Collection in Python, Comparisons between C and Python,
Comparisons between Java and Python. Writing Our Fist Python
Program: Installing Python for Windows, Installing Numpy, Setting the
Path to Python, Writing Our First Python Program, Executing a Python
1. Introduction to Python Program, Getting Help in Python, Getting Python Documentation
Help, Reopening the Python Program in IDLE. Data Types in Python:
Comments in Python, Doc Strings, How Python Sees Variables, Data
Types in Python, Built-in Data Types, Bool Data Type, Sequences
in Python, Sets, Literals in Python, Determining the Data Type of a
Variable, What about Characters, User-defined Data Types, Constants
in Python, Identifiers and Reserved Words, Naming Conventions in
Python.
It is sincerely hoped that this book will satisfy the expectations of students and at the same time helps them to score
maximum marks in exams.
Suggestions for improvement of the book from our esteemed readers will be highly appreciated and incorporated
in our forthcoming editions.
Python-1
B.Sc iii-year V-Semester [Computer Science] (oU)
&
B.A & B.Sc ii-year iii-Semester [Computer Applications] (oU)
CONT ENT S
Syllabus (As per (2016-17) Curriculum)
List of Important Deinitions l.1 – l.2
Model Question PaPers With solutions
Model Paper-I MP.1 – MP.2
Model Paper-II MP.3 – MP.3
Model Paper-III MP.4 – MP.4
exerCiSe QUeStionS 36
internAl ASSeSSMent 37 - 40
exerCiSe QUeStionS 76
internAl ASSeSSMent 77 - 80
Introduction to Python: Python, Features of Python, Execution of a Python Program, Viewing the Byte
Code, Flavors of Python, Python Virtual Machine, Frozen Binaries, Memory Management in Python,
Garbage Collection in Python, Comparisons between C and Python, Comparisons between Java and
Python.
Writing Our Fist Python Program: Installing Python for Windows, Installing Numpy, Setting the Path to
Python, Writing Our First Python Program, Executing a Python Program, Getting Help in Python, Getting
Data Types in Python: Comments in Python, Doc Strings, How Python Sees Variables, Data Types in
Python, Built-in Data Types, Bool Data Type, Sequences in Python, Sets, Literals in Python, Determining
the Data Type of a Variable, What about Characters, User-defined Data Types, Constants in Python,
UNIT-II
Operators in Python: Arithmetic Operators, Assignment Operators, Unary Minus Operator, Relational
Operators, Logical Operators, Boolean Operators, Bitwise Operators, Membership Operators, Identity
Input and Output: Output Statements, Input Statements, Command Line Arguments.
Control Statements: Control Statements, The if Statement, A Word on Indentation, The if ... else Statement,
The if ... elif ... else Statement, The while Loop, The for Loop, Infinite Loops, Nested Loops, The else
Suite, The break Statement, The bontinue Statement, The pass Statement, The assert Statement, The
return Statement.
List of Important Definitions Computer Science Paper-V
UNIT - I
1. Class
A class is a collection of components which may include class variables, class methods and instance method. Class
declaration consists of procedure which can act either as an instance method or a class method.
2. Variable
Variable can be defined as a storage location in memory. It stores data values of the programs and provides whenever
required to work on.
3. Sequence
A ‘sequence’ is a data structure, that stores elements, which can be accessed using index offsets.
4. Mapping Types
A map can determine a set of elements as key value pairs. If key is provided the value of it can be accessed.
5. Literal
6. Constant
A constant is similar to that of variable but it’s value cannot be changed or modified while program execution.
7. Garbage Collection
Garbage collector in python is a module that is used to delete the objects from the memory. The objects that are not useful
in the program are deleted by the garbage collector. Garbage collector is maintained by name gc.
8. Comments
Comments determine the features of program code. This will increase the readability. Comments are of two types in
Python, they are single line and multi line comments.
9. Tuples
Tuples are containers, that are used to store data items. They are similar to lists because they allow a list of elements to
store.
10. Sets
A set can be defined as a group unordered elements. The elements in a set might not appear in the order they are entered
into it.
UNIT - II
1. Operator
An operator can be defined as a symbol which perform specific operations such as mathematical, logical and other
manipulations using one or more operands.
2. Identity Operators
These operators are used to compare two objects with their memory addresses.
SIA PUBLISHERS and DISTRIBUTORS PVT. LTD. L.1
Computer Science Paper-V Python-I
3. Command Line Statements
Programs are run at command lines by using run command such as python program name in python. Programs can be
even designed to accept arguments at its command line.
4. Indentation
5. pass Statement
The pass statement is used in cases, where a python statement does nothing. In order to avoid syntax errors, we use pass
statement.
6. assert statement
The assert statement is used to check whether the given condition is fulfilled or not.
7. Expression
An expression can be defined as a set of values, variables and operators. The variable and value are considered itself as
an expression.
8. Control Statements
Control statements are the statements that allows the programmer to specify the next statement that must be executed
depending on some conditions.
9. continue Statement
The continue statement in Python is similar, to the continue statement of other high-level programming languages.
A function contains a set of statements that together perform a task. Upon completion of that particular task. The function
returns the result. The function should return the result to the calling function.
Paper-V (SEC-3)
E: Python-I
Part - a ( 2 × 5 = 10 Marks )
1. (a) List out the features of python. (Unit-I, Page No. 2, Q2)
OR
(b) Write short notes on multiline comments. (Unit-I, Page No. 3, Q6)
2. (a) Deine operator and list out the operators used in python. (Unit-II, Page No. 42, Q1)
OR
Part - B ( 2 × 15 = 30 Marks )
3. (a) (i) List and explain the features of python. (Unit-I, Page No. 5, Q14)
OR
(iii) Reopening the python program in IDLE. (Unit-I, Page No. 19, Q28)
(ii) Explain about python input and output statements. (Unit-II, Page No. 58, Q20)
OR
(b) (i) Discuss in detail about command line arguments. (Unit-II, Page No. 61, Q21)
(ii) Write how and when if-elif-else is used. (Unit-II, Page No. 65, Q25)
Part - a ( 2 × 5 = 10 Marks )
(Short answer Type)
OR
2. (a) Discuss in brief about boolean operators. (Unit-II, Page No. 42, Q3)
OR
(b) What are command line statements? (Unit-II, Page No. 44, Q6)
Part - B ( 2 × 15 = 30 Marks )
(Essay answer Type)
3. (a) (i) Discuss how a python program is executed. (Unit-I, Page No. 8, Q16)
(ii) Write steps to install python on windows. (Unit-I, Page No. 12, Q24)
OR
(b) (i) Explain the execution process of python. (Unit-I, Page No. 17, Q27)
(ii) Explain various data types in python. (Unit-I, Page No. 25, Q31)
OR
(b) (i) Deine control statements. Discuss about if statement. (Unit-II, Page No. 62, Q22)
(ii) Write in short about ininite and nested loops. (Unit-II, Page No. 69, Q27)
MODEL
PA P E R 3
FACULTY OF SCIENCE
B.Sc. (CBCS) V-Semester Examination
Paper-V (SEC-3)
E: Python-I
Part - a ( 2 × 5 = 10 Marks )
(Short answer Type)
1. (a) List ive differences between C and python. (Unit-I, Page No. 3, Q5)
OR
(b) List ten reserved words in python. (Unit-I, Page No. 4, Q12)
2. (a) Write about bitwise operators. (Unit-II, Page No. 43, Q4)
OR
(b) Explain the if...elif...else statement. (Unit-II, Page No. 46, Q12)
Part - B ( 2 × 15 = 30 Marks )
(Essay answer Type)
OR
(b) (i) Discuss about comments and doc strings. (Unit-I, Page No. 22, Q29)
(ii) Explain about user-deined datatypes in python. (Unit-I, Page No. 31, Q38)
4. (a) (i) Discuss in detail about mathematical functions in python. (Unit-II, Page No. 56, Q19)
(ii) Write in brief about if . . . else statement. (Unit-II, Page No. 64, Q24)
OR
UnIT
IntroductIon to python
1
Learning Objectives
After studying this unit, a student will have a thorough knowledge about the following concepts,
Ø Python, features and lavours of it
intrOductiOn
Python is a simple interactive, interpreted object oriented programming language compared to other programming
wages. It is very robust, elegant and a powerful language.
The development of Python language was started in the year 1989 by Guido Van Rossum. He is one among
the developers of ABC language. This ABC language was unpopular because of its typical syntax and limited
functionality. Hence, Guido decided to develop a language that has better features than the ABC language such as
more readability, extensibility and less unrequired variability.
Guido believed that the object oriented languages were too complex. The use of static typing also increased
programs complexity. To appeal to unix/c hackers, he designed Python on ABC’s extensive usability testing. And,
to make it suitable to both the beginners as well as the experienced programmers Guido wanted it to be acceptable
as programming language. Thus, Python started inheriting from other languages.
part-a
Short QueStIonS wIth SolutIonS
Q1. Deine the two modes in python.
Python has two modes namely script and interactive. In normal mode, the python iles that are scripted py iles are run
by python interpreter. Whereas interactive mode is a command line shell. It provides feedback for every statements immediately
while running the program. It allows even small bits of code to be tested before scripting.
Answer :
A class is a collection of components which may include class variables, class methods and instance method. Class
declaration consists of procedure which can act either as an instance method or a class method. If a procedure is parameterized
with formal parameter, ‘self’ and if it refers to an object of a class being declared, then such a procedure is said to be an instance
method, otherwise the procedure acts as a class method.
A compiler will convert the source code into the machine code before it is submitted to the computer. This is because the
computer understands only machine code. The python compiler also performs the same thing. It initially converts the source code
into byte code. Each byte code size would be 1 byte i.e., 8 bits. Thus, they are called byte code instructions. They are stored in
.pyc ile.
The byte code instructions are converted into machine code by a PVM. with this the computer can execute the machine
code and generate the output. PVM has an interpreter embedded in if. This interpreter is responsible to convert the .byte code
machine code. It then sends the machine code to the processor for execution.
2 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-1: INTrodUcTIoN To pyThoN Computer SCienCe paper-V
Q5. List ive differences between C and python. Model Paper-III, Q1(a)
OR
distinguish between C and python.
Answer : B.Sc[C.a], dec.-17, Q1(b)
C Python
1. C is a procedure oriented programming language. 1. Python is an object oriented programming language
with features such as classes, objects, polymorphism,
inheritance etc.
2. Execution speed is fast. 2. Execution speed is slow.
3. Declaration of variables is required. 3. Declaration of variables is not required.
4. It cannot handle exceptions. 4. It can handle exceptions.
5. It does not have garbage collector. 5. It has garbage collector.
Q6. Write short notes on multiline comments.
Answer : Model Paper-I, Q1(b)
Python allows multi line comments also. It would be complex task to used # symbol before every single line in multiline
comments. So all the lines of comments embedded in triple single quotes (''') or triple double quotes (" " ") at beginning as well
as ending also. They are called as multi line comments or block comments.
"""
Python is an object oriented programming language. It supports multiline comment.
"""
'''
Python is an object oriented programming language.
It supports multi line comments
'''
Q7. Deine variable.
Answer :
Variable
Variable can be deined as a storage location in memory. It stores data values of the programs and provides whenever
required to work on. Python does not require the variables to be declared. Rather only naming and assigning the values to it is
enough. Even the data type is not required to be speciied. Python internally handles the variables according to the values assigned
to them.
Example
x = 50
print x
This statement prints 50 as the result. A variable can be redeclared with some other value also. Variables are of few types
they are local and global variables.
Q8. Deine sequences.
Answer : Model Paper-II, Q1(b)
A ‘sequence’ is a data structure, that stores elements, which can be accessed using index offsets. For example, the strings
are sequences of characters i.e., a string ‘Hello world!’, contains the sequence of characters, H, e, l, l, o, W, o, r, l, d, !. These
sequence elements are stored, starting at index 0 till the index N – 1, where N is the length of the sequence.
i.e.,
0 1 2 3 4 5 6 7 8 9 10 11
H E L L O W O R L D !
OR
Write in brief about any four keywords in python.
Answer : B.a[C.a], dec-17, Q1(b)
Keywords are reserved words which forms a construct of the language. Use of these keywords for any other purpose
results syntax error.
The below table depicts keywords used in Python.
1. and 2. as 3. assert 4. break 5. class
6. continue 7. def 8. while 9. elif 10. else
1. class
A class is a collection of components which may include class variables, class methods and instance method.
2. else
If the statement if evaluates to a Boolean value false then the code in the else block gets executed.
3. while
‘while’, is the irst conditional looping statement in python, in while the code is executed in a loop until the condition
becomes false.
4. continue
The continue statement in Python is similar, to the continue statement of other high-level programming languages.
5. break
The break statement in python is similar, to the one found in ‘c’. It is used to exit the current loop and executes the
following statement.
6. assert
The assert statement is used to check whether the given condition is fulfilled or not.
4 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-1: INTrodUcTIoN To pyThoN Computer SCienCe paper-V
part-b
eSSay QueStIonS wIth SolutIonS
1.1 IntroductIon to python
The development of Python language was started in the year 1989 by Guido Van Rossum. He is one among the developers
of ABC language. This ABC language was unpopular because of its typical syntax and limited functionality. Hence, Guido decided
to develop a language that has better features than the ABC language such as more readability, extensibility and less unrequired
variability.
Guido believed that the object oriented languages were too complex. The use of static typing also increased programs
complexity. To appeal to unix/c hackers, he designed Python on ABC’s extensive usability testing. And, to make it suitable to
both the beginners as well as the experienced programmers Guido wanted it to be acceptable as programming language. Thus,
Python started inheriting from other languages.
While working on Python, in mid 1990’s, Guido move to US to work with CNRI (Corporation for National Research
Initiatives), a non proitable organization of US government to undertake the construction of large scale applications. This
application development interfered with the development of core language even after careful study about the nature of work
changed.
In the year 2000, Guido joined. Be Open.com, a commercial organization for open source software development along
with two other members of Python team. Among them is a long time pythonister (named Tim Peter) and other, an intelligent
contributor to comp.lang. Python news group. The development of core language and its supportive libraries was their main
intention. However, this did not work out well in BeOpen.com. Within three months, they moved to digital creations and then
to the zope corporation.
After moving to zope corporation, they found noticable changes. This corporation is a major Python user and the creator
of the zope websystem. It is certain that the association with zope will focus on features that are important in developing zope
even though the core development team left zope.
Finally, the core team joined an organization showing a clear interest in developing Python. Guido holds the ultimate veto
on changes in language and Python community is happy to have him and referred him as a benevolent dictator for life.
Q14. List and explain the features of python.
Writing and executing the python scripts is an easy process. Initially type “Python” or “Python 3” at the command prompt
to access python. With this even python REPL (Read-Eval-Print-Loop) gets opend. To exit from REPL type Ctrl-D. Follow the
below steps to write and run a phython script.
1. Create a new ile with name MyScript.py.
2. Type the below code in it
3. Save the ile with .py extension. Even text editors such as notepad or notepad ++ to write the code and press ctrl + x to
exit.
4. Without making the ile executable it can be run by navigating the location of the script and then by typing MyScript.py.
5. MyScript.py can be made executable by typing chmod +x MyScript.py at command prompt.
6. To run the script type at command prompt.
C:\>python MyScript.py
This command will call the compiler to convert the ile into byte code. This byte code will converted to machine code
and the processor will execute this machine code.
Output
(i) PVM
A compiler will convert the source code into the machine code before it is submitted to the computer. This is because the
computer understands only machine code. The python compiler also performs the same thing. It initially converts the source
code into byte code. Each byte code size would be 1 byte i.e., 8 bits. Thus they are called byte code instructions. They are stored
in .pyc ile.
The byte code instructions are converted into machine code by a PVM. with this the computer can execute the machine
code and generate the output. PVM has an interpreter embedded in it. This interpreter is responsible to convert the byte code
machine code. It then sends the machine code to the processor for execution.
(ii) Frozen Binaries
Once software is designed in python, it can be provided to the user in two ways. The irst method provides the .pyc iles
to the user. In order to run the instructions of .pyc iles, user need to install the PVM in the computer. The second method will
provide .pyc iles, PVM and some required python library to the user. These three things will be converted into a single executable
ile. User can double click this ile to execute it directly. Conversion of python programs into true executable by following this
process is called frozen binaries will be more than that of .pyc iles. frozen binaries are created by using some software like
py2exe, pyinstaller, frozen etc.
RAM
1.1.5 Comparisons between C and Python, Comparisons between Java and Python
Q22. differentiate between C and Python.
OR
What is the difference between C and python?
Answer : B.a[C.a], dec.-17, Q3(b)(ii)
C Python
1. C is a procedure oriented programming language. 1.
Python is an object oriented programming language
with features such as classes, objects, polymorphism,
inheritance etc.
2. Execution speed is fast. 2. Execution speed is slow.
3. Declaration of variables is required. 3. Declaration of variables is not required.
4. It cannot handle exceptions. 4. It can handle exceptions.
5. It does not have garbage collector. 5. It has garbage collector.
6. Indentation of c statement is not required. 6. Indentation is compulsory.
7. It allows in-time assignments. 7. It does not allow in-time assignments.
8. Comma is used as statement separator. 8. Semicolon is used as statement separator.
9. Semicolon is used to terminate the statements. 9. New line indicates statement termination.
10. Array index must be positive integer. 10. Array index can be positive or negative integer.
11. It supports one as well as multi-dimensional ar- 11. It support only one dimensional array.
rays.
12. It supports pointers. 12. It does not supports pointers.
Java Python
1. Java is an object oriented programming language. 1. Python contains combination of both functional pro-
gramming language and object oriented programming
language features.
2. Declaration of variables is compulsory. 2. Declaration of variables is not required.
3. It is static and weak. 3. It is dynamic and strong.
4. JVM does the memory allocation. 4. PVM does the memory allocation.
5. Array index must be positive integer. 5. Array index must be positive or negative integer.
6. It supports both one and multidimensional arrays. 6. It supports only one dimensional arrays.
7. Comma is used as statement separator. 7. Semicolon is used as statement separator.
8. Semicolon is used to terminate the statements. 8. New line is used to terminate the statements.
9. Indentation for statements is not necessary. 9. Indentation for statements is compulsory.
10. It has switch statements. 10. It does not have switch statements.
1.2.1 Installing Python for Windows, Installing Numpy, Setting the Path to Python
Q24. Write steps to install python on windows.
Answer : Model Paper-II, Q3(a)(ii)
The latest version of python is python 3.6.4. Any software has two version 32 bit and 64-bit. Respective version based
on the operating system can be downloaded and installed from the below link.
https://www.python.org/downloads/release/python-364
1. Select ‘windows x 86-64 executable installer’ for 64 bit operating system computer or select ‘windows x86 executable
installer’ for 32-bit operating system computer with this ‘python-3.6.4 and 64-exe’ ile will be downloaded.
2. Double click on ‘python-3.6.4-and 64.exe’ ile. This will display a setup dialog box.
3. Click the checkbox install launcher for all the users and add python 3.6 to PATH.
5. Once the installation completes a dialog box appears showing the message ‘setup was successful’. Finally, click on close
button.
OR
How to add the python path in windows?
(Refer Only Topic: Setting Path to Python)
Answer : B.a[C.a], dec.17, Q3(b)(i)
Once the python is installed on the computer a speciic path must be set before working with python.
Output
Here, # represents comments in python. Data stored in memory location is referred as variable. In the above program, 2
is stored in variable x, 6 is stored in variable y. In the fourth line product of x and y is stored in variable z. In the ifth the result
is displayed using print function.
Q27. Explain the execution process of python. Model Paper-II, Q3(b)(i)
OR
Explain how to write and execute a program in python.
Answer : B.Sc[C.a], dec.-17, Q3(a)(ii)
2. Goto ile and click on New File (Ctrl + N) option in IDLE window
1.2.3 Getting Help in Python, Getting Python Documentation Help, Reopening the Python
Program in IDLE
Q28. Explain about the following,
(i) Getting help in python
(ii) Getting python documentation help
(iii) Reopening the python program in IDLE.
Answer : Model Paper-I, Q3(b)
Another alternative to view help is to type help( ) command in paranthesis at python promt...
(ii) Getting Python Documentation Help
Python documents contain the description about the python features. It is mostly helpful to the beginners and professional
programmers in order to understand the python features. To view it user need to open IDLE window and select help followed by
Python Docs.
The window displays the documentation help of the respective python version. It displays all the features so that user can
select the desired feature by clicking on it.
Comments
Comments determine the features of program code. This will increase the readability. Comments are of two types in
Python, they are single line and multi line comments.
1. Single Line Comments
Comments begin with # symbol. The complex line from the # symbol represents a single line comment. Comments are not
executed by the compiler or PVM. They are non executable and are used only for human understandability x = 2 # x is assigned a value.
Doc Strings
Factfully the multiline comments are not supported by python. The lines embedded in triple quotes are not actually
comments. They are the regular strings with exception that they can span multiple lines. The memory is allocated internally to
the strings embedded in triple quotes. If these strings are not assigned to any variables. They will be removed from memory by
the garbage collector. Because of this they are referred as comments.
Users of python mostly not recommend the multiline comments because the occupy memory internally and waste the
interpreter time. When the multiline comments are placed before any module function, class or method, they are referred as
documentation strings. They are used in creating the API documentation ile from python program.
Example
def add(a, b):
“““
This function will add two variables and generates their sum
“““
Print(“sum = ”, (a + b))
Q30. How does python view the variables?
Answer :
Variable
Variable can be deined as a storage location in memory. It stores data values of the programs and provides whenever
required to work on. Python does not require the variables to be declared. Rather only naming and assigning the values to it is
enough. Even the data type is not required to be speciied. Python internally handles the variables according to the values assigned
to them.
Example
x = 50
print x
Multiple Assignment
In python, multiple assignment refers to the assignment of single object to multiple variables.
Example
In the above example, p, q and r are assigned to single integer object (of value 25).
Multuple Assignment
In python, multuple assignment refers to the assignment of multuple objects to multiple variables wherein objects on both
sides of the assignment operator are tuples.
An example of multuple assignment is as follows,
Another representation of multuple assignment is >>>(p, q, r) = (25, ‘B.Tech’, ‘Fair’). Here, parenthesis are used for
representing tuples and they are optional (which makes user easier to read).
24 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-1: INTrodUcTIoN To pyThoN Computer SCienCe paper-V
1.3.2 Datatypes in Python, Built-in Data Types, Bool Data Type
Q31. Explain various data types in python. Model Paper-II, Q3(b)(ii)
OR
Explain in detail different data types in python with examples.
Answer : B.a[C.a], dec.-17, Q3(a)(i)
Python provides various data types, they are as follows,
1. None Type
It is a special type in python known as null type. It indicates an object that will not contain any value.
2. Numeric Types
Numeric data types depict numbers. There are three types of numeric data types, they are,
(i) Integer Data Type
Integers represent numeric values that are stored, manipulated and expressed inside the variables. Integer data types are
of two types, namely standard integers and long integers.
Example
x = – 28
y = 40
(ii) Float Data Type
Floating point real numbers are represented as forward decimal or scientiic notations. In decimal numbers, decimal point
is used while in scientiic notation exponent is used.
Example
x = 2.45
y = – 6.98
(iii) Complex Data Type
A complex number is an unordered pair of loating point real number and imaginary number.
Syntax
real + imagj
Example
45.2j, 16 + 15.9j
3. Sequences
For answer refer Unit-I, Page No. 26, Q.No. 32.
4. Sets
For answer refer Unit-I, Page No. 28, Q.No. 34.
5. Mappings
For answer refer Unit-I, Page No. 28, Q.No. 34, Topic: Mapping Types.
6. Bool Data Type
The bool datatype will represent the boolean values. Boolean values are of two types namely True or False. Python
considers True as 1 and False as 0.
Example
x=6>2
print(x)
True.
1.3.3 Sequences in Python, Sets, Literals in Python
Q32. Write short notes on sequences with an example.
Answer : B.a[C.a], dec.-17, Q3(a)(ii)
Sequence
A ‘sequence’ is a data structure, that stores elements, which can be accessed using index offsets. For example, the strings
are sequences of characters i.e., a string ‘Hello world!’, contains the sequence of characters, H, e, l, l, o, W, o, r, l, d, !. These
sequence elements are stored, starting at index 0 till the index N – 1, where N is the length of the sequence.
i.e.,
0 1 2 3 4 5 6 7 8 9 10 11
H E L L O W O R L D !
Output
2. Lists
List is like a string, which provides sequential storage mechanism. Through slices, we can access any number of consecutive
elements of list. The unique and lexible characteristics of lists that, differentiate them from strings and arrays are,
(i) List can contain different types of Python objects-standard types, objects and user-deined objects.
(ii) At any given time, single or multiple objects can be inserted, removed and updated to the list.
(iii) List can grow and shrink.
(iv) List can even be sorted, reversed, empty and populated.
(v) A list can be added/removed to/from other lists.
(vi) Creating a list is also very simple.
(vii) Individual or multiple elements of a list can be easily added, updated or removed.
Example
Output
Output
Program
Output
The elements in the set must be separated by commas with in the curly braces. A set will not store any duplicate values.
Elements of sets cannot be retrieved by using the index elements. New elements can be added to the set by using update( ) method.
And remove( ) method is used to remove an element from the set.
2. The Frozenset Datatype
This data type is similar to that of set data type. The elements of the frozenset datatype cannot be modiied. It can be
created by passing a set to frozenset( ) function.
The update( ) function is used to add elements to the frozenset and remove( ) function is used to remove the elements
from the set.
Mapping Types
A map can determine a set of elements as key value pairs. If key is provided the value of it can be accessed.
The dictionary i.e., dict is one of the example of mapping type.
dt = {20 : ‘ABC’, 30 : ‘XYZ’}
The key value pairs in the dictionary are separated by colon(:).
Q36. Write a python program to display different data types using variables and literal constants.
Answer : BSc[C.a], dec.-17, Q3(a)(i)
Here, x stores the number 10 in it. The Python interpreter assumes x as integer type. The third line indicates that x is an
object of class ‘int’. Here, int is treated as the class. Even the function, method, module, lists, sets etc., are treated as objects in
python.
Characters
All the languages such as C and Java have char data type (which represents single character). But python does not have
char data type. Instead it has str data type for representing strings.
Example
In the above example, the variable C is assigned a variable ‘X’. The type( ) function will display that the type of C as
‘str’. Individual characters of any string can be accessed by using the index or position number.
Example
OR
Explain about user-deined data types with examples.
Answer : B.Sc[C.a], dec.-17, Q3(b)(ii)
Output
2. Arrays
An array is nothing but an object that contains a set of elements of same data type. Arrays in python can store only one type
of elements. The size of the arrays can be increased and decreased dynamically. Size of arrays are not required to be mentioned
in Python. It allows the elements to be added or deleted automatically. Arrays can be created or used by using the module ‘array’.
Arrays can be created in the following way,
arrayname = array.array(typecode, [elements])
Here, type code represents the type of array elements. It will be a single character such as ‘b’ representing signed integer,
‘f’ representing loating Point etc.
Example
Output
Output
The output of these three statements is same i.e., Hello world as all three names binded to same string.
SIA PUBLISHERS and dISTRIBUTORS PVT. LTd. 33
Computer SCienCe paper-V python-i
Reserved Words
Keywords are reserved words which forms a construct of the language. Use of these keywords for any other purpose
results syntax error.
Table depicts keywords used in Python.
S.No. Keyword
1 and
2 as
3 assert
4 break
5 class
6 continue
7 def
8 del
9 elif
10 else
11 except
12 exec
13 inally
14 for
15 from
16 global
17 if
18 import
19 in
20 is
21 lambda
22 not
23 or
24 pass
25 print
26 raise
27 return
28 try
29 while
30 with
31 none
32 yield
Table: Keywords
34 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-1: INTrodUcTIoN To pyThoN Computer SCienCe paper-V
Built-ins
Built-ins are special names identiiers used by interpreter. These are not keywords but considered as reserved for system.
Therefore, programmers should not use them. Built-ins are members of built-in module. Interpreter automatically imports the
built-in module before the program begins or user enter the >>> prompt in the interpreter. They can also be used as global
variables that can be accessed anywhere in programs.
Special Underscore Identiiers
In python, special underscore variables are also used. These variables are both preixed and sufixed. Some of these
underscore identiiers are as follows,
_xxx
It requests private name that integrates within classes.
_ _ xxx
It states that donot import with ‘from module import *’.
_ _xxx_ _
It is a system deined name.
3. Write a Python program to accept student information from users and print it.
Internal aSSeSSment
objectIve type
I. Multiple Choice
1. The term ____________ refers to capability of the programming language, to accept and handle
additional performance, upon the addition of new hardware to system. [ ]
(a) Portability (b) Scalability
(c) Extensibility (d) Robust
2. The development of python language was started in the year ____________ by Guido van Rossum. [ ]
(a) 1989 (b) 1990
(c) 1972 (d) 2000
3. ____________ are reserved words that form a construct of the language. [ ]
(a) Identiiers (b) Keywords
(c) Variables (d) Operators
4. ____________ represent numeric values which are stored, manipulated and expressed inside the variables. [ ]
(a) Strings (b) Boolean
(c) Integers (d) Character
5. ____________ can be deined as a storage location in memory. [ ]
(a) Keyword (b) Identiier
(c) Assignment operator (d) Variable
6. The _____________ type of objects can have two possible values True and False. [ ]
(a) Boolean (b) Integers
(c) Strings (d) Variable
7. _________ method is used to remove an item if it is present in another set. [ ]
(a) add( ) (b) clear( )
(c) remove( ) (d) discard( )
8. _________ refers to python’s mapping type. [ ]
(a) Dictionaries (b) Tuples
(c) Lists (d) Set
9. _________ is used to specify mapping variable. [ ]
(a) # (b) (var)
(c) <sp> (d) m.n
10. ________ is used, to display the raw strings without performing any translation to special or
non-printed characters. [ ]
(a) Format operator (b) Unicode string operator
(c) Raw string operator (d) String templates
SIA PUBLISHERS and dISTRIBUTORS PVT. LTd. 37
Computer SCienCe paper-V python-i
2. Python is not only a programming language but also a software package called as ____________.
5. ____________ refers to a set of valid string that can be used as names in a computer language.
6. The block of code in python begins with ____________ and ends with the irst unindented line.
7. ____________ are immutable data types that contain series of characters under single name.
8. The programming languages C, C++ and Java make use of ____________ for deining a block of code..
9. A ________ is a data structure, that stores elements which can be accessed using index off sets.
10. _________ are immutable data types, restricting their values to be changed.
Key
I. Multiple Choice
1. Python
2. Interpreter
4. Python
5. Identiiers
6. Indentation
7. Strings
8. Braces{ }
9. Sequence
10. Strings
Answer :
The byte code instructions are converted into machine code by a PVM.
Answer :
When the multiline commends are placed before any module function, class or method, they are referred as documentation
strings.
Answer :
Variable can be deined as a storage location in memory. It stores data values of the programs and provides whenever
required to work on.
Answer :
A literal can be deined as a constant value stored in variable of a program.
Answer :
Identiiers refers to a set of valid strings that can be used as names in a computer language.
2 statements In pythOn
Learning Objectives
After studying this unit, a student will have a thorough knowledge about the following concepts,
Ø Various types of operators
Ø Mathematical functions
intrOductiOn
An operator can be deined as a symbol which performs speciic operations such as mathematical, logical and
relational manipulations using one or more operands.
Python supports a large number of operators such as arithmetic, relational, logical, assignment, bitwise,
membership and identity operators. If multiple operators are found in an expression then the order of evaluation is
based on their precedence. For this, python uses PEDMAS rules. Python input and output statements are used to
read and write the data values from and to the input and output devices respectively. Python has various types of
control statements to control the low of execution. They are if, if..else, if..elif..else, for, while, pass, assert, break
and continue statements.
part-a
shOrt QuestIOns wIth sOlutIOns
Q1. Deine operator and list out the operators used in python.
Answer : Model Paper-I, Q2(a)
Operator
An operator can be deined as a symbol which perform speciic operations such as mathematical, logical and other
manipulations using one or more operands. Python supports, large number of operators.
Types of Operators
The operators that are present in python are as follows,
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Bitwise operators
6. Membership operators
7. Identity operator.
Q2. What are identity operators?
Answer :
Identity Operators
These operators are used to compare two objects with their memory addresses. Python provides two operators they are
mentioned below,
Operator Function
is It is determined as true when the variables are on one side of the operator that points
to same object or else false.
is not It is determined as false when the variables on one side of the operator points to
same object or else true.
Example
Boolean operators are used to operate on bool type literals. Such as true and false. The generate bool type output. That is
the output will be either true or false.
Boolean operators in python are as follows,
1. and
It is a boolean and operator.
x and y
The ‘and’ operator returns true if both x and y are true. Otherwise false is returned.
42 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-2 OperaTOrs, INpUT aNd OUTpUT, cONTrOl sTaTemeNTs IN pyThON Computer SCienCe paper-V
2. or
It is a boolean or operator.
x or y
The ‘or’ operator returns true if either x or y is true. Otherwise it returns false.
3. not
It is a boolean not operator.
not x
The ‘not’ operator returns true if x value if false otherwise is return true.
Q4. Write about bitwise operators.
Answer : Model Paper-III, Q2(a)
These operators are used to perform bit by bit operation on bits. Python provides certain bitwise operators mentioned as
below,
Input
The input is read from the input devices by using the input function. It reads the data value of the variables from the input
devices. The statement consists of assignment statement for the variable. The variable with this will change its value to the newly
assigned value provided as input. The user is prompted for the speciic input by a text string.
Example
Other than input function, another function provided by python for reading input is rawinput( _) function.
Example
Programs are run at command lines by using run command such as python program name in python. Programs can be
even designed to accept arguments at its command line. The arguments can be input to the program.
Example
product py
inport sys
product = int(sys.argv[1]) * int(sys.argv[2])
print(‘product = ’, product)
Output
Indentation can be deined as the space before beginning the statement. The programming language such as C, C++ and
Java makes use of braces { } for deining a block of code. The python makes use of indentation. The block of code (loop, function
etc) in python begins with indentation and ends with the irst unindented line. The indentation will be decided by the programmer
itself but the consistency should be maintained throughout the block. Generally four whitespaces are preferred for indentation
over tabspace.
For example, the function body will be indented under the function. The ‘if’ statement body or ‘then’ statement will be
indented under if. The statement that are indented as a group are together called a block. But the statements of a block should be
indented with same amount. If this is not done the python will produce error messages about inconsistency of indentation.
The programmer in python can select a block of code and adjust their indentation. This can be done by pressing tab key
for adjusting the indentation. To remove or decrease the indentation shift-tab can be used.
Q8. What are nested loops?
Answer :
The concept of nesting the loop involves embedding of one loop inside another loop. The embedding loop is called outer
loop and the embedded loop is called inner loop. These loops are called nested loops. Syntax of if is as follows,
loop expression:
statement(s)
loop expression:
statement(s)
statement(s)
The inner loop is executed first and the outer loop is executed later on.
Program
Output
elif condition n:
Statement n
else:
Statement
46 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-2 OperaTOrs, INpUT aNd OUTpUT, cONTrOl sTaTemeNTs IN pyThON Computer SCienCe paper-V
Q13. Give the operator precedence in python.
If multiple operators are found in an expression then, the order of evaluation is determined by operator precedence and
associativity. Apart from this, python follows certain mathematical rules for mathematical operators. The word PEMDAS is used
to remember the rules.
(a) Parentheses is used to evaluate an expression in sequence and it has the highest precedence. Therefore, the values which
are in parentheses in an expression are evaluated irst 3*(4– 1) is 9. Here the operands within the parenthesis are evaluated
irst i.e., 4 – 1 = 3. Next the result is multiplied by 3 i.e., 3 * 3 = 9.
(c) Multiplication and division have the same precedence: They have higher precedence than addition and subtraction. The
addition and subtraction posses same precedence.
Example: 5* 2 – 1 is 9 not 5.
Operators which are having same precedence are evaluated from left to right.
Operator Name
[...], {...}, (...) List, dictionary creation, Tuple
'- - -' String conversion
s[i : j], s[i] Slicing and Indexing
s.attr Attributes
f(- - -) Function calls
+x, –x, ~x Unary operators
x**y Power (right associative)
x%y, x/y, x*y, x//y Modulo, division, multiplication, loor division.
x – y, x + y Substraction, Addition
x>>y, x<<y Bit-shifting
x&y Bitwise and
x^y Bitwise exclusive or
x|y Bitwise or
x>y, x<y, x<=y, x>=y Identify, Comparison and Sequence Membership
Tests
x!=y, x==y Not equal, equal operator
x is not y, x is y Identity operators
x not in s, x in s Membership operators
not x Logical negation
x and y Logical and
x or y Logical or
Lambda args:expr Anonymous function
Examples
a = a*10 [Simple assignment statement]
a* = 10 [Augmented assignment statement]
The set of symbols that can be used in the augmented statements are,
+= *= %= <<= &= /=
– = /= **= >>= ∧=
In Python, pre/post increment and pre/post decrement are not supported.
For example,
a++
a––
++a
––a
In the Augmented Assignment Statements, the object at the left hand side of the operator is examined only once, unlike
in the simple assignment statement where it is examined twice.
Examples
When, binary AND operation is performed on p and q then, the obtained result is 8 (1000).
Binary OR operation is performed on p and q then, the obtained result is 29 (11101).
When, Binary XOR operation is performed on p and q then, the obtained result is 21 (10101).
Binary ones complement result is 243 (11110011).
Binary left shift result is 192 (1100000).
Binary Right shift result is 0(0).
(ii) Membership Operators
These operators are used to test the membership in an order like strings, lists or tuples. These are of two types such as,
Operator Description
in It is determined as true when the variables on one side of the
operator points to same object or else false.
not in It is determined as true if the variables are not found in a particu-
lar order or else false.
Example
Operator Function
is It is determined as true when the variables are on one side of
the operator that points to same object or else false.
is not It is determined as false when the variables on one side of the
operator points to same object or else true.
Example
If these statements are written in a script, the same result will not be generated. The expression result will only get displayed
when a print statement is used with the expression in the script.
Precedence and Associativity
If multiple operators are found in an expression then, the order of evaluation is determined by operator precedence and
associativity. Apart from this, python follows certain mathematical rules for mathematical operators. The word PEMDAS is used
to remember the rules.
Precedence of the operators is discussed below,
(a) Parentheses is used to evaluate an expression in sequence and it has the highest precedence. Therefore, the values which
are in parentheses in an expression are evaluated irst 3*(4– 1) is 9. Here the operands within the parenthesis are evaluated
irst i.e., 4 – 1 = 3. Next the result is multiplied by 3 i.e., 3 * 3 = 9.
(b) The second highest precedence is for exponentiation.
Example: 4** 2 + 1 is 17 but not 64.
SIA PUBLISHERS and dISTRIBUTORS PVT. LTd. 55
Computer SCienCe paper-V pyThON-1
(c) Multiplication and division have the same precedence: They have higher precedence than addition and subtraction. The
addition and subtraction posses same precedence.
Example: 5* 2 – 1 is 9 not 5.
Operators which are having same precedence are evaluated from left to right.
Example
In an expression a value is divided by 2 and then, multiplied by pi. Here, the division is computed irst then, the resultant
is multiplied with pi.
Operator Name
[...], {...}, (...) List, dictionary creation, Tuple
'- - -' String conversion
s[i : j], s[i] Slicing and Indexing
s.attr Attributes
f(- - -) Function calls
+x, –x, ~x Unary operators
x**y Power (right associative)
x%y, x/y, x*y, x//y Modulo, division, multiplication, loor division.
x – y, x + y Substraction, Addition
x>>y, x<<y Bit-shifting
x&y Bitwise and
x^y Bitwise exclusive or
x|y Bitwise or
x>y, x<y, x<=y, x>=y Identify, Comparison and Sequence Membership
Tests
x!=y, x==y Not equal, equal operator
x is not y, x is y Identity operators
x not in s, x in s Membership operators
not x Logical negation
x and y Logical and
x or y Logical or
Lambda args:expr Anonymous function
Mathematical Functions
Python provides certain functions to perform mathematical operations. It provides a math module that contains such
functions. Initially this module must be imported into the program using import statement.
import math
56 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-2 OperaTOrs, INpUT aNd OUTpUT, cONTrOl sTaTemeNTs IN pyThON Computer SCienCe paper-V
Any function for example sqrt( ) can be called by using the above module.
p = math.sqrt(5)
The math module can also be imported as shown below,
import math as mt
Here ‘mt’ is the user-deined name used to refer math.
If the user want to import speciic functions from import then from keyword is used.
from math import sqrt
Various functions of math module are depicted as follows,
1. degrees(a)
It converts the angle value a from radians into degrees.
2. sin(a)
It generates the sine value of a.
3. ceil(a)
It generates the next higher integer of a value.
4. loor(a)
It decreases the a value to the one less than it.
5. isnan(a)
It returns true if a is a NaN. Otherwise, it returns false.
6. gcd(p, q)
It produces greatest common divisor of p and q.
7. isinf(a)
It returns true if a is positive or negative ininity otherwise it returns false.
8. trun(a)
It returns the truncated value of x to integer value.
9. factorial(a)
It returns the factorial of a.
10. fmod(p, q)
It returns the remainder of division of p and q.
11. cos(a)
It returns the cosine value of a.
12. exp(a)
It returns exponentiation of a.
13. tan(a)
It returns tangent value of a.
14. fabs(a)
It generates the absolute value of a.
15. fsum(vals)
It returns the sum of loat values.
16. modf(a)
It returns the loat as well as integral parts of a.
17. log10(x)
It returns the base-10 logarithm of a
18. log(x, [, base])
It returns the natural log of a of speciied base.
SIA PUBLISHERS and dISTRIBUTORS PVT. LTd. 57
Computer SCienCe paper-V pyThON-1
19. sqrt(a)
It returns the square root of a
20. pow(p, q)
It raises the p value to power of q
21. radians(a)
It returns the converted value of a from degrees to radians.
Various constants of math module are as follows,
1. pi : It depicts the mathematical constant
p = 3.141592 . . . with high precision
2. inf : It depicts the loating point positive ininity
3. e : It depicts the mathematical constant
e = 2.718281 . . .
4. nam : It depicts the loating print “not a member” value.
Python input and output statements are used to read and write the data values from and to the input and output devices
respectively.
Input Output
Input devices Output devices
Input Statement
The input is read from the input devices by using the input function. It reads the data value of the variables from the input
devices. The statement consists of assignment statement for the variable. The variable with this will change its value to the newly
assigned value provided as input. The user is prompted for the speciic input by a text string.
Example
Other than input function, another function provided by python for reading input is rawinput( _) function.
Example
The string can be enclosed in either single quotes or double quotes. Escape character ‘\t’ indicates tab space and ‘\n’ indicates
a new line. Similarly even other escape sequences can be used in print function. The operator * indicates repetition of the
string and operator + performs addition operator between strings.
print function can display the variable values when variables are passed to it.
To separate with delimeters ‘sep’ attribute is used. ‘sep’ is nothing but separator.
The elements of a particular object can be printed by passing objects such as lists, tuples or dictionaries to print( ) function.
The variables can also be used along with strings in print( ) function.
The output can be formatted by using special operator ‘%’ and formatting string.
OR
Write a python program to display command line arguments.
(Refer Only Topics: Example, Output)
Answer : B.Sc[C.A], Dec.-17, Q4(b)(ii)
In the above example, the program computes the product of two numbers. At command line the program is run using the
command python followed by program name. The arguments 6 and 3 are passed as parameters to the program. They are called
as command line arguments. They are entered as input to the program from the keyboard separated by the keyboard. They are
by default stored in the list of variables starting from argv[0]. It is contained in sys module. The variable argv[0] stores program
name, argv[1] stores first command line argument and so on.
argv 'product.py' '6' '3'
argv[0] argv[1] argv[2]
Number of command line arguments can be known by using len( ) function. This function will read the command line
arguments and display the count of them
x = len(sys.argv)
The string arguments must be enclosed in quotations as shown below,
‘ “Halo” ’
“ ‘Halo’ ”
Arguments can converted into user desired such as int or float as shown below,
int(sys.argv[1])
float(sys.argv[1])
Command line arguments can be passed by using argparse module, with this user friendly programs can be designed.
When invalid arguments are provided the argparse module will generate help and usage messages to the user. In order to use this
module, it should be imported as shown below,
import argparse
SIA PUBLISHERS and dISTRIBUTORS PVT. LTd. 61
Computer SCienCe paper-V pyThON-1
The ArgumentParser class will be invoked only by using the object of it.
parser = argparse.ArgumentParser( )
The above statement creates an object of the ArgumentParser.
cmd1.py
import argparse
parser = argparse.ArgumentParser( )
parser.add_argument(“echo”)
args.parser.parse_args( )
print(args.echo)
Output
Control Statements
Control statements are the statements that allows the programmer to specify the next statement that must be executed
depending on some conditions.
if Statement
The if statement contains the following three components,
(i) The keyword ‘if’
(ii) An expression or a condition and
(iii) The code.
(i) The Keyword ‘if’
The ‘if’ clause is executed, only if the expression is true otherwise, execution starts at the next statement following the
code.
(ii) An Expression or a Condition
An expression is tested for its truth value. If the expression evaluates to non-zero or Boolean true then the code is executed.
Syntax
if expression:
Statement1
Statement2
Example
days = int(input(“How many days does leap year contain?: ”))
if days == 366:
print(“You are right!!”)
62 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-2 OperaTOrs, INpUT aNd OUTpUT, cONTrOl sTaTemeNTs IN pyThON Computer SCienCe paper-V
Output
Output
OR
Write a python program to accept a number from the keyboard and test whether it is even or odd.
(Refer Only Topics: Example, Output)
Answer : B.Sc[C.A], Dec.-17, Q4(a)(i)
if...else Statement
This statement is used to execute a set of statements if the condition is true otherwise it executes another set of statements.
syntax of if...else is as follows,
if condition :
statements
:
else :
statements
The if is succeeded by a condition and a set of statements. If the condition is true the statements following if condition
will be executed.
If the condition is false the statements following else will be executed.
Example
In the above example initially the input is accepted from user into a. The value of ‘a’ is divided by 2 using % operator.
This operator generates remainder of division operator. If the remainder is 0 then the statement following if condition is executed.
If the remainder is non zero then the statement following else will be executed.
Q25. Write how and when if-elif-else is used. Model Paper-I, Q4(b)(ii)
OR
Explain if-elif-else statement with a suitable program.
Answer : B.Sc[C.A], Dec.-17, Q4(b)(i)
if
The if clause is executed only if the expression is true otherwise execution starts at the next statement following the code.
An expression is tested for its truth value. If the expression evaluates to non-zero or Boolean true then the code is executed.
Syntax
if expression:
Statement1
Statement2
else
The else statement can be used in conjunction with the if statement. If the statement if evaluates to a Boolean value false
then the code in the else block gets executed.
Syntax
if condition:
Statement1
else:
Statement2
elif
Like else statement, elif is also optional. elif in python is else_if statement. In else statement there is only one statement
atmost but elif can be numerous in a python program.
The execution of the block continues till the condition becomes true.
Syntax
if condition1:
Statement1
elif condition 2:
Statement2
elif condition n:
Statement n
else:
Statement
SIA PUBLISHERS and dISTRIBUTORS PVT. LTd. 65
Computer SCienCe paper-V pyThON-1
Some of the problems or situations might contain multiple conditions. Such cases can be handled by using multiple elif
clauses after an if and before else clause. This is depicted as follows,
if expression1:
Statement1
Statement2
elif expression2:
Statement3
Statement4
elif expresion3:
Statement5
Statement6
else:
Statement7
Statement8
In the above scenario, python will evaluate each and every expression sequentially. The statements are executed only if
the expression above them is true. If no expression is true then the statements under else are executed.
Example
Output
2.3.2 The while Loop, The for Loop, Ininite Loops, Nested Loops
Q26. Explain the working of while and for loops.
Answer :
‘while’ Loop
‘while’, is the irst conditional looping statement in python. In ‘if’ statement, the code is executed if the condition is true,
whereas, in while the code is executed in a loop until the condition becomes false.
Syntax
while condition
Code to be executed.
The code in the while loop, gets executed repeated number of times, until the expression (condition) becomes false
(Boolean value false).
Whenever a user does know the number of times a loop need to execute, it is better to use the ‘while’ statement.
Counting Loops
Output
With each iteration, the condition in the while loop is checked, whenever condition becomes false control comes out of
the loop.
‘for’ Loop
The for statement is a powerful looping construction in Python. The looping mechanism in for statement is applied, over
the sequence members. for statement calls the next( ) method of an iterator and ends when StopIteration exception is raised. List
comprehensions and generator expressions also uses ‘for statement’.
Syntax
for var in <object> :
<statements>
To repeat the code in the for loop, each time the iteration variable is set to the current element of the object.
Output
The iteration variable ‘spam’, always contains only a single character when iterating over a string. This construct is useful
in debugging of sequences in the for loop.
(ii) Iterating by Sequence Item
Example
Output
For each iteration in the above example, the list is iterated and the variable ‘x’ contains the list elements.
68 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-2 OperaTOrs, INpUT aNd OUTpUT, cONTrOl sTaTemeNTs IN pyThON Computer SCienCe paper-V
(iii) Iterating by Sequence Index
Example
Output
OR
What the term “Nested loops” refers to? Explain.
(Refer Only Topic: Nested Loops)
Answer : B.A[C.A], Dec.-17, Q4(b)(i)
Infinite Loop
These loops never terminate. The number of iterations in this loop is ininite.
Example
The above loop is an ininite loop, and gets executed ininite number of times, as the condition remains true always. Since,
true never becomes false, it executes continuously. These ininite loops are useful, when the server needs to run continuously to
serve the client requests.
Nested Loops
The concept of nesting the loop involves embedding of one loop inside another loop. The embedding loop is called outer
loop and the embedded loop is called inner loop. These loops are called nested loops. Syntax of it is as follows,
loop(condition)
{
loop(condition)
{
}
}
The inner loop is executed first and the outer loop is executed later on.
70 SIA PUBLISHERS and dISTRIBUTORS PVT. LTd.
UNIT-2 OperaTOrs, INpUT aNd OUTpUT, cONTrOl sTaTemeNTs IN pyThON Computer SCienCe paper-V
Example
Output
2.3.3 the else suite, the break statement, the continue statement, the pass statement,
the assert statement, the return statement
Q28. Write short notes on else suite.
Answer :
Else Suite
Python allows else suite to be used along with for loop or while loop. The statements of defined after the keyword else are
called suite. The execution of statements within else suite are not dependent upon the execution of statements within the loop.
Example
In the above example, the for part as well as the else part both are used executed. When else is used with if, only one of
them will be executed. But when else is used with any loops, both of them will be executed.
In the above example, the statement in for will be executed 10 times and statement within else will be executed once.
Q29. Discuss in brief about the following statements,
(i) break
(ii) continue
(iii) pass. Model Paper-III, Q4(b)
OR
Explain break and continue statement with the help of for loop in an example.
(Refer Only Topics: break Statement, continue Statement)
Answer : B.Sc[C.A], Dec.-17, Q4(a)(ii)
Output
Output
If the structure of the code is used without interfacing with the other parts that already exist, pass statement is used.
It is helpful in debugging and development stages. It is also used in exception handling.
Q30. Discuss in brief about the following,
(i) break
(ii) continue
(iii) return
(iv) assert statement.
OR
Explain the use of the following statements with an example,
(i) break
(ii) continue
(iii) return.
Answer : B.A[C.A], Dec.-17, Q4(a)
(i) break
For answer refer Unit-II, Page No. 72, Q.No. 29(i).
(ii) continue
For answer refer Unit-II, Page No. 72, Q.No. 29(ii).
(iii) return Statement
A function contains a set of statements that together perform a task. Upon completion of that particular task. The function
returns the result. The function should return the result to the calling function.
Syntax
return expression
Example
In the above example, a function is defined to compute the square of a number. The result is returned back by using the
return statement. The function will only work when it is invoked or called. So the function square is called and the returned
result is stored in variable res. When the function is called the control goes to function definition and when return statement is
encountered the result is returned to calling statement. Finally the result is returned.
(iv) assert Statement
The assert statement is used to check whether the given condition is fulfilled or not.
Syntax
assert expression, message
In the above syntax ‘message’ is optional.
Example
Output
In the above example, asserts checks whether the number ‘a’ divided by 2 will generate the remainder ‘0’ or not. If ‘0’ is
the result then the following print statement is executed, otherwise an assertion error will be displayed.
The assertion errors are nothing but the exceptions. They can be handled by using ‘try...except’ statement.
Example
a = int(input(‘Enter a number:’)
try:
assert(a%2 = = 0)
print(‘Given number is even’)
except AssertionError:
print(“Entered number is not divisible by 2”)
The assert statement must be used in try block and exception must be included in exception block.
exercIse QuestIOns
Internal assessment
ObjectIve type
I. Multiple Choice Questions
1. In python ____________ refers to the assignment of single object to multiple variables. [ ]
(a) Augmented assignment (b) Multiple assignment
(c) Variable assignment (d) Multiple assignment
2. Other than input function, another function provided by python for reading input is ____________ function.
[ ]
(a) Output( ) (b) Rawinput( )
(c) Both (a) and (b) (d) None of the above
3. _________ is used to copy the bit, if it is available in any one operand. [ ]
(a) Binary OR (b) Binary XOR
(c) Binary AND (d) Binary Left Shift
4. _________ operators negate or link two or more expressions. [ ]
(a) Arithmetic operators (b) Comparison operators
(c) Boolean operators (d) None of the above
5. ________ calls the next( ) method of an iterator and ends when stop iteration exception is raised. [ ]
(a) if statement (b) while statement
(c) for statement (d) if-else statement
6. When _______ statement is encountered in a loop, it stops executing the succeeding times and transfers the control
to the top of loop. [ ]
(a) break statement (b) pass statement
(c) if statement (d) continue statement
7. To execute the blocks without any code, we use empty braces but in python we use _______. [ ]
(a) pass statement (b) break statement
(c) continue statement (d) while statement
8. List comprehensions and generator expressions also uses ________. [ ]
(a) while statement (b) for statement
(c) continue statement (d) if statement
9. The ‘if’ clause is executed, only if the expression is ________ otherwise, execution starts at the next statement fol-
lowing the code. [ ]
(a) True (b) False
(c) Both (a) and (b) (d) None of the above
10. The _________ statement is used when a condition demands the control to come out the loop. [ ]
(a) exit (b) break
(c) terminate (d) close
2. The block of code in python begins with _________ and ends with the irst unindented line.
5. _________ operators are used to compare two objects with their memory addresses.
6. The statements in the _________ loop, gets executed repeated number of times, until the expression becomes false.
7. _________ is used when a condition demands the control to come out of the loop.
8. The _________ statement is used in cases, where a python statement does nothing.
Key
1. Augmented assignment
2. Indentation
3. Shift –tab
4. Augmented assignment
5. Identity
6. While
7. Break statement
8. Pass
Answer :
An operator can be deined as a symbol which perform speciic operations such as mathematical, logical and other
manipulations using one or more operands.
Answer :
Unary minus operator is represented by the symbol minus (–). It is used before a variable to make its value negated.
Answer :
The ‘if’ clause is executed, only if the expression is true otherwise, execution starts at the next statement following the
code.
Answer :
Answer :
Ininite loops never terminate. The number of iterations in this loop is ininite.
FACULTY OF ARTS
B.Sc. (CBCS) III-Semester Examination
December - 2017
Subject: COMPUTER APPLICATIONS
Paper-III (SEC-I)
B: Python-I
Part - a ( 2 × 5 = 10 Marks )
(Short Answer Type)
1. (a) Deine the two modes in python. (Unit-I, Page No. 2, Q1)
OR
2. (a) Give the operator precedence in python. (Unit-II, Page No. 47, Q13)
OR
(b) Explain about indentation in python. (Unit-II, Page No. 44, Q7)
Part - B ( 2 × 15 = 30 Marks )
(Essay Answer Type)
3. (a) (i) Write a python program to display different data types using variables and literal constants.
(Unit-I, Page No. 29, Q36)
(ii) Explain how to write and execute a program in python. (Unit-I, Page No. 17, Q27)
OR
(b) (i) Write in detail about memory management in python. (Unit-I, Page No. 10, Q20)
(ii) Explain about user-deined data types with examples. (Unit-I, Page No. 31, Q38)
4. (a) (i) Write a python program to accept a number from the keyboard and
test whether it is even or odd. (Unit-II, Page No. 64, Q24)
(ii) Explain break and continue statement with the help of for loop in
an example. (Unit-II, Page No. 72, Q29)
OR
(b) (i) Explain if-elif-else statement with a suitable program. (Unit-II, Page No. 65, Q25)
(ii) Write a python program to display command line arguments. (Unit-II, Page No. 61, Q21)
FACULTY OF ARTS
B.A. (CBCS) III-Semester Examination
December - 2017
Subject: COMPUTER APPLICATIONS
Paper-III (SEC-I)
B: Python-I
1. (a) List out the features of python. (Unit-I, Page No. 2, Q2)
OR
(b) Write in brief about any four keywords in python. (Unit-I, Page No. 4, Q12)
2. (a) Write a python program for evaluating an expression entered from keyboard. (Unit-II, Page No. 46, Q11)
OR
Part - B ( 2 × 15 = 30 Marks )
(Essay Answer Type)
3. (a) (i) Explain in detail different data types in python with examples. (Unit-I, Page No. 25, Q31)
(ii) Write short notes on sequences with an example. (Unit-I, Page No. 26, Q32)
OR
(b) (i) How to add the python path in windows? (Unit-I, Page No. 13, Q25)
(ii) What is the difference between C and python? (Unit-I, Page No. 11, Q22)
(i) break
(ii) continue
OR
(b) (i) What the term “Nested loops” refers to? Explain. (Unit-II, Page No. 69, Q27)
(ii) Write a python program to display each char from a string using
sequence index. (Unit-I, Page No. 27, Q33)
Important Questions
Unit- 1
Q1. List and explain the features of python.
Answer : Important Question
Unit- 2
Q1. Deine operator. Describe different types of operators supported by Python with an example for each.
Answer : Important Question