Question Bank Solution-1
Question Bank Solution-1
Unit -1
Q1 Explain features of python.
Ans
Features in Python
There are many features in Python, some of which are discussed below –
1. Easy to code:
Python is a high-level programming language. Python is very easy to learn the
language as compared to other languages like C, C#, Javascript, Java, etc. It is very
easy to code in python language and anybody can learn python basics in a few
hours or days. It is also a developer-friendly language.
3. Object-Oriented Language:
One of the key features of python is Object-Oriented programming. Python
supports object-oriented language and concepts of classes, objects encapsulation,
etc.
1
4. GUI Programming Support:
Graphical User interfaces can be made using a module such as PyQt5, PyQt4,
wxPython, or Tk in python.
PyQt5 is the most popular option for creating graphical apps with Python.
5. High-Level Language:
Python is a high-level language. When we write programs in python, we do not
need to remember the system architecture, nor do we need to manage the memory.
6. Extensible feature:
Python is a Extensible language. We can write us some Python code into C or C++
language and also we can compile that code in C/C++ language.
9. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at
a time. like other languages C, C++, Java, etc. there is no need to compile python
code this makes it easier to debug our code. The source code of python is
converted into an immediate form called bytecode.
3
Q3 Python is interpreted language. Explain it
Ans
Python is an interpreted language, which means the source code of a Python
program is converted into bytecode that is then executed by the Python virtual
machine. Python is different from major compiled languages, such as C and C + +,
as Python code is not required to be built and linked like code for these languages.
This distinction makes for two important points:
•
Python code is fast to develop: As the code is not needed to be compiled
and built, Python code can be readily changed and executed. This makes for
a fast development cycle.
•
Python code is not as fast in execution: Since the code is not directly
compiled and executed and an additional layer of the Python virtual machine
is responsible for execution, Python code runs a little slow as compared to
conventional languages like C, C + +, etc.
Strengths
4
Python has steadily risen in the charts of widely used programming languages and,
according to several surveys and research, it is the fifth most important language in
the world. Recently several surveys depicted Python to be the most popular
language for machine learning and data science! We will compile a brief list of
advantages that Python offers that will likely explain its popularity.
Easy to learn: Python is a relatively easy-to-learn language. Its syntax is simple
for a beginner to learn and understand. When compared with languages like C or
Java, there is minimal boilerplate code required in executing a Python program.
Supports multiple programming paradigms: Python is a multiparadigm,
multipurpose programming language. It supports object-oriented programming,
structured programming, functional programming, and even aspect-oriented
programming. This versatility allows it to be used by a multitude of programmers.
Extensible: Extensibility of Python is one of its most important characteristics.
Python has a huge number of modules easily available that can be readily installed
and used. These modules cover every aspect of programming from data access to
implementation of popular algorithms. This easy-to-extend feature ensures that a
Python developer is more productive, as a large array of problems can be solved by
available libraries.
Active open-source community: Python is open source and supported by a large
developer community. This makes it robust and adaptive. The bugs encountered
are easily fixed by the Python community. Being open source, developers can
tinker with the Python source code if necessary.
1.4.1 Pitfalls
Although Python is a very popular programming language, it comes with its own
share of pitfalls. One of the most important limitations it suffers is in terms of
execution speed. Being an interpreted language, it is slow when compared to
compiled languages. This limitation can be a bit restrictive in scenarios where
extremely high performance code is required. This is a major area of improvement
for future implementations of Python, and every subsequent Python version
addresses it. Although we have to admit it can never be as fast as a compiled
language, we are convinced that it makes up for this deficiency by being super-
efficient and effective in other departments.
You can install Python and the necessary libraries individually using a
prepackaged Python distribution that comes with necessary libraries (i.e.,
Anaconda). Anaconda is a packaged compilation of Python along with a whole
suite of libraries, including core libraries that are widely used in data science. The
main advantage of this distribution is that we do not need an elaborate setup and it
works well on all flavors of operating systems and platforms, especially Windows.
The Anaconda distribution comes with a wonderful IDE, Spyder (Scientific Python
Development Environment), as well as other useful utilities like Jupyter
5
Notebooks, the IPython console, and the excellent package management tool
Conda (Sarkar et al., 2018).
1.4.2 Drawbacks
The only real drawback of Python is that it is not as fast as Java or C. You can,
however, call C-compiled programs from Python. This gives you the best of both
worlds and allows you to incrementally develop a program. If the program is built
in a modular fashion, you can first get it up and running in Python and then, to
improve speed, start building portions of the code in C. The Boost C + + library
makes this easy to do. Other tools, such as Cython and PyPy, allow you write
typed versions of Python with performance gains over regular Python. If an idea
for a program or application is flawed, then it will be flawed at low speed as well
as high speed. If an idea is a bad idea, writing code can make it fast or scale
(Harrington, 2012).
1.4.3 The NumPy library
NumPy is the backbone of machine learning in Python. It is one of the most
important libraries in Python for numerical computations. It adds support to core
Python for multidimensional arrays (and matrices) and fast vectorized operations
on these arrays. It is employed in almost all machine learning and scientific
computing libraries. The extent of popularity of NumPy is verified by the fact that
major OS distributions, like Linux and MacOS, bundle NumPy as a default
package instead of considering it as an add-on package (Sarkar et al., 2018).
1.4.4 Pandas
Pandas is a vital Python library for data manipulation, wrangling, and analysis. It
functions as an intuitive and easy-to-use set of tools for execution operations on
any kind of data. Pandas allows you to work with both cross-sectional data and
time series–based data. DataFrame is the most important and useful data structure
that is employed for almost all types of data representation and manipulation in
Pandas. Unlike NumPy arrays, a DataFrame can contain heterogeneous data.
Naturally, tabular data are characterized by means of DataFrames, which are
analogous to Excel sheets or SQL tables. This is really beneficial in representing
raw datasets as well as processed feature sets in machine learning and data science.
All the operations can be performed along the axes, rows, and columns in a
DataFrame (Sarkar et al., 2018).
6
Unit 2
Q4 Which are the built-in data types in python?
Ans
Variables can store data of different types, and different types can do different
things.
Python has the following data types built-in by default, in these categories:
Example
Print the data type of the variable x:
x = 5
7
print(type(x))
8
Setting the Specific Data Type
Syntax:
list.append (element)
# Adds List Element as value of List.
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
9
print(List)
Output:
['Mathematics', 'chemistry', 1997, 2000, 20544]
Output:
List1 = [1, 2, 3]
List2 = [2, 3, 4, 5]
[1, 2, 3, 2, 3, 4, 5]
[2, 3, 4, 5, 1, 2, 3, 2, 3, 4, 5]
sum(), count(), index(), min() and max() functions of List
10
sum(List)
List = [1, 2, 3, 4, 5]
print(sum(List))
Output:
15
What happens if numeric value is not used a parameter?
Sum is calculated only for Numeric values, elsewise throws TypeError.
See example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
Output:
4
length:Calculates total length of List.
Syntax:
len(list_name)
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(len(List))
Output:
10
index(): Returns the index of first occurrence. Start and End index are not
necessary parameters.
11
Syntax:
List.index(element[,start[,end]])
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2))
Output:
1
Another example:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.index(2,2))
Output:
List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
Output:
1.054
max(): Calculates maximum of all the elements of List.
Syntax:
max(List)
5.33
sort() and reverse() functions
reverse(): Sort the given data structure (both tuple and list) in ascending order. Key
and reverse_flag are not necessary parameter and reverse_flag is set to False, if
nothing is passed through sorted().
Syntax:
sorted([list[,key[,Reverse_Flag]]])
list.sort([key,[Reverse_flag]])
To Delete one or more elements, i.e. remove an element, many built in functions
can be used, such as pop() & remove() and keywords such as del.
pop(): Index is not a necessary parameter, if not mentioned takes the last index.
Syntax:
list.pop([index])
Note: Index must be in range of the List, elsewise IndexErrors occurs.
2.5
2.3
del() : Element to be deleted is mentioned using list name and index.
Syntax:
del list.[index]
# Driver Code
lst = [10, 11, 12, 13, 14, 15]
print(Reverse(lst))
Output:
15
lst.reverse()
return lst
16
Q8 Explain dictionary with example.
Ans
Dictionary
The dictionary is an unordered collection that contains key:value pairs
separated by commas inside curly brackets. Dictionaries are optimized
to retrieve values when the key is known.
Example: Dictionary
capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New
Delhi"}
items={("Parker","Reynolds","Camlin"):"pen",
("LG","Whirlpool","Samsung"): "Refrigerator"} # tuple key, string value
17
romanNums = {'I':1, 'II':2, 'III':3, 'IV':4, 'V':5} # string key, int
value
The same key cannot appear more than once in a collection. If the key
appears more than once, only the last will be retained. The value can
be of any data type. One value can be assigned to more than one key.
18
A bitwise operator is an operator used to perform bitwise operations on bit patterns
or binary numerals that involve the manipulation of individual bits.
• Communication stacks where the individual bits in the header attached to the
data signify important information
• Embedded software for controlling different functions in the chip and
indicating the status of hardware by manipulating the individual bits of
hardware registers of embedded microcontrollers
• Low-level programming for applications such as device drivers,
cryptographic software, video decoding software, memory allocators,
compression software and graphics
• Maintaining large sets of integers efficiently in search and optimization
problems
• Bitwise operations performed on bit flags, which can enable an instance of
enumeration type to store any combination of values defined in an
enumerator list
19
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that valuate to True.
Example
Only accept items that are not "apple":
newlist = [x for x in fruits if x != "apple"]
The condition if x != "apple" will return True for all elements other than "apple",
making the new list contain all fruits except "apple".
The condition is optional and can be omitted:
Example
With no if statement:
newlist = [x for x in fruits]
As per the above syntax, the list comprehension syntax contains three parts: an
expression, one or more for loop, and optionally, one or more if conditions. The
list comprehension must be in the square brackets []. The result of the first
expression will be stored in the new list. The for loop is used to iterate over the
iterable object that optionally includes the if condition.
Suppose we want to find even numbers from 0 to 20 then we can do it using a for
loop, as shown below:
even_nums = []
for x in range(21):
if x%2 == 0:
even_nums.append(x)
print(even_nums)
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
The same result can be easily achieved using a list comprehension technique
shown below.
Output
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
The same result can be easily achieved using a list comprehension technique
shown below.
21
What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
We generally use this loop when we don't know the number of times to iterate
beforehand.
Syntax of while Loop in Python
while test_expression:
Body of while
In the while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test
expression is checked again. This process continues until
the test_expression evaluates to False.
In Python, the body of the while loop is determined through indentation.
The body starts with indentation and the first unindented line marks the end.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
Flowchart of while Loop
22
# n = int(input("Enter n: "))
n = 10
while i <= n:
sum = sum + i
i = i+1 # update counter
elif choice == 5:
exit()
else:
print("Wrong input..!!")
Input:
Output:
Result = 45
24
Q3 Explain Enumerate function with example.
Ans
Python enumerate() Function
Example
Convert a tuple into an enumerate object:
The enumerate() function adds a counter as the key of the enumerate object.
Syntax
enumerate(iterable, start)
i=1
25
while i <= x:
if i % 2 == 0:
i=i+1
Output:
num = 29
26
# check if flag is True
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
Output
29 is a prime number
Syntax
range(start, stop, step)
Parameter Values
27
In operator
Python “in” operator
Basically, the in operator in Python checks whether a specified value is a
constituent element of a sequence like string, array, list, or tuple etc. When
used in a condition, the statement returns a Boolean result evaluating into either
True or False
list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)
Here:
Firstly, we have initialised a list list1, a string string1 and a tuple tuple1 with some
values. Then we use the in operator to check whether some values are part of the
above sequences or not.
As we can see from the above output, 5 in list1 evaluates into a True. Which
signifies that the value 5 is found inside the list.
Similarly, using the in operator we also confirm the presence of the
string “is” in string1. But for the last case, the condition results in
a False since 88 is not present inside the sequence tuple1.
2. Not in
28
Python “not in” operator
The not in operator in Python works exactly the opposite way as the in operator
works. It also checks the presence of a specified value inside a given sequence but
it’s return values are totally opposite to that of the in operator.
When used in a condition with the specified value present inside the sequence, the
statement returns False. Whereas when it is not, we get a True.
Let us take the previous example, just replacing in operator with the not in one.
#not in operator working
list1= [1,2,3,4,5]
string1= "My name is AskPython"
tuple1=(11,22,33,44)
not in Output
As expected, the resultant output is the exact opposite of what we got earlier using
the in operator.
Unit 4
Q1 Explain the use and structure of function in python.
Ans
29
of its elements, by coding yourself using a for loop; if don't want to use the sum()
method of python.
What are arbitrary arguments in Python?
def mySum(*args):
if len(args) == 1:
return args[0]
else:
return args[-1] + mySum(args[:-1])
but when I tested mySum(3, 4), I got this error:
30
Python supports various built-in The major difference between
type conversion functions such as Type Conversion and Type
int(), long(), float(), str() etc,. Coercion is that, type conversion
is done manually using built-in
This type of conversion is also functions where as type coercion
called as Explicit Type is done automatically.
Conversion or Type Casting.
# Driver code
n=5
print(recurSum(n))
Output
15
Q5 Explain the inbuilt math function of python and explain any 2 with examples.
Ans
31
32
33
Pi
Code:
import math
math.pi
#3.141592653589793
34
Output:
radius = 5
math.e
#2.718281828459045
Output:
Tau
35
Tau (𝜏) is a mathematical constant, defined as the ratio of the circumference of the
circle to the radius of the circle.
math.tau = 2*pi
Check out the code below:
Code:
import math
math.tau
#6.283185307179586
Output:
Infinity
Infinity is a boundless entity that cannot be defined in numbers. In Python, positive
and negative infinities are defined as follows:
Code:
import math
math.inf
-math.inf
Output:
Infinity is used to compare given numbers to the absolute maximum and absolute
minimum values as demonstrated in the code below:
Code:
import math
x = 13.789
36
x < math.inf
x < -math.inf
Output:
math.nan
Output:
floor() method
The floor() method of the math module rounds down a number to the nearest
integer. Syntax for floor() is given below:
Syntax:
math.floor(x)
x is the input number. The floor() method takes positive or negative numbers as
input.
The floor() method returns the nearest integer less than or equal to x. If the number
is a floating-point number, 10.89, floor() will return 10.
If the number is an integer, floor() will return the same integer. Consider the
following example:
Code:
import math
37
x = 3.5367
math.floor(x)
x=6
math.floor(x)
Output:
ceil() method
The ceil() method of the math module rounds up a number to the nearest integer.
Syntax for ceil() is given below:
Syntax:
math.ceil(x)
x is the input number. The ceil() method takes positive or negative numbers as
input.
The ceil() method returns an integer value greater than or equal to x. If the number
is a floating-point number, 10.89, ceil() will return 11.
If the number is an integer, ceil() will return the same integer. The following
example explains the ceil() method:
Code:
import math
x = 10.89
math.ceil(x)
38
x = 10
math.ceil(x)
Output:
math.sqrt()
The sqrt() method returns the square root of an input value. The syntax of sqrt() is
as follows:
Syntax:
math.sqrt(x)
x is the input number. It must be greater than or equal to 0. If x is less than 0
(negative number), sqrt() will return ValueError.
The sqrt() method returns a floating-point number. Consider the example below:
Code:
import math
math.sqrt(9)
math.sqrt(4)
math.sqrt(24)
math.sqrt(-49)
Output:
39
If the number is less than 0, we will have the following error:
math.fabs(x)
fabs represents the absolute function. The absolute function returns a non-negative
value of the given number.
It means that the absolute value of a positive number will be the same number and
if the given number is negative, the fabs function will convert it into a positive
number.
For example, the fabs value of -8 will be 8 and the fabs value of 8 will be 8. Syntax
of fabs is given below:
Syntax:
math.fabs(x)
x can be an integer or a floating-point.
The method will return a non-negative floating-point number. Consider the
following example:
Code:
import math
math.fabs(-3)
math.fabs(-89.9)
math.fabs(89)
40
Output:
The difference between math.fabs() method and the python’s abs() method is that
the math.fabs() method always returns a floating-point number.
math.pow(x)
The pow() method of the math module returns the value of input number x raised
to the power y that is xy.
The syntax for math.pow() is as follows:
Syntax:
math.pow(x, y)
x is the input number and y is the power of x. If x is 3 and y equals 4, it will mean:
34 = 3 * 3 * 3 * 3.
The function returns a floating-point value.
In mathematics, anything raised to power 0 equals 1, and 1 raised to power
anything also equals 1. Therefore, the pow() method will return 1.0 if y is 0 and x
is any number.
Similarly, pow() will return 1.0 if x is 1 and y is any number.
math.pow(x, 0.0) = 1.0
math.pow(1.0, y) = 1.0
Output:
Code:
import math
41
print("3 raised to power 4 = ", math.pow(3, 4))
Output:
math.isclose()
The isclose() method of the math module uses relative and absolute tolerance to
check the closeness of two values. Tolerance is defined as the threshold to check
the closeness of the numbers.
If the two numbers are close to each other, the isclose() method will return true and
return false if they are not close to each other.
The syntax of isclose() is given below:
Syntax:
math.isclose(a, b, rel_tol, abs_tol)
42
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.
print(double(5))
double = lambda x: x * 2
def double(x):
return x * 2
Use of Lambda Function in python
43
In Python, we generally use it as an argument to a higher-order function (a
function that takes in other functions as arguments). Lambda functions are
used along with built-in functions like filter() , map() etc.
Here is an example use of filter() function to filter out only even numbers
from a list.
print(new_list)
Unit 5
Q1 Explain the concept of string slicing along with examples.
Ans
In the previous lesson, you saw how you could access individual characters in a
string using indexing. In this lesson, you’ll learn how to expand that syntax to
extract substrings from a string. This technique is known as string slicing. You’ll
practice with the standard syntax, and learn how omitting the first or last index
extends the slice. You’ll also learn how to specify a stride in a string slice by using a
third index.
44
# String slicing
String ='ASTRING'
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output
String slicing
AST
SR
GITA
String Concatenation
String concatenation means add strings together.
str1="Hello"
str2="World"
print ("String 1:",str1)
45
print ("String 2:",str2)
str=str1+str2
Output
String 1: Hello
String 2: World
str=str * x
Output
String 1: Hello
def isPalindrome(s):
return s == s[::-1]
46
# Driver code
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
Output
Yes
Example
Output
name_1 = Varun and name_2 = Tarun
47
Python String Methods
48
49
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'
50
# original string never changes
print("\nOriginal String")
print(text)
Output
Converted String:
GEEKS FOR GEEKS
Converted String:
geeks for geeks
Converted String:
Geeks For Geeks
Original String
geeKs For geEkS
51