Python
Chapter1
1 marks
[Link] developed Python Programming Language? CO1 LEVEL 1 REMEMBER
a) Wick van Rossum
b) Rasmus Lerdorf
c) Guido van Rossum
d) Niene Stom
2. Which type of Programming does Python support?
a) object-oriented programming
b) structured programming
c) functional programming
d) all of the mentioned
[Link] Python code compiled or interpreted?
Python code is both compiled and interpreted
4. What is pep 8?
PEP stands for Python Enhancement Proposal. It is a set of rules that specify how to format
Python code for maximum readability.
5 Which is the extension of the Python file?
.py
6. Which is used to define a block of code in Python language?
Indentation
7. Which keyword is used for function in Python language?
Def
8. Python supports the creation of anonymous functions at runtime, using a construct called
__________
lambda
9. What is the order of precedence in python?
Parentheses, Exponential, Multiplication, Division, Addition, Subtraction
10. What will be the value of the following Python expression?
4+3%5
Ans 7
5 Marks
1. What are the key features of Python? What type of language is python? Programming
or scripting? 4+1
Python is an interpreted language. That means that, unlike languages like C and its
variants, Python does not need to be compiled before it is run. Other interpreted
languages include PHP and Ruby.
Python is dynamically typed, this means that you don’t need to state the types of
variables when you declare them or anything like that. You can do things
like x=111 and then x="I'm a string" without error
Python is well suited to object orientated programming in that it allows the definition
of classes along with composition and inheritance. Python does not have access
specifiers (like C++’s public, private).
In Python, functions are first-class objects. This means that they can be assigned to
variables, returned from other functions, and passed into functions. Classes are also
first-class objects.
Writing Python code is quick but running it is often slower than compiled languages.
Fortunately Python allows the inclusion of C-based extensions so bottlenecks can be
optimized away and often are. The numpy package is a good example of this, it’s
really quite quick because a lot of the number-crunching it does isn’t actually done by
Python
Python finds use in many spheres – web applications, automation, scientific modeling,
big data applications and many more. It’s also often used as “glue” code to get other
languages and components to play nice.
Python is capable of scripting, but in general sense, it is considered as a general-purpose
programming language.
[Link] are the benefits of using Python? What are Python namespaces? 3+2
Ans: The benefits of using python are-
a. Easy to use– Python is a high-level programming language that is easy to use,
read, write and learn.
b. Interpreted language– Since python is interpreted language, it executes the
code line by line and stops if an error occurs in any line.
c. Dynamically typed– the developer does not assign data types to variables at
the time of coding. It automatically gets assigned during execution.
d. Free and open-source– Python is free to use and distribute. It is open source.
e. Extensive support for libraries– Python has vast libraries that contain almost
any function needed. It also further provides the facility to import other
packages using Python Package Manager(pip).
f. Portable– Python programs can run on any platform without requiring any
change.
g. The data structures used in python are user friendly.
h. It provides more functionality with less coding.
A namespace in python refers to the name which is assigned to each object in python. The
objects are variables and functions. As each object is created, its name along with space(the
address of the outer function in which the object is), gets created. The namespaces are
maintained in python like a dictionary where the key is the namespace and value is the
address of the object. There 4 types of namespace in python-
1. Built-in namespace– These namespaces contain all the built-in objects in python and
are available whenever python is running.
2. Global namespace– These are namespaces for all the objects created at the level of
the main program.
3. Enclosing namespaces– These namespaces are at the higher level or outer function.
4. Local namespaces– These namespaces are at the local or inner function.
3. What are the common built-in data types in Python? What is the difference
between .py and .pyc files? 4+1
Ans: The common built-in data types in python are-
Numbers– They include integers, floating-point numbers, and complex numbers. eg. 1,
7.9,3+4i
List– An ordered sequence of items is called a list. The elements of a list may belong to
different data types. Eg. [5,’market’,2.4]
Tuple– It is also an ordered sequence of elements. Unlike lists , tuples are immutable, which
means they can’t be changed. Eg. (3,’tool’,1)
String– A sequence of characters is called a string. They are declared within single or
double-quotes. Eg. “Sana”, ‘She is going to the market’, etc.
Set– Sets are a collection of unique items that are not in order. Eg. {7,6,8}
Dictionary– A dictionary stores values in key and value pairs where each value can be
accessed through its key. The order of items is not important. Eg. {1:’apple’,2:’mango}
Boolean– There are 2 boolean values- True and False.
Ans: The .py files are the python source code files. While the .pyc files contain the bytecode
of the python files. .pyc files are created when the code is imported from some other source.
The interpreter converts the source .py files to .pyc files which helps by saving time.
4. What are Keywords in Python? Python an interpreted language. Explain.
3+2
Ans: Keywords in python are reserved words that have special meaning. They are generally
used to define type of variables. Keywords cannot be used for variable or function names.
There are following 33 keywords in python-
And
Or
Not
If
Elif
Else
For
While
Break
As
Def
Lambda
Pass
Return
True
False
Try
With
Assert
Class
Continue
Del
Except
Finally
From
Global
Import
In
Is
None
Nonlocal
Raise
Yield
Ans: An interpreted language is any programming language which is not in machine-level
code before runtime. Therefore, Python is an interpreted language.
15 Marks
What are Dict and List comprehensions? What are Literals in Python and explain
about different Literals? Write a Program to calculate the area of a rectangle. How is
memory managed in Python? 3+5+3+4
Ans: Dictionary and list comprehensions are just another concise way to define dictionaries
and lists. Essentially, the only difference between this and the list comprehension is the use of
curly braces to contain the comprehension and the placement of x before the colon to indicate
that this represents the key. This can be then also be used to create a dictionary based on an
already existing list.
Ans: A literal in python source code represents a fixed value for primitive data types. There
are 5 types of literals in python-
1. String literals– A string literal is created by assigning some text enclosed in single or
double quotes to a variable. To create multiline literals, assign the multiline text
enclosed in triple quotes. [Link]=”Tanya”
2. A character literal– It is created by assigning a single character enclosed in double
quotes. Eg. a=’t’
3. Numeric literals include numeric values that can be either integer, floating point
value, or a complex number. Eg. a=50
4. Boolean literals– These can be 2 values- either True or False.
5. Literal Collections– These are of 4 types-
a) List collections-Eg. a=[1,2,3,’Amit’]
b) Tuple literals- Eg. a=(5,6,7,8)
c) Dictionary literals- Eg. dict={1: ’apple’, 2: ’mango, 3: ’banana`’}
d) Set literals- Eg. {“Tanya”, “Rohit”, “Mohan”}
6. Special literal- Python has 1 special literal None which is used to return a null variable.
Ans:
Algorithm to Calculate the Area of a Rectangle
a. Get the length and breadth of the rectangle from the user.
b. Use the relevant formula to calculate the area
Area = Length * Breadth
c. Finally display the area of the rectangle.
This algorithm can be written as code as shown in program
Length = 10
breadth = 20
print(‘ Length = ‘,length,’ Breadth = ‘,breadth)
area = length * breadth
print(‘ Area of Rectangle is = ‘,area)
Ans: Memory is managed in Python in the following ways:
1. Memory management in python is managed by Python private heap space. All
Python objects and data structures are located in a private heap. The programmer does
not have access to this private heap. The python interpreter takes care of this instead.
2. The allocation of heap space for Python objects is done by Python’s memory
manager. The core API gives access to some tools for the programmer to code.
3. Python also has an inbuilt garbage collector, which recycles all the unused memory
and so that it can be made available to the heap space.
Q2. What is namespace in Python? What is PYTHONPATH? What are python modules?
Name some commonly used built-in modules in Python? What are local variables and global
variables in Python? Is python case sensitive? What is type conversion in Python?
1+2+2+3+4+1+2
Ans A namespace is a naming system used to make sure that names are unique to avoid
naming conflicts.
Ans: It is an environment variable which is used when a module is imported. Whenever a
module is imported, PYTHONPATH is also looked up to check for the presence of the
imported modules in various directories. The interpreter uses it to determine which module to
load.
Ans: Python modules are files containing Python code. This code can either be functions
classes or variables. A Python module is a .py file containing executable code.
Some of the commonly used built-in modules are:
os
sys
math
random
data time
JSON
Ans:
Global Variables:
Variables declared outside a function or in global space are called global variables. These
variables can be accessed by any function in the program.
Local Variables:
Any variable declared inside a function is known as a local variable. This variable is present
in the local space and not in the global space.
Ans: Yes. Python is a case sensitive language.
Ans: Type conversion refers to the conversion of one data type into another.
int() – converts any data type into integer type
float() – converts any data type into float type
ord() – converts characters into integer
hex() – converts integers to hexadecimal
oct() – converts integer to octal
tuple() – This function is used to convert to a tuple.
set() – This function returns the type after converting to set.
list() – This function is used to convert any data type to a list type.
dict() – This function is used to convert a tuple of order (key, value) into a dictionary.
str() – Used to convert integer into a string.
complex(real,imag) – This function converts real numbers to complex(real,imag) number.
Q3. What is the Difference Between a Shallow Copy and Deep Copy? How is Memory
managed in Python? How Would You Generate Random Numbers in Python? What Does the
// Operator Do? What Does the ‘is’ Operator Do? 4+2+3+3+3
Deepcopy creates a different object and populates it with the child objects of the original
object. Therefore, changes in the original object are not reflected in the copy.
[Link]() creates a Deep Copy.
Shallow copy creates a different object and populates it with the references of the child
objects within the original object. Therefore, changes in the original object are reflected in the
copy.
[Link] creates a Shallow Copy.
Python has a private heap space that stores all the objects. The Python memory manager
regulates various aspects of this heap, such as sharing, caching, segmentation, and allocation.
The user has no control over the heap; only the Python interpreter has access.
To generate random numbers in Python, you must first import the random module.
The random() function generates a random float value between 0 & 1.
> [Link]()
The randrange() function generates a random number within a given range.
Syntax: randrange(beginning, end, step)
Example - > [Link](1,10,2)
Ans: In Python, the / operator performs division and returns the quotient in the float.
For example: 5 / 2 returns 2.5
The // operator, on the other hand, returns the quotient in integer.
For example: 5 // 2 returns 2
Ans:
The ‘is’ operator compares the id of the two objects.
list1=[1,2,3]
list2=[1,2,3]
list3=list1
list1 == list2 - True
list1 is list2 - False
list1 is list3 – True
Q4. How does break, continue and pass work? What is the difference between range &
xrange? What is pickling and unpickling? What are the generators in python? Whenever
Python exits, why isn’t all the memory de-allocated? Explain split(), sub(), subn() methods of
“re” module in Python. 3+3+3+1+2+3
Ans.
Break - Allows loop termination when some condition is met and the control is transferred to
the next statement.
Continue - Allows skipping some part of a loop when some specific condition is met and the
control is transferred to the beginning of the loop
Pass work - Used when you need some block of code syntactically, but you want to skip its
execution. This is basically a null operation. Nothing happens when this is executed.
Ans: For the most part, xrange and range are the exact same in terms of functionality. They
both provide a way to generate a list of integers for you to use, however you please. The only
difference is that range returns a Python list object and x range returns an xrange object.
This means that xrange doesn’t actually generate a static list at run-time like range does. It
creates the values as you need them with a special technique called yielding. This technique
is used with a type of object known as generators. That means that if you have a really
gigantic range you’d like to generate a list for, say one billion, xrange is the function to use.
Ans: Pickle module accepts any Python object and converts it into a string representation and
dumps it into a file by using dump function, this process is called pickling. While the process
of retrieving original Python objects from the stored string representation is called
unpickling.
Ans: Functions that return an iterable set of items are called generators.
Ans:
1. Whenever Python exits, especially those Python modules which are having circular
references to other objects or the objects that are referenced from the global
namespaces are not always de-allocated or freed.
2. It is impossible to de-allocate those portions of memory that are reserved by the C
library.
3. On exit, because of having its own efficient clean up mechanism, Python would try to
de-allocate/destroy every other object.
Ans: To modify the strings, Python’s “re” module is providing 3 methods. They are:
split() – uses a regex pattern to “split” a given string into a list.
sub() – finds all substrings where the regex pattern matches and then replace them
with a different string
subn() – it is similar to sub() and also returns the new string along with the no. of
replacements.
CHAPTER 2
1Marks