Section A: Easy To Code
Section A: Easy To Code
Section A
Ques. 1: List any four features of python.
Ans. 1:
Easy to Code
Python is a very developer-friendly language which means that anyone and everyone can learn to code it
in a couple of hours or days. As compared to other object-oriented programming languages like Java, C,
C++, and C#, Python is one of the easiest to learn. Python is easy to learn as compared to other
programming languages. Its syntax is straightforward and much the same as the English language. There
is no use of the semicolon or curly-bracket, the indentation defines the code block. It is the recommended
programming language for beginners.
Python is an open-source programming language which means that anyone can create and contribute to its
development. Python has an online forum where thousands of coders gather daily to improve this
language further. Along with this Python is free to download and use in any operating system, be it
Windows, Mac or Linux. Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly working towards
make new python modules and functions. Anyone can contribute to the Python community. The open-
source means, "Anyone can download its source code without paying any penny."
Integrated by Nature
Python is an integrated language by nature. This means that the python interpreter executes codes one line
at a time. Unlike other object-oriented programming languages, we don’t need to compile Python code
thus making the debugging process much easier and efficient. Another advantage of this is, that upon
execution the Python code is immediately converted into an intermediate form also known as byte-code
which makes it easier to execute and also saves runtime in the long run. It can be easily integrated with
languages like C, C++, and JAVA, etc. Python runs code line by line like C,C++ Java. It makes easy to
debug the code.
Highly Portable
Suppose you are running Python on Windows and you need to shift the same to either a Mac or a Linux
system, then you can easily achieve the same in Python without having to worry about changing the code.
This is not possible in other programming languages, thus making Python one of the most portable
languages available in the industry. Python can run equally on different platforms such as Windows,
Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. It enables
programmers to develop the software for several competing platforms by writing a program only once.
1
D20MCA11140
All the classes and its classes are String and all wrapper class are immutable
Type
mutable by default by their nature. by their nature.
Final To create a Mutable object, the To create a Immutable object, the class
Class class don’t require to be final require to be final
List, Set, Dictionary, and User- Number, String, Tuples, Frozen Sets,
Examples
Defined Classes Bytes, and User-Defined Classes
Immutable objects refer to those whose values or content cannot change after initialization as
per the requirement of the user or programmer. In Python, Number, String, Tuples, Frozen Sets, Bytes,
and User-Defined Classes are the types of Immutable objects.
2
D20MCA11140
Mutable objects refer to those objects whose values or the content can be changed after
initialization as per the requirement and usage. Mutable objects are classified as List, Set, Dictionary, and
User-Defined Classes. For example, we declare a list with the values as “Red”, “Green”, and “Orange”
and want to change the last value with “Blue” and First value with “Black”. So, List, Set, and Dictionary
allow to change the values. But the rest don’t allow the same.
3
D20MCA11140
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or
user-defined objects. However, same is not true for the keys.
More than one entry per key not allowed. Which means no duplicate key is allowed. When
duplicate keys encountered during assignment, the last assignment wins.
For example:
Output:
Keys must be immutable. Which means you can use strings, numbers or tuples
as dictionary keys but something like [‘key’] is not allowed.
For example:
Output:
4
D20MCA11140
A lambda function can have any number of parameters, but the function body can only
contain one expression. Moreover, a lambda is written in a single line of code and can also be invoked
immediately.
A lambda function in python has the following syntax.
Syntax of Lambda Function in python
Lambda arguments: expression
Lambda functions can have any number of arguments but only one expression. The expression is
evaluated and returned. Lambda functions can be used wherever function objects are required.
Example of Lambda Function in python
Here is an example of lambda function that doubles the input value.
Output: 10
returned.This function has no name. It returns a function object which is assigned to the identifier double.
5
D20MCA11140
Reusability enhanced reliability. The base class code will be already tested and debugged.
As the existing code is reused, it leads to less development and maintenance costs.
Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
With inheritance, we will be able to override the methods of the base class so that the meaningful
implementation of the base class method can be designed in the derived class. An inheritance
leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered by the
derived class.
The codes are easy to debug. Inheritance allows the program to capture the bugs easily
Inheritance results in better organisation of codes into smaller, simpler and simpler compilation
units.
6
D20MCA11140
A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers.
The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the
size of the array along each dimension.
We can initialize numpy arrays from nested Python lists, and access elements using square brackets:
7
D20MCA11140
Arrays
An array is a collection of items stored at contiguous memory locations. The idea is to store multiple
items of the same type together. This makes it easier to calculate the position of each element by simply
adding an offset to a base value, i.e., the memory location of the first element of the array (generally
denoted by the name of the array).
For simplicity, we can think of an array a fleet of stairs where on each step is placed a value (let’s say one
of your friends). Here, you can identify the location of any of your friends by simply knowing the count
of the step they are on. Array can be handled in Python by a module named array. They can be useful
when we have to manipulate only a specific data type values. A user can treat lists as arrays. However,
user cannot constraint the type of elements stored in a list. If you create arrays using the array module, all
elements of the array must be of the same type.
Index - The location of an element in an array has a numerical index, which is used to identify the
position of the element.
8
D20MCA11140
Data visualization is the most important step in the life cycle of data science, data analytics, or we can say
in data engineering. It is more impressive, interesting and understanding when we represent our study or
analysis with the help of colours and graphics.
Using visualization elements like graphs, charts, maps, etc., it becomes easier for clients to understand the
underlying structure, trends, patterns and relationships among variables within the dataset. Simply
explaining the data summary and analysis using plain numbers becomes complicated for both, people
coming from technical and non-technical backgrounds.
Data visualization gives us a clear idea of what the data wants to convey to us. It makes data neutral for
us to understand the data insights.
Pandas library in python is mainly used for data analysis. It is not a data visualization library but, we can
create basic plots using Pandas. Pandas is highly useful and practical if we want to create exploratory data
analysis plots. We do not need to import other data visualization libraries in addition to Pandas for such
tasks.
As Pandas is Python’s popular data analysis library, it provides several different functions to visualizing
our data with the help of the .plot() function. There is one more advantage of using Pandas for
visualization is we can serialize or create a pipeline of data analysis functions and plotting functions. It
simplifies the task.
To visualize the data we will create a DataFrame that has 4 columns consists of random values using the
Numpy random.rand() function. The IDE we are using is Google Colab. Let’s create each type of plot one
by one.
9
D20MCA11140
10
D20MCA11140
The difference between a discrete random variable is that you can identify an exact value of the variable.
For instance, the value for the variable, e.g., a stock price, only goes two decimal points beyond the
decimal (e.g., 52.55), while a continuous variable could have an infinite number of values (e.g.,
52.5572389658…).
When the PDF is graphically portrayed, the area under the curve will indicate the interval in which the
variable will fall. The total area in this interval of the graph equals the probability of a discrete random
variable occurring.
More precisely, since the absolute likelihood of a continuous random variable taking on any specific
value is zero due to the infinite set of possible values available, the value of a PDF can be used to
determine the likelihood of a random variable falling within a specific range of values.
PDFs are used to gauge the risk of a particular security, such as an individual stock or ETF. They are
typically depicted on a graph, with a normal bell curve indicating neutral market risk, and a bell at either
end indicating greater or lesser risk/reward.
A bell at the right side of the curve suggests greater reward, but with lesser likelihood, while a bell on the
left indicates lower risk and lower reward.
The Probability Density Function(PDF) defines the probability function representing the density of a
continuous random variable lying between a specific range of values. In other words, the probability
density function produces the likelihood of values of the continuous random variable.
Sometimes it is also called a probability distribution function or just a probability function. However, this
function is stated in many other sources as the function over a broad set of values. Often it is referred to
as cumulative distribution function or sometimes as probability mass function(PMF).
However, the actual truth is PDF (probability density function ) is defined for continuous random
variables, whereas PMF (probability mass function) is defined for discrete random variables.
Formula
11
D20MCA11140
Properties:
Let x be the continuous random variable with density function f(x), and the probability density function
should satisfy the following conditions:
For a continuous random variable that takes some value between certain limits, say a and b, the
PDF is calculated by finding the area under its curve and the X-axis within the lower limit (a) and
upper limit (b). Thus, the PDF is given by
12
D20MCA11140
Ans. 10:
Actual Parameters :
The arguments that are passed in a function call are called actual arguments. These arguments are defined
in the calling function. These are the variables or expressions referenced in the parameter list of a
subprogram call. There is no need to specify datatype in actual parameter.
This value 2 and 3 are the actual parameters. Those values are passed
to the method addition, and the sum of two numbers will display on the
screen. Again, new two integer values are passed to the addition
method. Now the actual parameters are 4 and 5.
Formal Parameters :
These are the variables or expressions referenced in the parameter list of a subprogram specification. The
datatype of the receiving value must be defined. The scope of formal arguments is local to the function
definition in which they are used.
The method name is to identify the method. The “def” keyword is a statement for defining a function
in Python. The formal parameter is enclosed in parenthesis.
13
D20MCA11140
When a function is called, the values The parameter used in function definition
(expressions) that are passed in the function statement which contain data type on its
call are called the arguments or actual time of declaration is called formal
parameters. parameter.
These are the variables or expressions These are the variables or expressions
referenced in the parameter list of a referenced in the parameter list of a
subprogram call. subprogram specification.
Actual Parameters are the parameters which Formal Parameters are the parameters
are in calling subprogram. which are in called subprogram.
There is no need to specify datatype in actual The datatype of the receiving value must be
parameter. defined.
14
D20MCA11140
Section B
Ques. 1: Write a python program to find whether the given string is palindrome or not without using
functions.
Ans. 1:
Output:
15
D20MCA11140
Ans. 2: A Python data type conversion method is called a conversion of type. We can convert objects of
string type to a numeric value, convert them to various container types, etc. Python primarily provides
two types of conversion methods: implicit conversion type and explicit conversion type.
In Python, the conversion of data type is called an implicit conversion of data type when it takes place
during compilation, or during run time. Python manages the conversion of the implicit data type, so we do
not directly convert the data type to another data type.
Implicit type casting means conversion without losing the original significance of data forms. This form
of typecasting is important if you want to adjust the data without changing the importance of the values
stored in the variable.
Conversion of the implicit type occurs automatically if a value is copied to its compatible type. Strict
guidelines for conversion of forms shall be enforced during conversion. If the operands are of two
different data types, then the operand with a lower data type will be automatically converted to a higher
data type.
Let us add two Python variables of two types of data, and store the result in a variable, and see if the
Python compiler converts the resultant variable data type.
16
D20MCA11140
Output:
In the example above, we have taken and added two variables of integer and float data.
In addition, we have declared and stored the result of the added variable called ‘sum’. By checking the
sum variable data type, the Python compiler transforms the sum variable data type automatically into the
float data type. This is referred to as conversion of implicit type.
The explanation for converting the sum variable into the floating data type is that if the compiler had
converted it into the integer data type, the fractional part had to be omitted and data loss would have
occurred. Python thus turns smaller data types into larger data types to avoid data loss.
In certain instances, Python cannot use implicit conversion and explicit conversion of the form enters into
play.
Users convert the data type of an object to the data type required by Explicit Type Conversion. To
perform explicit type conversion, we use predefined functions such as int(), float(), str().
This conversion form is also called typecasting as the user casts (changes) the object data type.
The conversion of the explicit type happens when the programmer specifies the program clearly and
explicitly. There are several built-in Python functions for explicit form conversion.
Syntax:
17
D20MCA11140
Example:
Output:
Variable value1 is the data type number and variable value2 is the data type string. If these two entries are
inserted and the value is stored in the variable called result1, a TypeError happens as seen in the
output. So, we must use explicit casting to perform this operation.
We’ve turned the variable value2 to int and then inserted variable value1 and value2. The amount is
stored in the result2 variable and 400 is shown in the output.
18
D20MCA11140
Ques. 3: Define set in python. How are sets used in python? Give example.
Ans. 3:
A Python set is the collection of the unordered items. Each element in the set must be unique, immutable,
and the sets remove the duplicate elements. Sets are mutable which means we can modify it after its
creation.
Unlike other collections in Python, there is no index attached to the elements of the set, i.e., we cannot
directly access any element of the set by the index. However, we can print them all together, or we can
get the list of elements by looping through the set.
Creating a set
The set can be created by enclosing the comma-separated immutable items with the curly braces {}.
Python also provides the set() method, which can be used to create the set by the passed sequence.
Example:
Output:
19
D20MCA11140
It can contain any type of element such as integer, float, tuple etc. But mutable elements (list, dictionary,
set) can't be a member of set. Consider the following example.
Output:
Adding items to
Python provides the add() method and update() method which can be used to add some particular item to
the set. The add() method is used to add a single element whereas the update() method is used to add
multiple elements to the set.
Example:
20
D20MCA11140
Output:
21
D20MCA11140
22
D20MCA11140
SN Method Description
7 intersection_update(.... It removes the items from the original set that are
) not present in both the sets (all the sets if more
than one are specified).
23
D20MCA11140
24
D20MCA11140
Major OOP (object-oriented programming) concepts in Python include Class, Object, Method,
Inheritance, Polymorphism, Data Abstraction, and Encapsulation.
A class is a collection of objects or you can say it is a blueprint of objects defining the common attributes
and behavior. Now the question arises, how do you do that?
Well, it logically groups the data in such a way that code reusability becomes easy. I can give you a real-
life example- think of an office going ’employee’ as a class and all the attributes related to it like
’emp_name’, ’emp_age’, ’emp_salary’, ’emp_id’ as the objects in Python. Let us see from the coding
perspective that how do you instantiate a class and an object.
Example:
Inheritance:
Ever heard of this dialogue from relatives “you look exactly like your father/mother” the reason behind
this is called ‘inheritance’. From the Programming aspect, It generally means “inheriting or transfer of
characteristics from parent to child class without any modification”. The new class is called
the derived/child class and the one from which it is derived is called a parent/base class.
25
D20MCA11140
26
D20MCA11140
Polymorphism:
You all must have used GPS for navigating the route, Isn’t it amazing how many different routes you
come across for the same destination depending on the traffic, from a programming point of view this is
called ‘polymorphism’. It is one such OOP methodology where one task can be performed in several
different ways. To put it in simple words, it is a property of an object which allows it to take multiple
forms.
Compile-time Polymorphism
Run-time Polymorphism
Compile-time Polymorphism:
A compile-time polymorphism also called as static polymorphism which gets resolved during the
compilation time of the program. One common example is “method overloading”. Let me show you a
quick example of the same.
Example:
Output:
27
D20MCA11140
Run-time Polymorphism:
A run-time Polymorphism is also, called as dynamic polymorphism where it gets resolved into the run
time. One common example of Run-time polymorphism is “method overriding”. Let me show you
through an example for a better understanding.
Example:
Output:
Encapsulation:
In a raw form, encapsulation basically means binding up of data in a single class. Python does not have
any private keyword, unlike Java. A class shouldn’t be directly accessed but be prefixed in an underscore.
Example:
Output:
1234
Traceback (most recent call last):
1234
File “C:/Users/Harshit_Kant/PycharmProjects/test1/venv/encapsu.py”,
line 10, in
print(object1.__salary)
AttributeError: ’employee’ object has no attribute ‘__salary’
So, we have made use of the setter method which provides indirect access to them
Example:
Output:
earning is:1000000
earning is:1000000
earning is:10000
28
D20MCA11140
Abstraction:
Suppose you booked a movie ticket from bookmyshow using net banking or any other process. You don’t
know the procedure of how the pin is generated or how the verification is done. This is called
‘abstraction’ from the programming aspect, it basically means you only show the implementation details
of a particular process and hide the details from the user. It is used to simplify complex problems by
modeling classes appropriate to the problem.
An abstract class cannot be instantiated which simply means you cannot create objects for this type
of class. It can only be used for inheriting the functionalities.
Example:
Output:
emp_id is 12345
29