0% found this document useful (0 votes)
15 views29 pages

Makaut - Question Bank

Uploaded by

mikey2op2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views29 pages

Makaut - Question Bank

Uploaded by

mikey2op2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Module 1:

Is Python an interpreter language True or False? 1


Ans True
When Python is dealing with identifiers, is it case sensitive? 1
Ans Yes
What is the extension of the Python file? 1
.py

What are the advantages of Python over other languages? 5


Presence of Third party modules
Extensive support libraries
Open source and community development
Learning ease and support available
User friendly data structure
Productivity and speed

What are frozen binaries in Python used for? 4


Frozen binaries are a form of distribution for Python applications. They meticulously bundle the Python interpreter,
your application's codebase, and all essential libraries and resources into a single, self-contained executable file.

Think of a frozen binary as a self-contained package for your Python app. It bundles everything it needs to run—the
Python engine, your app's code, and any extra tools—into a single, neat file. This means users can simply download
and run your app, with no extra setup needed!

.
In Python, how is memory managed? 6
Steps in managing memory in Python are –
 The Python memory is primarily 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 and interpreter takes care of this
Python private heap.
 The allocation of Python heap space for python objects is done by Python memory manager.
 The core API gives access to some tools for the programmer to code.
 Python has an inbuilt garbage collector, that recycles all the unused memory and frees the
memory and makes it available to the heap space.
What is Python virtual machine? 5
The Python Virtual Machine, often referred to as the Python interpreter, is responsible for executing
Python code. It serves as an abstraction layer between the Python bytecode and the underlying hardware,
providing a consistent environment for running Python programs across different platforms. The Python
VM is implemented in CPython, the reference implementation of Python.

Module 2:
What will be the output of the following expression ?
Print(True+10)
Ans 11

What will be the output of the following expression ?


Print(10,20,sep=”#”)
10#20
What will be the output of the following expression ?
Print(4*”8”)
Ans 8888
What is variable? How to assign values to multiple variables in one line and How assign the same value to
multiple variables in one line in Python? 5

A Python variable is a reserved memory location to store values.Every value in Python has a datatype. Different data
types in Python are Numbers, List, Tuple, Strings, Dictionary, etc.

x, y, z = 10,20,30

x = y = z = 10

What is the output of the following code ?


i)print(bool(0), bool(3.14159), bool(3), bool(1.0+1j))
Ans False True True True
ii) a,b= 15,6
print(a and b)
print(a or b)
Ans 6 15
iii) a=input("Enter a number")
print(a*5)
Ans 5 times content of a will be printed
iv) print(int())
Ans 0
v) print(not(True)+5)
Ans False
What is the purpose of comments in Python ? 5
Comments in Python is the inclusion of short descriptions along with the code to increase its readability. A
developer uses them to write his or her thought process while writing the code. It explains the basic logic behind
why a particular line of code was written.
Write a Program that prompts user to enter his first name and last name and then displays a message
“Greetings!!! First name Last name 5
Module 3:
What will be the output after the following statements?
a,b,c = True,False,False
if not a or b:
print(1)
elif not a or not b and c:
print (2)
elif not a or b or not b and a:
print (3)
else:
print (4)
Ans. 3
What will be the output after the following statements?
a,b = 0 ,3
while a + b < 8:
a += 1
print(a, end='')

Ans. 12345

What is the output of the following ?


for i in range(10):
if i == 5:
break
else:
print(I,end=” “)
else:
print("Here")
Ans 0 1 2 3 4
Which function generates a sequence of numbers from 1 to n.
range(1,n+1)

Write a Program to print its digits in reverse order. The input is to be taken by user.
num = 1234
rev = 0
while num != 0:
digit = num % 10
rev = rev * 10 + digit
num //= 10
print("Reversed Number: " + str(rev))

Write an interactive ‘Python’ program to evaluate the series: 1 – 1/2 + 1/3 – 1/4 …±1/n, where n is
entered from keyboard.
n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
sum1=sum1+(1/i)
print("The sum of series is", sum1)
What are the disadvantages of nested if-else statement?
if-else statements can become nested and complex, making the code harder to read and maintain.
Additionally, if-else statements can lead to code duplication if the same logic needs to be repeated in
multiple places.

Write a program which asks the user a number between 1 and 7 and prints the corresponding day of the
week. (1: Sunday, 2: Monday, …)
num = int(input("Enter any no. from 1 to 7 to display day of the week : "))
if num == 1:
print('Sunday')
elif num == 2:
print('Monday')
elif num == 3:
print('Tuesday')
elif num == 4:
print('Wednesday')
elif num == 5:
print('Thursday')
elif num == 6:
print('Friday')
elif num == 7:
print('Saturday')
else:
print('Invalid number !')

Write a program which asks for a integer from the user. It reverses the integer and prints “same” if after
reversal the number is same as old number otherwise it prints “not same”.
n=int(input(“Enter a number”))
m=n
s=0
while(n!=0)
r=n%10
s=s*10+r
n=n//10
if s==m:
print(“Same”)
else:
print(“Not same”)
Write a program to print all the Krishnamurti number from 1 to n. Here, n is user dependent. A
Krishnamurti number is a number whose sum of factorial of individual digits equals the number. For
example, 145 = 1! + 4! + 5! = 1 + 24+ 120 = 145.

def factorial(n) :
fact = 1
while (n != 0) :
fact = fact * n
n=n-1
return fact

# function to Check if number is


# krishnamurthy/special
def isKrishnamurthy(n) :
sum = 0
temp = n
while (temp != 0) :

# calculate factorial of last digit


# of temp and add it to sum
rem = temp%10
sum = sum + factorial(rem)

# replace value of temp by temp / 10


temp = temp // 10

# Check if number is krishnamurthy


return (sum == n)

# Driver code
n = 145
if (isKrishnamurthy(n)) :
print("YES")
else :
print("NO")

Write a ‘Python’ program to find out a factorial of a given number.

num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)

Write a program to display the multiplication table of the number.


num = int(input("Display multiplication table of? "))

# Iterate 10 times from i = 1 to 10


for i in range(1, 11):
print(num, 'x', i, '=', num*i)

Write a Python program to check whether a number is prime or not.

n=5

# Check if the number is greater than 1

if n > 1:
for i in range(2, int(n/2)+1):
if (n % i) == 0:
print(num, "is not a prime number")
break
else:
print(n, "is a prime number")
# If the number is less than 1, its also not a prime number.
else:
print(n, "is not a prime number")
What is the use of break, continue and pass statement in Python.
In Python, the break statement allows you to exit out of a loop when an external condition is triggered.
You’ll put the break statement within the code block under your loop statement, usually after a
conditional if statement.
The continue statement allows you to skip over the part of a loop where an external condition is triggered,
but to go on to complete the rest of the loop. The current iteration of the loop will be disrupted, but the
program will return to the top of the loop.
The continue statement will be within the code block under the loop statement, usually after a
conditional if statement.
When an external condition is triggered, the pass statement allows you to handle the condition without the
loop being impacted in any way; all of the code will continue to be read unless a break or other statement
occurs.
Explain what is range() function and how it is used in for loop?

he range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.

range(start, stop, step)


Parameter Description

start Optional. An integer number specifying at which position to start.


Default is 0

stop Required. An integer number specifying at which position to stop


(not included).

step Optional. An integer number specifying the incrementation. Default


is 1

Write the syntax and usage of for loop


For loops in Python iterate over a sequence (such as a list, tuple, string, or range) and execute a block of
code multiple times. They're beneficial for performing repetitive tasks efficiently and can handle
numerical and non-numerical data. Python for loops are simple and flexible, making them a fundamental
tool for programming.
for item in sequence:
# Code block to be executed

Example

numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)

Module 4
How can you concatenate two strings in Python?
+
What is the output of the following Python code snippet?
string = "Hello, World!"
print(string[1:-1])
ello, World

Which method is used to find the index of the first occurrence of a substring in a string in Python?
find
What is the output of the following Python code snippet?
string = "Hello, World!"
print(string.replace("World", "Python"))
Hello, Python!
What will be the output? (1+1+3=5)
a) Select the correct output of the following String operations

str1 = "my isname isisis jameis isis bond"


sub = "is"
print(str1.count(sub, 4))
Ans 6
b) What is the output of the following string operations
str = "My salary is 7000"
print(str.isalnum())
Ans False

c) What is the ord() and chr() function in Python


ord() is used to convert a single Unicode character into its integer representation, i.e., it takes a single
string character as an input and returns an integer (representing the Unicode equivalent of the character)
as an output.
ord() function returns an error if the length of the string is not equal to 1.
Example
print(ord( 'A')) # 65
chr() function does exactly the opposite to the ord() function, i.e., it takes Unicode (a number between 0
and 1,114,111) and returns corresponding character.
print(chr(65)) # A
What is slicing in Python?Give examples.

Slicing in Python
Slicing is the process of accessing a sub-sequence of a sequence by specifying a starting and ending
index. In Python, you perform slicing using the colon : operator. The syntax for slicing is as follows:
sequence[start_index:end_index]
where start_index is the index of the first element in the sub-sequence and end_index is the index of the
last element in the sub-sequence (excluding the element at the end_index). To slice a sequence, you can
use square brackets [] with the start and end indices separated by a colon.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])

Write a program that takes a string from the user and then count the number of vowels separately.
vowels = set("aeiou")
ip_str = 'Hello, have you tried our tutorial section yet?'
ip_str = ip_str.lower()
count = {}.fromkeys(vowels,0)
for char in ip_str:
if char in count:
count[char] += 1
print(count)

Write a program to input a sentence from the user and prints the words that ends with “th” irrespective
of the case. Also prints the total count of such words
x=input("Enter a string")
x=x.casefold()
y=x.split()
k=0
for t in y:
if t.endswith("th"):
print (t)
k+=1
print(k)

Write a program that takes a string from the user and then check whether the string is palindrome or not
def isPalindrome(s):
return s == s[::-1]
s = "malayalam"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")

List five(5) built-in string methods with examples


Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case

count() Returns the number of times a specified value occurs in a string

endswith() Returns true if the string ends with the specified value

find() Searches the string for a specified value and returns the position of where it was found

index() Searches the string for a specified value and returns the position of where it was found

Write a Python program to count Uppercase, Lowercase, special characters and numeric values in a given
string(without using string method)
str = "abcd 1234$#"
upper_ctr, lower_ctr, number_ctr, special_ctr = 0, 0, 0, 0
for i in range(len(str)):
if str[i] >= 'A' and str[i] <= 'Z':
upper_ctr += 1
elif str[i] >= 'a' and str[i] <= 'z':
lower_ctr += 1
elif str[i] >= '0' and str[i] <= '9':
number_ctr += 1
else:
special_ctr += 1
print(upper_ctr, lower_ctr, number_ctr, special_ctr)
Write a Python program to find the longest word in a sentence.
def longest_word(input_string):
words = input_string.split()
return max(words, key=len)
print(longest_word("It is a house"))
Module 5
What is the output of the following program ?
def myfunc(a) :
a=a+2
a=a*2
return a
print (myfunc(2))
Ans. 8
Python supports the creation of anonymous functions at runtime, using a construct called __________.
Ans lambda
What will be the output of the following Python code ?
def power(x, y=2):
r=1
for i in range(y):
r=r*x
return r
print (power(3))
print (power(3,3))
Ans 9 27
Predict and explain the output of following program 5
r=lambda q:q*2
s=lambda q:q*3
x=2
x=r(x)
x=s(x)
x=r(x)
print(x)
Ans 24
Write a recursive function to find the factorial of a number.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = 7

# check if the number is negative


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_factorial(num))

What is function? Explain the different type of arguments in functions with examples.
Python Functions is a block of statements that return the specific task. The idea is to put some commonly
or repeatedly done tasks together and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability

Function arguments are values passed to a function when it is called. On the other hand, parameters are
the variables inside the function's parentheses. There are four types of function arguments in
Python: required arguments, default arguments, keyword arguments, and arbitrary arguments.
Differentiate between local and global variables in python with the help of a program

Parameter Local Variables Global Variables

Defined outside of all functions or


Definition Defined inside a function or block.
blocks.

Accessible only within the Accessible throughout the entire


Scope
function/block where it’s defined. program.

Exists only during the function’s Remains in memory for the duration
Lifetime
execution. of the program.

Cannot be accessed outside its Can be accessed and modified by any


Accessibility
function. function in the program.

Keyword for Use the global keyword to modify it


No special keyword is required.
Modification inside a function.

Memory Storage Stored in the stack. Stored in the data segment of


memory.

Risk of Unintended Low, as it’s confined to its


Higher, as any function can modify it.
Modification function.

What is lambda in Python? Why is it used?

A lambda function is an anonymous function (i.e., defined without a name) that can take any number of
arguments but, unlike normal functions, evaluates and returns only one expression.

A lambda function in Python has the following syntax:

lambda parameters: expression

The anatomy of a lambda function includes three elements:

 The keyword lambda — an analog of def in normal functions


 The parameters — support passing positional and keyword
arguments, just like normal functions
 The body — the expression for given parameters being evaluated
with the lambda function

Note that, unlike a normal function, we don't surround the parameters of a lambda function with
parentheses. If a lambda function takes two or more parameters, we list them with a comma.

We use a lambda function to evaluate only one short expression (ideally, a single-line) and only once,
meaning that we aren't going to apply this function later. Usually, we pass a lambda function as an
argument to a higher-order function (the one that takes in other functions as arguments), such as Python
built-in functions like filter(), map(), or reduce().

What does *args and **kwargs mean?


Introduction to *args and **kwargs in Python
In Python, we can pass a variable number of arguments to a function using special symbols. There are two special
symbols:

*args (Non Keyword Arguments)


**kwargs (Keyword Arguments)
We use *args and **kwargs as an argument when we are unsure about the number of arguments to pass in the
functions.

Python *args
As in the above example we are not sure about the number of arguments that can be passed to a function. Python has
*args which allow us to pass the variable number of non keyword arguments to function.

In the function, we should use an asterisk * before the parameter name to pass variable length arguments.The
arguments are passed as a tuple and these passed arguments make tuple inside the function with same name as the
parameter excluding asterisk *.

def adder(*num):
sum = 0

for n in num:
sum = sum + n

print("Sum:",sum)

adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
Python **kwargs
Python passes variable length non keyword argument to function using *args but we cannot use this to pass keyword
argument. For this problem Python has got a solution called **kwargs, it allows us to pass the variable length of
keyword arguments to the function.

In the function, we use the double asterisk ** before the parameter name to denote this type of argument. The
arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the
parameter excluding double asterisk **.
def intro(**data):
print("\nData type of argument:",type(data))

for key, value in data.items():


print("{} is {}".format(key,value))

intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890)


intro(Firstname="John", Lastname="Wood", Email="[email protected]", Country="Wakanda", Age=25,
Phone=9876543210)

Module 6
What data type is the object below ?
L=[1, 23, 'hello', 1]
Ans list
What is the output of the following Python code snippet?
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
Ans [3,4]
What will be the output of the following Python code ?
list1 = [1, 3]
list2 = list1
list1[0] = 4
print(list2)
Ans [4,3]
What is the output of the following code snippet ?
print([i.lower() for i in "HELLO"])
Ans ['h', 'e', 'l', 'l', 'o']
Which function is used to add an element (5) in the list1 ?
Ans list1.append(5)
What is the output of the following ?
print(max([1, 2, 3, 4], [4, 5, 6], [7]))
Ans [7]
What is the output of the following code ?
M=[‘a’ * x for x in range(4)]
print(M)
Ans. ['', 'a', 'aa', 'aaa']
What will be the output of the following Python code snippet?
my_list = [1, 2, 3, 4, 5]
my_list.pop(2)
print(my_list)

Ans [1,2,4,5]
Assume a list L1=[12,5,7,80,33,65]
a. Remove the element 80
b. Add 120 at the end of the existing list
c. Insert 75 at the index 2 of the list L1
d. Print the last element of the list
e. Print the list in sorted order
Ans a) L1.remove(80)
b) L1.append(120)
c) L1.insert(2,75)
d) print(L1[-1])
e) print(sorted(L1))
Write a Python program that accepts a list from the user and print all elements of list using for loop
lst = []

# number of elements as input


n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = int(input(“Enter a no”))
# adding the element
lst.append(ele)
for i in range(n):
print(lst[i])
Write a Python program that accepts a list from the user and find sum and average of the numbers in List
lst = []
s=0
# number of elements as input
n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = int(input(“Enter a no”))
# adding the element
lst.append(ele)
s=s+ele
print(s,(s/n)

Write a Python program that accepts a list from the user and print the smallest and largest number from a
list. 5
lst = []
# number of elements as input
n = int(input("Enter number of elements : "))

# iterating till the range


for i in range(0, n):
ele = int(input(“Enter a no”))
# adding the element
lst.append(ele)

print(“Largest”,max(lst))
print(“Smallest”,min(lst))

Write a python program to remove multiple elements from a list in Python. 5


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
x = []
for item in numbers:
if item not in x:
x.append(item)
print("Modified list:", x)

Write a Python Program to Square Each Element of the List and Print List in Reverse Order. 5
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for i in range(len(a)):
a[i]= a[i]**2
print(a[::-1])
Write a Python program to count Even and Odd numbers in a List
list1 = [10, 21, 4, 45, 66, 93, 1]

even_count, odd_count = 0, 0
# iterating each number in list
for num in list1:

# checking condition
if num % 2 == 0:
even_count += 1

else:
odd_count += 1

print("Even numbers in the list: ", even_count)


print("Odd numbers in the list: ", odd_count)

Write a Python program that accepts word from the user and store in list. Print the word that are
palindrome. 5

def isPalindrome(s):
return s == s[::-1]
s = ["malayalam",”madam”,”abcd”]
for i in s:
ans = isPalindrome(i)
if ans:
print(i)

Write a Python program to count the number of strings from a given list of strings. The string length is 2
or more and the first and last characters are the same.
Sample List:['abc', 'xyz', 'aba', '1221']
Expected Result : 2

def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1

return ctr

print(match_words(['abc', 'xyz', 'aba', '1221']))

Write a Python function that takes two lists and returns True if they have at least one common
member.
def common_data(list1, list2):
result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result

print(common_data([1, 2, 3, 4, 5], [5, 6, 7, 8, 9]))


print(common_data([1, 2, 3, 4, 5], [6, 7, 8, 9]))
What is the deep and shallow copy in Python?
Using copy() for Shallow Copy (only for the top-level list):

For a list with simple elements (like integers or strings), you can use the copy() method to create a
shallow copy. However, this does not create a true copy of nested lists.
original_list = [1, 2, 3]
shallow_copy = original_list.copy()
shallow_copy[0] = 99
print(original_list) # Output: [1, 2, 3] (unaffected)
But if the list contains nested lists, changes to the inner lists will affect both the original and the shallow
copy:
original_list = [[1, 2], [3, 4]]
shallow_copy = original_list.copy()
shallow_copy[0][0] = 99
print(original_list) # Output: [[99, 2], [3, 4]] (affected)
Using copy.deepcopy() for Deep Copy:

The copy module provides the deepcopy() function, which creates a true copy of the entire list, including
all nested elements.
import copy
original_list = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(original_list)
deep_copy[0][0] = 99
print(original_list) # Output: [[1, 2], [3, 4]] (unaffected)
With deepcopy(), any modifications to the copied list, including changes to nested lists, do not affect the
original list.

Write a Python program to convert a list of characters into a string.


a = ['h','e','l','l','o']
x = "".join(a)
print(x)
Module 7

How to create a single element in a tuple?


Ans. A=[12,]
What is the output of the following code
aTuple = (100, 200, 300, 400, 500)
print(aTuple[-4:-1])
Ans. (200,300,400)

Write a Python program to create a tuple with different data types.


# Create a tuple containing elements of different data types
tuplex = ("tuple", False, 3.2, 1)
# Print the contents of the 'tuplex' tuple
print(tuplex)

Write a Python program to check whether an element exists within a tuple.


tuplex = ("w", “e”, "s", "t", "b", "e", "n", "g", "a", "l")

# Check if the character "r" is present in the 'tuplex' tuple and print the result
print("r" in tuplex)
Write a Python program to reverse a tuple.
# Create another tuple containing a sequence of numbers
x = (5, 10, 15, 20)
y = reversed(x)
print(tuple(y))
What is the difference between list and tuple?
The key difference between tuples and lists is that while tuples are immutable objects, lists are mutable.
This means tuples cannot be changed while lists can be modified. Tuples are also more memory efficient
than the lists.

Discuss built-in Python Tuple Functions

len(tuple) Returns the total length of the tuple


max(tuple) Returns the largest element from the tuple

min(tuple) Returns the smallest element from the tuple

tuple(seq) Converts a list into tuple

Write a Python program to unpack a tuple into several variables.

t = (4, 8, 3)
print(t)
# Unpack the values from the tuple into the variables n1, n2, and n3
n1, n2, n3 = t
# Calculate and print the sum of n1, n2, and n3

print(n1 , n2 , n3)

Write a Python program to get the 4th element from the last element of a tuple.

x = (5, 10, 15, 20,34,5,89)

item1 = x[-4]

print(item1)
Write a Python program to remove an item from a tuple.
tuplex = ("w", e, "s", "t", "b", "e", "n", "g", "a","l")
listx = list(tuplex)
# Use the 'remove' method to eliminate the item "e" from the list
listx.remove("e")
# Convert the modified list back to a tuple to obtain 'tuplex' with the item removed
tuplex = tuple(listx)
# Print the final 'tuplex' tuple
print(tuplex)

Module 8
In the dictionary key and value pair which part holds the unique elements only?
Ans key
In the dictionary, which symbol is used to separate key and value pairs?
Ans :
How you make an empty dictionary in Python?

Ans. DICT={}

Can you include lists and tuples as pairs in the dictionary?

Ans yes

Which of the following function of dictionary gets all the keys from the dictionary ?
Ans keys()
Which line of code correctly adds an item to the fruits dictionary with a key of ‘grapes’ and a
value of 15?
Ans. fruits['grapes'] = 15
What will be the output of the following code?
D={1:7,2:"everyone"}
print(D[2])

Ans everyone

Apart from indexing which alternative function is used to access the value in dictionary?
Ans get()

Ans. Which method is used to remove all elements dictionary?


clear()

Check if a Given Key Already Exists in Dictionary


D1 = {'first_name' : 'Jim', 'age' : 23, 'height' : 6.0 , 'job' : 'developer', 'company': 'XYZ'}
def check_key(x):
if x in D1:
return 'Yes'
else:
return 'No'
print(check_key('first_name'))
Write a Python script to concatenate the following dictionaries to create a new one.
Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40}

dic1 = {1: 10, 2: 20}

dic2 = {3: 30, 4: 40}

dic3 = {}

for d in (dic1, dic2):

dic3.update(d)

print(dic3)

Write a Python program to check whether a given key already exists in a dictionary.
d = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
def is_key_present(x):
if x in d:
print('Key is present in the dictionary')
else:
print('Key is not present in the dictionary')
is_key_present(5)

Write a Python program to iterate through the key-value pairs in the dictionary using a for loop

d = {'x': 10, 'y': 20, 'z': 30}


for dict_key, dict_value in d.items():
print(dict_key, '->', dict_value)

Write a Python program to multiply all the items in a dictionary.


my_dict = {'data1': 100, 'data2': -54, 'data3': 247}
result = 1
for key in my_dict:
result = result * my_dict[key]
print(result)
Write a Python program to remove a key from a dictionary.
myDict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
print(myDict)
if 'a' in myDict:
del myDict['a']
print(myDict)
Write a Python program to sort a given dictionary by key.
d1 = {1:"one",2:"two",3:"three"}
for key in sorted(d1):
print(key, d1[key]))

Create Dictionary From Two Lists l1 = [1,2,3] and l2 = ["one","two","three"]


output will be
{1:"one",2:"two",3:"three"}

l1 = [1,2,3]
l2 = ["one","two","three"]
res = {}
for key in test_keys:
for value in test_values:
res[key] = value
print("Resultant dictionary is : " + str(res))

Difference between tuple and dictionary

The following are the main differences between a tuple and a dictionary in python.

Tuple Dictionary

A tuple is a non-homogeneous data structure that can Dictionary is a non-homogeneous data structure
hold a single row as well as several rows and columns. that contains key-value pairs.

Tuples are represented by brackets (). Dictionaries are represented by curly brackets {}.

Dictionaries are mutable and keys do not allow


Tuples are immutable i.e, we can not make changes.
duplicates.

A tuple is ordered. Dictionary is ordered (python 3.7 and above).

Tuple can be created using tuple() function. Dictionary can be created using the dict() function.

Creating an empty Tuple: () Creating an empty dictionary: {}

As tuples are immutable, the reverse() method is not Because the dictionary's entries are in the form of
defined in them. key-value pairs, the elements cannot be reversed.

Example: (“python”, “is”,“simple”) Example : {1: 'One', 2: 'Two'}


Merge two Python dictionaries into one
dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
Expected output:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}


dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
dict3 = dict1.copy()
dict3.update(dict2)
print(dict3)

Discuss built-in methods in dictionary.

Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair

Convert a list of tuples into a dictionary.


tuple_list = [("a", 1), ("b", 2), ("c", 3)]
converted_dict = dict(tuple_list)
print(converted_dict)

Module 9:
Ravi opened a file in python using open( ) function but forgot to specify the mode. In which mode the file
will open ?
Ans. read
Which statement will move file pointer 10 bytes backward from current position ?
Ans. f.seek(-10,1)

Which statement will return one line from a file (file object is f)?
Ans. f.readline()
What will be the output of the following code ?
f=open("demo.txt","r")
print(f.tell())
Ans 0
Which method is used to check if a file exists in Python?
isfile()
Print a line with line numbers from a file
F1=open(“file1.txt”,”r”)
n=1
for line in F1:
print(str(n)+”:”+line)
n=n+1
F1.close()

Write a program code to open a data file. Save element values 2, 4, 9, 10, 11 in this data file and read the
numbers from file

n = [2,4,9,10,11]
with open('abc.txt', "w") as myfile:
for c in n:
myfile.write("%s\n" % c)

content = open('abc.txt')
print(content.read())
Differentiate between the following : (a) readline() and readlines() (b) tell() and seek()

a)The readline() method returns one line from the file.


You can also specified how many bytes from the line to return, by using the size parameter.
The Python File readlines() method reads all the lines from a file in a single go. That means, a file is read
continuously until the End Of File (or EOF) is hit.
b) The seek() function in Python is used to move the file cursor to the specified location. When we read a
file, the cursor starts at the beginning, but we can move it to a specific position by passing an arbitrary
integer (based on the length of the content in the file) to the seek() function.
seek(offset, whence)

Here,

offset – Required parameter. Sets the cursor to the specified position and starts reading after that position.

whence – Optional parameter. It is used to set the point of reference to start from which place.

0 – Default. Sets the point of reference at the beginning of the file. Equivalent to os.SEEK_SET.

1 – Sets the point of reference at the current position of the file. Equivalent to os.SEEK_CUR.

2 – Sets the point of reference at the end of the file. Equivalent to os.SEEK_END.
whereas the tell() function returns the position where the cursor is set to begin reading.
Syntax
tell()

The tell() function takes no parameter.


Opening a file in binary mode
with open('sample.txt', 'rb') as file:
# Setting cursor at the 25th pos from the end
file.seek(-25, 2)
# Using tell() function
pos = file.tell()
# Printing the position of the cursor
print(f'File cursor position: {pos}')
# Printing the content
data = file.read()
print(data)

Module 10:
-------- and ---------------- are the two main aspects of OOPs
Ans Class, Objects

_____ represents an entity in the real world with its identity and behavior.
Ans. An object

What is the correct way to define a class in Python?

Ans class abc:

What will be the output of the following Python code?


class test:
def __init__(self,a="Hello World"):
self.a=a
def display(self):
print(self.a)
obj=test()
obj.display()
Ans. Hello World
What will be the output of the following Python code?

class change:
def __init__(self, x, y, z):
self.a = x + y + z

x = change(1, 2, 3)
y = getattr(x, 'a')
setattr(x, 'a', y + 1)
print(x.a)
Ans 7
Which access specifier in Python indicates that an attribute should not be accessed directly from outside
the class?
Ans. private
What is the process of defining a new class based on an existing class called?
Ans inheritance
What is the purpose of the __init__ method in Python classes?
Ans. The __init__ method is a special method in Python classes used to initialize newly created objects
with initial values.
Which feature of OOPS described the reusability of code?
Ans. Inheritance

How do you create a constructor in Python? Explain with an example. 5

In Python, a constructor is a special method called __init__() that is automatically invoked when a new
object of a class is created. It is used to initialize the object's state or set up initial values for its attributes.

Here’s an example of creating a constructor in Python:

class Car:

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year

car1 = Car("Toyota", "Corolla", 2020)

print(car1.make) # Output: Toyota

print(car1.model) # Output: Corolla

print(car1.year) # Output: 2020

Differentiate between class variables and instance variables? 5

In Python, instance variables belong to instances of a class, representing the state of individual objects,
while class variables belong to the class itself, representing attributes shared by all instances of the class.
Instance variables are defined within methods using the self keyword and are unique to each instance,
whereas class variables are defined outside methods and are accessed using the class name. Instance
variables are specific to each object, while class variables are common to all objects of the class.

What is class instatiation? How is it done? 5

When a copy of a class is created that inherits all the class properties and functions, it is called
instantiating a class. To instantiate a class in Python, the class like it is called a function, passing the
arguments defined by the __init__ method. The newly created object is the return value.

Differentiate between public and private variables. 5


The main difference between public and private variables is their visibility. Public variables can be
accessed by any code that has a reference to the object, while private variables can only be accessed
within the class in which they are defined.

Explain inheritance in python. 10

Inheritance is the capability of one class to derive or inherit the properties from another class.

Benefits of inheritance are:

Inheritance allows you to inherit the properties of a class, i.e., base class to another, i.e., derived class.
The benefits of Inheritance in Python are as follows:

It represents real-world relationships well.

It provides the reusability of a code. We don’t have to write the same code again and again. Also, it
allows us to add more features to a class without modifying it.

It is transitive in nature, which means that if class B inherits from another class A, then all the subclasses
of B would automatically inherit from class A.

Inheritance offers a simple, understandable model structure.

Less development and maintenance expenses result from an inheritance.

Python Inheritance Syntax

The syntax of simple inheritance in Python is as follows:

Class BaseClass:

{Body}

Class DerivedClass(BaseClass):

{Body}

What is the purpose of the super() function in Python? 8

The super() function in Python is used to call methods and access attributes from the superclass (parent
class) within a subclass (child class). It allows subclasses to inherit and leverage behavior from their
superclass, facilitating code reuse and maintaining a clean and organized class hierarchy. By using
super(), developers can invoke superclass methods and constructors, ensuring that all necessary
initialization and functionality from the superclass are properly executed within the subclass.

What are the main features in oops? 7


Python showcases OOP with powerful features for systematic software development.
 OOP starts with classes, which act as blueprints for creating objects. Objects are instances of
these classes, encapsulating both data and functionality.
 Encapsulation involves bundling data and the methods that operate on the data within a single
unit, a class. This ensures that the internal workings of an object are hidden from the outside
world, promoting data security and code organisation.
 Inheritance allows a class to inherit properties and methods from another class. This promotes
code reuse and establishes a hierarchy of classes. In Python, a class can inherit from one or more
classes, supporting single and multiple inheritance.
 Polymorphism enables objects to take multiple forms. In Python, this can be achieved through
method overloading and method overriding. Polymorphism enhances flexibility by allowing
different objects to be treated uniformly, promoting code extensibility.
 Abstraction
 Abstraction involves simplifying complex systems by modelling classes based on the essential
features they provide. Abstract classes and methods in Python allow developers to define
blueprints without providing a complete implementation, leaving room for further customization
in derived classes.
 Constructors initialise objects when they are created, ensuring that they start with a valid state.
Python supports both the __init__ method as a constructor and the __del__ method as a destructor
for resource cleanup. Constructors contribute to object initialization, while destructors handle
cleanup tasks when an object is no longer in use.
 OOP in Python allows developers to choose between composition and inheritance. Composition
involves creating relationships between classes by including instances of other classes, promoting
code flexibility. This provides an alternative to traditional inheritance, allowing for better code
maintainability in specific scenarios.
OOP in Python provides a comprehensive set of features that facilitate code organisation, reusability, and
maintainability. By leveraging classes, encapsulation, inheritance, polymorphism, abstraction,
constructors, and design principles, developers can build efficient and scalable software solutions in a
structured manner.

Write a Python program to create a class representing a Circle. Include methods to calculate its area and
perimeter 10
class Circle:
# Initialize the Circle object with a given radius
def __init__(self, radius):
self.radius = radius

# Calculate and return the area of the circle using the formula: π * r^2
def calculate_circle_area(self):
return 3.1415 * self.radius**2

# Calculate and return the perimeter (circumference) of the circle using the formula: 2π * r
def calculate_circle_perimeter(self):
return 2 * 3.1415 * self.radius

# Example usage
# Prompt the user to input the radius of the circle and convert it to a floating-point number
radius = float(input("Input the radius of the circle: "))

# Create a Circle object with the provided radius


circle = Circle(radius)

# Calculate the area of the circle using the calculate_circle_area method


area = circle.calculate_circle_area()

# Calculate the perimeter of the circle using the calculate_circle_perimeter method


perimeter = circle.calculate_circle_perimeter()

# Display the calculated area and perimeter of the circle


print("Area of the circle:", area)
print("Perimeter of the circle:", perimeter)
What is polymorphism in Python?

What is Polymorphism?

The literal meaning of polymorphism is the condition of occurrence in different forms.

Polymorphism is a very important concept in programming. It refers to the use of a single type entity

(method, operator or object) to represent different types in different scenarios.

You might also like