0% found this document useful (0 votes)
51 views

Python PRactice Questions

Uploaded by

prathamdhobi360
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Python PRactice Questions

Uploaded by

prathamdhobi360
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Question 1  Give the output for the following Python code snippets and justify

your answer:

 Write a Python function, with appropriate comments, to reverse each


word of a sentence passed to it as a string parameter. For example,
Input : ‘My Name is Jessa’
Output : ‘yM emaN si asseJ’

 Write a Python function, with appropriate comments, that takes name


and age of a person as input and displays an appropriate message
whether the person is eligible to vote or not. Minimum age for voting
being 18 years.
Question 2  Write a Python function with appropriate comments that takes an
integer n as input to find the sum of the following series:
1*3/1! + 2*5/2! + 3*7/3! + … + n*(2n+1)/n!
Use appropriate assertions where needed.

 What will be the output of the following? Justify your answers.

 For the following sets:


s = set (['a', 'b', 'c', 'd', 'e'])
v = set (['x', 'y', 'z'])
What will be the output of the following? Justify your answers.

 Write a Python function with appropriate comments, that takes a list


of values as input parameter and returns a new list after removing the
duplicate values in the original list. The function should also return
the number of elements in the new list. For example,
Input to the function: [ 1,4, 6, 1, 3, 1, 6]
Values returned form the function: [1,4,6,3],
4
Question 3  Write a Python function with appropriate comments that takes an
integer n as parameter and prints the following pattern. For example,
for n = 5 it prints:
*
***
*****
***
*

 For the given string:


s1 = 'Programming is Fun!'
What will be the output of the following? Justify your answer.

 Write a Python function with appropriate comments that reads the


contents of the file “Poem.txt” and prints the number of alphabets,
blank spaces, lowercase letters and uppercase letters, the number of
words starting with a vowel, and the number of occurrences of each
word in the file.
 Show the contents of the stack after every operation during
evaluation of the postfix expression: 836+27-9+*/
Question 4  Write a Python function searchKey(inList, key) with
appropriate comments for searching the key in the list of n integers
inList using linear search. The function should return the index of
the item if it is present in the list, otherwise, it should return -1. Write
the statements to call searchKey()when inList=[10,4,5,-7, 23]
and key = -77.

 For the given dictionary:


Grades = {“Sahil” : 90, “Abhijeet” : 65}
What will be the output of the following? Justify your answer.

 Given the tuple:


t1 = (12, 5, 2, 4, 17, 6, 9, 10)
Write Python statements to:
 Print first half of the values of t1 in one line and the other half
in another line.
 Display a list comprising all the even numbers in the tuple t1.
 Concatenate a tuple t2=(11,13,15) with t1.
 Return maximum and minimum value from t1.
 Create a tuple t3 with only one element 10 in it.

 Write one line Python code for:


 Swapping two numbers without using a third variable.
 Generating the series 7, 14, 21….. 70 using the range function.
 Finding the cube of first 5 natural numbers using list
comprehension.
Question 5  Consider a queue that is initially empty. It undergoes the following
sequence of operations: enqueue(5), enqueue(10),
dequeue, enqueue(20), enqueue(25), dequeue,
dequeue, dequeue, dequeue. Show the contents of the
queue after each operation.

 A Fibonacci sequence is a sequence of integers: 0, 1, 1, 2, 3, 5, 8, ....


where the first two terms are 0 and 1. All other terms are obtained by
adding the preceding two terms. In other words, nth term is the sum of
(n-1)th and (n-2)th term. Define a Python function fibo, with
appropriate comments, to display the Fibonacci sequence up to n
terms where n is passed as parameter to the function.

 Given that:
list1 = [1, 2, 3]
list2 = ['a', 1, 'z', 26,'d', 4]
What will be the output of the following? Justify your answer.

 Identify the errors in the following code and rewrite the correct code:
Question 6 Define a Python class BankAccount that keeps track of a bank’s
customers having the following data members:
name: Name of the customer
accountNum: Account Number (auto generated value, beginning at 1)
balance: Amount deposited in the Bank account
Keep an additional variable count to record the number of objects
created for this class. Every time a new account is opened in the bank, the
count is updated.

The class should support the following methods:


 Deposit: for depositing money in the account
 Withdraw: for withdrawing money from the account
 A method to display the total number of accounts in the bank.
 The str function to display the complete details of an object of the
BankAccount.
 findInterest: to determine the interest on the basis of
balance in the account and the interest rate applicable as per the
table listed below:

Amount Rate of Interest (%)


>= 3,00,000 7
>= 1,00,000 and < 3,00,000 5
< 1,00,000 3

Write statements to:


 Create an account for Ms ABC having a balance of Rs 2,50,000,
and Mr PQR having a balance of Rs 3,50,000. Display the number
of accounts in the bank.
 Ms ABC keeps this money with the bank for a year. Calculate the
interest for Ms ABC. Also, after end of 1 st year, she deposits the
same amount in her account. Show the updated balance for her
account.
 Mr PQR withdraws Rs 1,00,000 from the account. Display the
updated balance for his account.

 Which of the following are valid identifiers? If they are invalid, then mention the
cause of violation.
 #ofElements
 No of elements
 3elements
 noOfElements
 for
 In
 What will be the value associated with the variable name a on execution of the
following statements? Justify your answers.
 b = 10
a *= b + 2
 a = 2 + 3 ** 2 // 4 % 3
 a = "32 * 76"
 a = 'ho' * 5
 a = 'string' > 'Strings'
 a = ~-12

Q2 Write functions for the following (n to be passed as an argument to the function):


 display the following pattern:
A
BA B
C B A B C
D CBA B C D
A BCBA
A B A
A
Here n is the number of rows in the diamond shape, assume that n is odd
and less than 52. For the above sample figure n is 7.

 sum of the first n terms of following series:


1 1 1
𝑆 =1− + − +⋯
2 3 4

 greatest common divisor of two numbers (in addition to n, another argument m


is passed to the function)

Q3
 You are given a dictionary priceList = {"Pen" : 10, "Pencil" : 5,
"Eraser" : 5, "Ruler" : 20}, representing products and their rates.
 write a function rate that accepts this dictionary along with the name of a
product and returns the price of that product. If the product does not exist in
the dictionary, then it should return -1. For example, if the name of the product
is Ruler then the function should return 20.
 write another function update to modify the dictionary. The function should
accept the dictionary, name of a product and new rate for it. The function
should return the updated dictionary as per the following cases:
Case 1: if the rate of the product is negative or zero and the product exists in
the dictionary then the product should be removed from the dictionary
Case 2: if the rate of the product is positive and the product exists in the
dictionary then the rate of the product in the dictionary should be changed to
the new rate that is passed to the function
Case 3: if the rate of the product is positive and the product does not exist in
the dictionary then the product-rate pair should be added to the dictionary

 Which of the following fourteen statements (Line 1 to Line 14) have


errors? Identify all errors and justify your answers.

str = "Hello There" # Line 1


str[6] = 't' # Line 2
print(str[12]) # Line 3
print(str[-2 : -4]) # Line 4
print(str[2 : 12]) # Line 5

lst = list(str) # Line 6


lst[3] = 'i' # Line 7
print(lst[2 : 4]) # Line 8

s = set(str) # Line 9
s[3] = 'i' # Line 10
print(s[2 : 4]) # Line 11

t = tuple(s) # Line 12
t[3] = 'i' # Line 13
print(s[2 : 4]) # Line 14

Q4
 Consider the following two tuples showing games played by Ramesh and Suresh:
gamesRamesh = ('lawn tennis', 'cricket')
gamesSuresh = ('cricket', 'hockey', 'badminton')
Write the statements to compute the following:
 games played by Suresh but not Ramesh
 games that are common to both of them
 all the games that are played by either of them
 games that are not common to both of them

 What will be the output produced on execution of the following code segments? Justify
your answers.

 def fun(a = 0, b = 1):


return a * b

print(fun(5, 6))
print(fun(6))
print(fun(b = 5))
print(fun())

 import copy
lst1 = [13, 23, [38, 42], 52]
lst2 = copy.deepcopy(lst1)
lst3 = lst1
lst2[2][0] = 78
lst3[3] = 61
print(lst1, lst2, lst3)

 def m(s):
ans = ''
for i in range(len(s)):
if i % 2 == 0:
ans += s[i]
return ans
print(m('HelloWorld'))
 lst = [x * y for x in range(3, 9, 2) for y in range(6,
1, -1) if x * y % 2 == 0 ]
print(lst)

 def fn(a, n):


try:
print(a[n])
except IndexError:
print("In IndexError")
raise ValueError("An error")
except:
print("Some error")
print("Bye")

lst = [1, 2, 3]
try:
fn(lst, 1)
fn(lst, 3)
fn(lst, 2)
except ValueError as msg:
print(msg)
Q5
 Write a program to read three sides of a triangle and display whether the triangle
is a scalene or equilateral or isosceles triangle, provided that the sides entered by
the user are positive and they form a valid triangle. The program should have
assert statements to ensure that these two conditions are satisfied.

 Write a function that accepts the name of a file as an argument and returns the
number of lines in the file. The function should return -1 if the specified file
does not exist.

 Write a function for linear search that accepts two arguments: a list of numbers
and a number to be searched. Assume that the list can have duplicate elements.
The function should return a list of all the indices corresponding to the element
being searched. If the element is not there, then the program should return the
list [-1]. For example, if the list is [68, 24, 68, 68, 24, 14] and 68 is to be
searched
then the function should return [0, 2, 3].

Q6 Define a class Student that keeps a record of students. The class should contain the
following:
 data members for every student: rollNo, Name, Class, Section,
marks1, marks2, and marks3. Assume that the maximum marks for each
subject are 100.
 an additional data member count to keep a record of the number of objects
created for this class. Add appropriate statements in the code to increment the
value of count by 1, when an object is created.
 Also define function members:
 a constructor function to initialize the members
 a function grade, that returns the overall grade of the student according
to the following criteria:
A : if percentage ≥ 90
B : if percentage ≥ 80 and < 90
C : if percentage ≥ 70 and < 80
D : if percentage < 70
 str function to display the details of a student including the overall
grade of the student

Also write statements for the following:


 create an object s1 of this class for a student Tarun of Class BE IV having roll no
15 and marks in three subjects as 83, 93, 86.
 display the details of the student s1 using str function statement.

You might also like