Python Practice Questions

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Data Type:

Q1. Write a program which accepts a sequence of comma-separated numbers from a file and generate a
list and a tuple which contains every number.
Suppose the following input is supplied from a file to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '55', '33', '12', '98']
('34', '67', '55', '33', '12', '98')

Q2. Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25]) and makes a new
list of only the first and last elements of the given list.
print("Enter a list numbers")
lst = [i for i in input().split()]
new_list = []
new_list.append(lst[0])
new_list.append(lst[len(lst)-1])
print(new_list)

Q3. Write a program where initialize a list a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]. Write one line of
Python that takes this list a and makes a new list that has only the even elements of this list in it.
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
lst = [i for i in a if i%2==0]
print(lst)

File Handling:
Q. Given a ‘input.txt’ file that has a list of a bunch of comma separated names , count how many of each
name there are in the file, and write out the results to another text file ‘output.txt’.
Assume ‘input.txt’ file content is:
Kamal, Aryan, Raj, Kamal, Aryan, Deepak, Rahul, Raj, Deepak, Kamal, Rishav, Vishal, Ayushi, Rishav,
Aryan, Deepak

Exception Handling:
Q. You are given two values  x and y, perform integer division x/y and print output, every kind of
exception should be handled.
try:
x = int(input("Enter x:"))
y = int(input("Enter y:"))
quo = x/y
except ZeroDivisionError:
print("Cannot be divided by 0!!")
except ValueError:
print("Enter a valid number!!")
finally:
print("Program execution successful!")
Q. Write your custom exception class “MyExceptions” and use it with any other python program .
class MyExceptions(Exception):
pass

def verify_age(age):
if age < 18:
raise MyExceptions("Pahle baalig ho jao!!")
else:
print("Badhai ho! Tum baalig ho!")

a = int(input("Umra batao: "))


try:
verify_age(a)
except MyExceptions as e:
print("Gadbad haigo!\nError:",e)
finally:
print("Chalo ji! Phir mulakat hogi!")

Oops:
Q. You are given two complex numbers , and you have to print the result of their addition, subtraction,
multiplication, division and modulus operations, use classes for this, implement operator overloading.

Q. Write a class A and implement some methods (add, subtract, divide integers), write another class B
which inherits class A and call these 3 methods from class B object.

Loops and Iterators:


Q. Read an integer N from user, for all non-negative integers i<N, print i*2, write separate programs
using every kind of loop.
num = int(input("Number: "))

# for loop
print("For Loop")
for i in range(1, num):
print(i*2, end=" ")

print()

# while loop
print("While Loop")
i=1
while i < num:
print(i*2, end=" ")
i += 1
Q1) Reverse a given list using list comprehensions. Reverse same list also using list slicing.
# Reversing List using Slicing
print("Enter List")
lst = [i for i in input().split()]
rev_lst = lst[ : :-1]
print(rev_lst)

# Reversing List using List Comprehension


print("Enter List")
lst = [i for i in input().split()]
rev_lst = [lst[i] for i in range(len(lst)-1, -1, -1)]
print(rev_lst)

Q2) Write a function to verify that tuple is immutable this function takes any tuple as parameter.

Q3) Convert nested dictionary into flattened dictionary for example


               given a input test = {"outer1": {"inner1": {"inner2": "data"}}, "outer2": "data", "outer3":
{"inner3": "data"}}
               output should be:
               {"outer1_inner1_inner2": "data", "outer2": :"data", "outer3:inner3": "data"}
               Your program should also work for very large nested dict.

Q4) Why python is called dynamically typed language?

Q5) Create a function which takes a string as an input and modify it by inserting tab escape sequence
between every character of it and return it.
    So when returned data is printed it shows tabs between every character on console.
def convert(s):
new_s = []
k=0
length = len(s) + len(s)-1
for i in range(0,length):
if i%2==0:
new_s.append(s[k])
k += 1
else:
new_s.append('\t')
res = str("".join(new_s))
return res

print(convert("nitish"))
Q6) Using python string formatting print a table on console like this:

Name        Age        class        Roll


Rishav      18         12           56565
Vishal      15         10           131313
Etc
data = [['NAME', 'AGE', 'HANDEDNESS', 'SCORE (%)'],
['Martin', 38, 'L', 54.123],
['Marty', 33, 'L', 32.438],
['Martine', 25, 'R', 71.128],
['Martyn', 59, 'R', 50.472],
['Mart', 23, 'L', 2.438],
['Martyne', 15, 'R', 71.128],
['Marlyn', 101, 'R', 0.472],
['Marti', 2, 'L', 55.438],
['Mardi', 9, 'R', 81.128],
['Martyne', 49, 'R', 24.472],
['Marteen', 91, 'L', 1.128]]

dash = '-' * 40
for i in range(len(data)):
if i == 0:
print(dash)
print('{:<10s}{:>4s}{:>12s}{:>12s}'.format(data[i][0],data[i][1],data[i][2],data[i][3]))
print(dash)
else:
print('{:<10s}{:>4d}{:^12s}{:>12.1f}'.format(data[i][0],data[i][1],data[i][2],data[i][3]))

Q7)Write a class which reads text file and create another file converting all data in binary and vice versa.
               This is simplest form of data encryption/decryption, This class can have following methods:

               read_text()
               write_binary()
               read_binary()
               write_text()

               Implement this class with context manager.

Q8)         Implement a bare minimum example class which shows following:

               data hiding


               Object printing
               Inheritance
               polymorphism
               abstraction

Q9) what is the difference between iterator and generator.


               Create a generator on which a program can iterate from 1 to 1000

               print numbers from 1 to 100000 on console using:


               iterator
               generator

               and tell which is better and why.

Q10) Write your own exception class and inherit properties of "Exception" class.
               Write a program to show usage of your custom class.

You might also like