Python Mid Exam Que Ans-1
Python Mid Exam Que Ans-1
1)What is _ _init_ _?
The Default _init_ Constructor in C++ and Java. Constructors are used to
initialize the object’s state. The task of constructors is to initialize(assign
values) to the data members of the class when an object of the class is
created. Like methods, a constructor also contains a collection of
statements(i.e. instructions) that are executed at the time of Object
creation. It is run as soon as an object of a class is instantiated. The
method is useful to do any initialization you want to do with your object.
Example:
# A Sample class with init method
class Person:
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Nikhil')
p.say_hi()
Output:
The reason you need to use self. is because Python does not use the @
syntax to refer to instance attributes. Python decided to do methods in a
way that makes the instance to which the method belongs be passed
automatically, but not received automatically: the first parameter of
methods is the instance the method is called on.
In more clear way you can say that SELF has following Characteristic-
Self is always pointing to Current Object.
Self is a convention and not a Python keyword .
Self is the first argument to be passed in Constructor and Instance
Method.
Example:
#it is clearly seen that self and obj is referring to the same object
class check:
def _init_(self):
print("Address of self = ",id(self))
obj = check()
print("Address of class object = ",id(obj))
Output:
Address of self = 140124194801032
Address of class object = 140124194801032
Syntax:- frozenset([iterable])
frozenset() Parameters
The frozenset() function takes a single parameter:
Example
# tuple of vowels
fSet = frozenset(vowels)
fSet.add('v')
Output:
The frozen set is: frozenset({'a', 'o', 'u', 'i', 'e'})
fSet.add('v')
def add(a,b,c):
return (a+b+c)
The above function can be called in two ways:
First, during the function call, all arguments are given as positional
arguments. Values passed through arguments are passed to parameters
by their position. 10 is assigned to a, 20 is assigned to b and 30 is
assigned to c.
print (add(10,20,30))#Output:60
The second way is by giving a mix of positional and keyword arguments.
Keyword arguments should always follow positional arguments.
print (add(10,c=30,b=20))#Output:60
Output:
SKEEGROFSKEEG
Long Questions
Example 1: Filter out all odd numbers using filter() and lambda function
Python
Output:
[5, 7, 97, 77, 23, 73, 61]
Example 2: Filter all people having age more than 18, using lambda and
filter() function
Python3
print(adults)
Output:
[90, 59, 21, 60]
Python
Output:
[10, 14, 44, 194, 108, 124, 154, 46, 146, 122]
Python3
# Python program to demonstrate
# use of lambda() function
# with map() function
animals = ['dog', 'cat', 'parrot', 'rabbit']
print(uppered_animals)
Output:
['DOG', 'CAT', 'PARROT', 'RABBIT']
Python
Output:
193
2) Discuss Decorators and Generators in python with example.
Decorators are one of the most helpful and powerful tools of Python.
These are used to modify the behavior of the function. Decorators provide
the flexibility to wrap another function to expand the working of wrapped
function, without permanently modifying it.
Output: -2.0
Python3
Output
1
2
3
The show() function is used to display the plot on the screen. It takes no
input parameters and simply displays the plot that has been created
using the plot() function.
The title() function is used to set the title of the plot. It takes a string as
input, which is used as the title of the plot. For example, the following
code snippet creates a line plot of the values in the array y and sets the
title of the plot to "My Plot":
pythonCopy code
import matplotlib.pyplot as plt
y = [1, 2, 3, 4, 5]
plt.plot(y)
plt.title("My Plot")
plt.show()
4) Explain Exceptional Handling with example.
5) Sequences in Python
Explain sequences with python code.
str datatype
• We can also write string inside “““ (triple double quotes) or ‘‘‘
(single double quotes)
str = “Welcome to TMES”
str = ‘Welcome to TMES’
str1 = “““ This is book on python which discusses all the topics of Core
python
in a very lucid manner.”””
str1 = ‘‘‘This is book on python which discusses all the topics of Core
python in a very lucid manner.’’’
str datatype
print(s*2)
Welcome to Core PythonWelcome to Core Python
bytes Datatype
bytearray Datatype
x[0]=88
x[1]=99
print(x[0])
list Datatype
• Lists in Python are similar to arrays in C or Java.
• The main difference between a list an array is that a list can
store different types of elements, but array can store only one
type of elements.
• List can grow dynamically in memory.
• But the size of arrays is fixed and they cannot grow at
runtime.
list Datatype
2
nd positions. i.e 10,20,15.5
>>>list = [10, -20, 15.5, ‘vijay’, “Marry”]
>>>print(list)
10, -20, 15.5, ‘vijay’, “Marry”
>>> print(list[0])
10
>>>print(list[1:3])
[-20,15.5]
>>>print(list[-2])
vijay
>>>print(list*2)
[ 10, -20, 15.5, ‘vijay’, “Marry” 10, -20, 15.5, ‘vijay’, “Marry”]
6/14/2021 Prepared By: Yogeshwari M. Lohar 25
tuple datatype
tuple datatype
range Datatype
range Datatype
>>> r = range(10)
>>> for i in r : print(i)
0
1
2
3
4
5
6
7
8
9
range Datatype
>>> r = range(30,40,2)
>>> for i in r:print(i)
30
32
34
36
38
ceil() :- This function returns the smallest integral value greater than
the number. If number is already integer, same number is returned. 2.
floor() :- This function returns the greatest integral value smaller than
the number. If number is already integer, same number is returned.
Python
Python
a = -10
b= 5
Output:
The absolute value of -10 is : 10.0
The factorial of 5 is : 120
Time Complexity: O(b)
Auxiliary Space: O(1)
5. copysign(a, b) :- This function returns the number with the value of
‘a’ but with the sign of ‘b’. The returned value is float type. 6. gcd() :-
This function is used to compute the greatest common divisor of 2
numbers mentioned in its arguments. This function works in python 3.5
and above.
Python
a = -10
b = 5.5
c = 15
d=5
Output:
The copysigned value of -10 and 5.5 is : -5.5
The gcd of 5 and 15 is : 5
List
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("Original list ", List)
List[3] = 77
print("Example to show mutability ", List)
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Output:
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
import pandas as pd
filepath = "emp.csv"
df = pd.read_csv(filepath)
print("Read the CSV file:-")
print("Printing the Data Frame:-\n ",df)
print("\n\nNum of rows and coloumns:-\n ",df.shape)
print("\n\nData of the 3rd row\n",df.iloc[2])
print("\n\nData of the 4th row\n",df.iloc[3])
row=df[df["salary"]<=10000]
print("\n\nData of the employee whose salary is not more than
10000:- ")
print(row[["empid","empname"]].to_string(index=False))
print("\n\nSorted data as per Date of joining:- ")
print(df.sort_values(by=['DOJ']))
print("The data having minimum salary:- ")
print(df[df["salary"]==df["salary"].min()])
df1=df.set_index('empid')
print("\n\nEmp id as an index :- ")
print(df1)
output:-
Read the CSV file:-
Printing the Data Frame:-
empid empname salary gender dob DOJ
0 101 tanjiro 50000 male 01-01-2002 25-05-2022
1 102 zenitsu 20000 male 02-02-2002 14-09-2021
2 103 inosuke 15000 male 03-03-2002 11-05-2021
3 104 giyu 9000 male 04-04-2002 16-07-2020
4 105 naruto 5000 male 11-05-2002 15-08-2015
5 106 yuji 9500 male 06-06-2002 20-10-2019
6 107 steve 15000 male 07-07-2002 25-10-2018
7 108 light 20000 male 08-08-2002 02-08-2019
8 109 nezuko 40000 female 09-09-2002 09-09-2022
9 110 mitsuri 100000 female 10-10-2002 24-10-2019
Emp id as an index :-
empname salary gender dob DOJ
empid
101 tanjiro 50000 male 01-01-2002 25-05-2022
102 zenitsu 20000 male 02-02-2002 14-09-2021
103 inosuke 15000 male 03-03-2002 11-05-2021
104 giyu 9000 male 04-04-2002 16-07-2020
105 naruto 5000 male 11-05-2002 15-08-2015
106 yuji 9500 male 06-06-2002 20-10-2019
107 steve 15000 male 07-07-2002 25-10-2018
108 light 20000 male 08-08-2002 02-08-2019
109 nezuko 40000 female 09-09-2002 09-09-2022
110 mitsuri 100000 female 10-10-2002 24-10-2019