Python Solved QP
Python Solved QP
Python Solved QP
c) Describe Dictionary
Ans: In Python, a Dictionary can be created by placing a sequence of elements within curly
{} braces, separated by ‘comma’. Dictionary holds pairs of values, one being the Key and the
other corresponding pair element being its Key:value. Values in a dictionary can be of any
data type and can be duplicated, whereas keys can’t be repeated and must be immutable.
Dictionary keys are case sensitive, the same name but different cases of Key will be treated
distinctly.
# Creating a Dictionary
Dict = {1: 'PWP', 2: 'MAD', 3: 'NIS'}
print("This is subject")
print(Dict)
d) State use of namespace in Python
Ans: A namespace is a collection of currently defined symbolic names along with
information about the object that each name references. You can think of a namespace as a
dictionary in which the keys are the object names and the values are the objects themselves.
Each key-value pair maps a name to its corresponding object.
Ans: 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
2. Free and Open Source: Python language is freely available at the official website.Since it
is open-source, this means that source code is also available to the public. So you can
download it as, use it as well as share it.
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.
4. 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.
a) Explain two Membership and two logical operators in python with appropriate
examples
Membership operators
Ans: Operator : in
Description: Evaluates to true if it finds a variable in the specified sequence and false
otherwise.
Example: x in y, here in results in a 1 if x is a member of sequence y.
Operator : not in
Description: Evaluates to true if it does not finds a variable in the specified sequence
and false otherwise.
Example: x not in y, here not in results in a 1 if x is not a member of sequence y.
logical operators
Operator: and Logical AND
Description: If both the operands are true then condition becomes true. (a and b) is
true.
Example: (a and b) is true.
Operator: or Logical OR
Description: If any of the two operands are non-zero then condition becomes true.
Example: (a or b) is true.
Operator: not Logical NOT
Description : Used to reverse the logical state of its operand.
Example: Not(a and b) is false.
print(List)
3) count() - Returns the number of elements with the specified value
EX- List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]
print(List.count(1))
4) insert() - Inserts an elements at specified position
EX - List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2,10087)
print(List)
The scope remains throughout the program. The scope is limited and remains within the
function only in which they are declared.
Global variables are stored in the data Local variables are stored in a stack in
segment of memory. memory.
We cannot declare many variables with the We can declare various variables with the
same name. same name but in other functions.
Before SWAPPING
First Tuple (1, 2, 3)
Second Tuple (5, 6, 7, 8)
AFTER SWAPPING
First Tuple (5, 6, 7, 8)
Second Tuple (1, 2, 3)
statements(s)
statements(s)
Example:
# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
# Reading a file
f = open(__file__, 'r')
#read()
text = f.read(10)
print(text)
f.close()
write(string): It writes the contents of string to the file. It has no return value. Due to
buffering, the string may not actually show up in the file until the flush() or close()
method is called.
# Writing a file
f = open(__file__, 'w')
line = 'Welcome Geeks\n'
#write()
f.write(line)
f.close()
# Constructor
def __init__(self):
self.value = "Inside Child"
# Child's show method
def show(self):
print(self.value)
# Driver's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()
Output:
Inside Parent
Inside Child
tuple.index(value)
Parameter Values:
Value - Required The item to search for
Example:
# Search for the first occurrence of the value 8, and return its position:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)
b) Write a python program to read contents of first.txt file and write same content in
second.txt file
Ans: first.txt file:
This is python language.
with open('first.txt', 'r') as firstfile, \
open('second.txt', 'w') as secondfile:
print("content saved successfully")
for content in firstfile:
secondfile.write(content)
Output:
content saved successfully
This is python language.
c) Show how try…except blocks is used for exception handling in Python with example.
Ans: try-expect statement - If the Python program contains suspicious code that may throw
the exception, we must place that code in the try block. The try block must be followed with
the except statement, which contains a block of code that will be executed if there is some
exception in the try block.
Syntax :
try:
#block of code
except Exception1:
#block of code
except Exception2:
10
#block of code
#other code
Example :
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
d) Write the output for the following if the variable fruit=’banana’:
>>>fruit[:3]
>>>fruit[3:]
>>>fruit[3:3]
>>>fruit[:]
Ans: fruit = ‘banana’
print("Original item is - ", fruit)
f1 = fruit[:3]
print("Element in range :3 is - ", f1)
f2 = fruit[3:]
print("Element in range 3: is - ", f2)
f3 = fruit[3:3]
print("Element in range 3:3 is -", f3)
f4 = fruit[:]
print("Element in range : is -", f4)
Output:
Original item is - banana
Element in range :3 is - ban
Element in range 3: is - ana
Element in range 3:3 is –
Element in range : is – banana
11
12
13
Output :
1. [1, 2, 3, 4, 5, 6]
2. [1, 2, 3, 1, 2, 3, 1, 2, 3]
3. ['a', 'x', 'y', 'd', 'e', 'f']
14
Set Intersection
Intersection of A and B is a set of elements that are common in both sets. The Intersection is
performed using (&) operator. Same can be accomplished using the function intersection().
A={1, 2, 3, 4, 5)
B=(4, 5, 6, 7, 8)
C= A&B #OR C = A.intersection(B)
print("Set A contains:"A)
print("Set B contains :"B)
print("The INTERSECTION operation results:",C)
This will result as:
Set A contains: {1, 2, 3, 4, 5)
Set B contains: (4, 5, 6, 7, 8)
The INTERSECTION operation results: {4, 5}
Set Difference
Difference of A and B (A-B) Is a set of elements that are only In A but not in B. Similarly, B-
A is a set of element in B but not in A. The Difference is performed using (-) operator. Same
can be accomplished using the function difference()
Example
A=(1,2,3,4,5)
B=(4,5,6,7,8}
C = A-B #OR A .difference(B)
D = B-A #OR B.difference(A)
print("A-B results as",C)
print("B-A results as :",D)
The output will be:
A-B results as: (1,2,3)
B-A results as: (8,6,7)
Set Symmetric_Difference
Symmetric Difference of A and B is a set of elements in both A and B except those
that are common in both. The Symmetric difference is performed using (a) operator.
Same can be accomplished using the function symmetric difference().
Example
15
A={1,2,3,4,5)
B=(4, 5, 6, 7, 8)
C = A^B #OR A.symmetric difference (B)
print("Symmetric difference results as "C)
This will result as:
Symmetric difference results as : {1, 2, 3, 6, 7, 8)
c) Design a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information
Ans: class Employee:
__name=""
16
__department=""
__salary=0
# function to set data
def setData(self,name,department,salary):
self.__name = name
self.__department = department
self.__salary = salary
# function to get/print data
def showData(self):
print("Name\t:", self.__name)
print("department\t:", self.__department)
print("Salary\t:", self.__salary)
# main function definition
def main():
emp=Employee()
emp.setData('Rohit','software Eng',55000)
emp.showData()
if __name__=="__main__":
main()
Output :
Name : Rohit
department : software Eng
Salary : 55000
17