Python Questions with solution
Python Questions with solution
Q1. Define Python and mention its key features. (K1, CO1, PO1)
Solution:
Python is a high-level, interpreted programming language known for its simplicity, readability, and
flexibility.
Key features:
Q2. How are variables assigned in Python? Give an example. (K1, CO1, PO1)
Solution:
Variables in Python do not need an explicit declaration. The assignment happens using the =
operator.
Example:
x = 10 # Integer variable
print(x, y, name)
Q3. What are Python’s standard data types? (K1, CO1, PO1)
Solution:
Python has the following standard data types:
Q4. Differentiate between mutable and immutable types in Python. (K2, CO1, PO2)
Solution:
Mutable objects: Can be changed after creation (e.g., list, dict, set).
Immutable objects: Cannot be changed after creation (e.g., int, float, str, tuple).
Example:
# Mutable Example
lst = [1, 2, 3]
# Immutable Example
name = "Python"
Solution:
Python manages memory using:
import gc
Q6. What are Python Identifiers? Give examples. (K1, CO1, PO1)
Solution:
Identifiers are variable, function, class, and module names in Python.
Rules:
Example:
_myVar = 10 # Valid
Q7. Write a Python program to demonstrate the use of comments. (K2, CO1, PO2)
Solution:
"""
"""
x = 5 # Assigning value to x
print(x)
Solution:
Python supports:
Example:
a = 10
b=5
Solution:
Python is preferred for ease of use, while Java and C++ are faster but complex.
Q10. Explain string operations in Python with examples. (K3, CO1, PO3)
Solution:
Python provides various string operations:
1. Concatenation (+)
2. Repetition (*)
3. Slicing ([start:end])
Example:
s = "Hello"
print(s.upper()) # HELLO
Q11. Discuss the built-in functions available in Python for numbers and strings. (K3, CO1, PO3)
Solution:
Example:
print(abs(-10)) # 10
print(len("Python")) # 6
Q12. Write a Python program to illustrate the use of different data types. (K4, CO1, PO4)
Solution:
x = 10 # Integer
y = 3.14 # Float
z = "Hello" # String
Output:
<class 'int'> <class 'float'> <class 'str'> <class 'list'> <class 'tuple'> <class 'dict'>
Alright! Let’s move on to Unit 2: Lists, Dictionaries, Conditionals, and Loops with short and long
questions along with their solutions, categorized based on Bloom's Taxonomy (K1-K6), COs, and
POs.
Q1. What are lists in Python? Explain with an example. (K1, CO1, PO1)
Solution:
A list is an ordered, mutable collection of items. Lists can hold elements of different types.
Example:
Q2. What is a dictionary in Python? How is it different from a list? (K1, CO1, PO1)
Solution:
A dictionary is an unordered collection of key-value pairs. Unlike lists, dictionaries are accessed using
keys rather than indices.
Example:
my_dict = {"name": "John", "age": 25}
Difference:
Q3. What are the built-in methods available for lists? (K2, CO1, PO2)
Solution:
Some important list methods:
Example:
lst = [3, 1, 2]
lst.append(4)
lst.sort()
Q4. Explain the difference between a tuple and a list. (K2, CO1, PO2)
Solution:
Example:
Q5. How does the for loop work in Python? (K2, CO1, PO2)
Solution:
A for loop iterates over a sequence (list, tuple, string, etc.).
Example:
print(i)
Output:
Q6. What is the use of the break statement in loops? (K2, CO1, PO2)
Solution:
The break statement is used to exit a loop when a condition is met.
Example:
if num == 5:
break
print(num)
Output:
Q7. Explain the use of continue and pass statements. (K2, CO1, PO2)
Solution:
Example:
for i in range(5):
if i == 3:
continue # Skips 3
print(i)
Output:
Q8. Write a Python program to demonstrate list operations (append, remove, sort). (K3, CO2, PO3)
Solution:
# List operations
numbers = [4, 1, 3, 2]
numbers.append(5) # Append 5
numbers.remove(3) # Remove 3
Q9. Explain dictionary operations with a Python program. (K3, CO2, PO3)
Solution:
# Creating a dictionary
# Modifying a value
student["age"] = 23
# Deleting a key
del student["grade"]
print(student)
Q10. Write a Python program using conditional statements (if, elif, else). (K3, CO2, PO3)
Solution:
if num > 0:
print("Positive Number")
print("Negative Number")
else:
print("Zero")
Q11. Write a Python program to calculate the sum of all elements in a list. (K3, CO2, PO3)
Solution:
total = sum(numbers)
Q12. Write a Python program to demonstrate looping through dictionary keys and values. (K3,
CO2, PO3)
Solution:
name : John
age : 21
grade : A
Q13. Explain the difference between while and for loops with examples. (K4, CO2, PO4)
Solution:
Usage Used for iterating over sequences Used when a condition must be met
Example:
# For loop
for i in range(3):
print(i)
# While loop
i=0
while i < 3:
print(i)
i += 1
Q14. Write a Python program to count occurrences of elements in a list using a dictionary. (K4,
CO2, PO4)
Solution:
numbers = [1, 2, 2, 3, 3, 3, 4]
count_dict = {}
count_dict[num] = count_dict.get(num, 0) + 1
print(count_dict)
# Output: {1: 1, 2: 2, 3: 3, 4: 1}
Q15. Analyze the use of looping structures in handling large datasets. (K5, CO2, PO5)
Solution:
Loops allow efficient traversal and modification of large datasets. For loops iterate over structured
data, while while loops are useful when conditions must be met dynamically.
sum_data = sum(data)
print(sum_data)
Great! Let’s move on to Unit 3: Objects, Classes, and Files with short and long questions along with
solutions, categorized based on Bloom's Taxonomy (K1-K6), COs, and POs.
Solution:
A class is a blueprint for creating objects. It defines attributes (variables) and behaviors (methods).
Example:
class Car:
self.brand = brand
my_car = Car("Toyota")
Q2. Define an object in Python and give an example. (K1, CO1, PO1)
Solution:
An object is an instance of a class. It contains data (attributes) and functions (methods).
Example:
class Student:
s1 = Student("Alice")
Q3. What is the purpose of the __init__ method in Python classes? (K2, CO1, PO2)
Solution:
The __init__ method is the constructor that initializes an object’s attributes when it is created.
Example:
class Person:
self.name = name
self.age = age
Q4. What is inheritance in Python? Explain with an example. (K2, CO1, PO2)
Solution:
Inheritance allows a class (child) to inherit attributes and methods from another class (parent).
Example:
class Animal:
def speak(self):
class Dog(Animal):
def speak(self):
return "Bark"
d = Dog()
Example:
class Cat:
def sound(self):
return "Meow"
class Dog:
def sound(self):
return "Bark"
print(animal.sound())
Q6. What are class variables and instance variables? (K2, CO1, PO2)
Solution:
Example:
class Student:
Q7. How does Python handle file operations? (K2, CO1, PO2)
Solution:
Python provides built-in functions like open(), read(), and write().
Example:
Q8. Write a Python program to create a class, instantiate an object, and access its attributes and
methods. (K3, CO2, PO3)
Solution:
class Car:
self.brand = brand
self.model = model
def details(self):
Q9. Write a Python program demonstrating multiple inheritance. (K3, CO2, PO3)
Solution:
class Parent1:
def func1(self):
class Parent2:
def func2(self):
pass
c = Child()
print(c.func1()) # Output: Function from Parent1
Solution:
Method overriding allows a child class to provide a different implementation of a method from its
parent class.
Example:
class Animal:
def speak(self):
class Dog(Animal):
def speak(self):
return "Bark"
d = Dog()
Q11. Write a Python program to create and read a file. (K3, CO2, PO3)
Solution:
# Writing to a file
file.write("Hello, Python!")
content = file.read()
print(content)
Q12. Explain the concept of file handling modes in Python. (K4, CO2, PO4)
Solution:
Mode Description
r Read (default)
w Write (overwrite)
a Append
Example:
f.write("New data")
Q13. Write a Python program to copy the contents of one file to another. (K4, CO2, PO4)
Solution:
dest.write(src.read())
Q14. Explain the concept of serialization and deserialization using the pickle module. (K5, CO2,
PO5)
Solution:
Serialization (dump) converts objects to a binary format, while deserialization (load) restores them.
Example:
import pickle
# Serialization
pickle.dump(data, f)
# Deserialization
loaded_data = pickle.load(f)
print(loaded_data) # Output: {'name': 'Alice', 'age': 25}
Q15. Explain exception handling in Python with an example. (K5, CO2, PO5)
Solution:
Exception handling uses try-except to prevent crashes.
Example:
try:
print(10 / num)
except ZeroDivisionError:
except ValueError:
print("Invalid input!")
Q16. Analyze how object-oriented programming enhances code reusability. (K6, CO2, PO6)
Solution:
OOP improves code reusability through:
Example:
class Vehicle:
def start(self):
return "Starting"
class Car(Vehicle):
pass
c = Car()
Solution:
A regular expression (regex) is a sequence of characters defining a search pattern. Python's re
module provides regex functionalities.
Example:
import re
Q2. List any four special characters used in regular expressions. (K1, CO1, PO1)
Solution:
Q3. What is the difference between match() and search() in the re module? (K2, CO1, PO2)
Solution:
Example:
import re
Solution:
Exceptions are errors detected during execution that disrupt normal flow. Examples:
ZeroDivisionError, ValueError, FileNotFoundError.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
Q5. What is the purpose of the finally block in exception handling? (K2, CO1, PO2)
Solution:
The finally block always executes after try-except, regardless of whether an exception occurred.
Example:
try:
print(1 / 0)
except ZeroDivisionError:
print("Error")
finally:
Q6. What is the difference between raise and assert in Python? (K2, CO1, PO2)
Solution:
Example:
x = -1
Solution:
The try-except block handles runtime errors to prevent crashes.
Example:
try:
except ValueError:
print("Invalid input!")
Q8. Write a Python program to extract all email addresses from a given text using regex. (K3, CO2,
PO3)
Solution:
import re
Q9. Write a Python program to validate if a given phone number follows the pattern (XXX)-XXX-
XXXX. (K3, CO2, PO3)
Solution:
import re
def validate_phone(number):
pattern = r"\(\d{3}\)-\d{3}-\d{4}"
Q10. Explain the working of findall(), sub(), and split() in regex with examples. (K3, CO2, PO3)
Solution:
Example:
import re
Q11. Write a Python program to handle multiple exceptions. (K4, CO2, PO4)
Solution:
try:
print(10 / x)
except ZeroDivisionError:
except ValueError:
print("Invalid input!")
Q12. How does Python handle user-defined exceptions? Write a program for the same. (K4, CO2,
PO4)
Solution:
Python allows users to define custom exceptions using a class.
Example:
class NegativeValueError(Exception):
pass
def check_value(num):
if num < 0:
try:
check_value(-5)
except NegativeValueError as e:
Q13. What is exception chaining in Python? Give an example. (K5, CO2, PO5)
Solution:
Exception chaining links one exception to another using raise from.
Example:
try:
except ValueError as e:
Q14. Explain the role of logging in exception handling. Write a Python program to log exceptions to
a file. (K5, CO2, PO5)
Solution:
Logging allows errors to be recorded for debugging.
Example:
import logging
logging.basicConfig(filename="errors.log", level=logging.ERROR)
try:
print(1 / 0)
except ZeroDivisionError as e:
Q15. Compare checked and unchecked exceptions in Python. (K6, CO2, PO6)
Solution:
Example:
# Checked Exception
try:
with open("file.txt") as f:
print(f.read())
except FileNotFoundError:
# Unchecked Exception
print(10 / 0) # ZeroDivisionError
(Includes Short & Long Questions with Solutions, Based on Bloom’s Taxonomy, COs, and POs)
Solution:
A database connection allows Python to interact with databases (e.g., MySQL, SQLite). The sqlite3
and mysql.connector modules are commonly used.
Example:
import sqlite3
print("Connected successfully!")
conn.close()
Q2. What is SQL Injection, and how can it be prevented? (K1, CO1, PO1)
Solution:
SQL Injection is a security vulnerability where attackers inject malicious SQL queries into input fields.
It can be prevented using parameterized queries.
Example (Unsafe Query – Vulnerable to SQL Injection):
Solution:
Multithreading allows multiple tasks to run concurrently within a single process.
Example:
import threading
def print_hello():
thread = threading.Thread(target=print_hello)
thread.start()
thread.join()
Q4. Explain the difference between Threading and Multiprocessing. (K2, CO2, PO2)
Solution:
Example Use Web Scraping, File I/O Image Processing, Data Analysis
Q5. What is the difference between synchronous and asynchronous programming? (K2, CO2, PO2)
Solution:
Example (Synchronous):
def task1():
print("Task 1 completed")
def task2():
print("Task 2 completed")
task1()
task2()
Example (Asynchronous):
import asyncio
print("Task 1 completed")
print("Task 2 completed")
asyncio.run(task1())
asyncio.run(task2())
Q6. Write a Python program to connect to a MySQL database and retrieve data from a table. (K3,
CO3, PO3)
Solution:
import mysql.connector
cursor = conn.cursor()
print(row)
conn.close()
Q7. How can we create and search a table in an SQLite database using Python? (K3, CO3, PO3)
Solution:
import sqlite3
conn = sqlite3.connect("company.db")
cursor = conn.cursor()
# Create Table
cursor.execute('''CREATE TABLE IF NOT EXISTS employees (id INTEGER PRIMARY KEY, name TEXT,
salary REAL)''')
# Insert Data
conn.commit()
# Search Data
print(cursor.fetchone())
conn.close()
Q8. What is database normalization? Explain its advantages. (K4, CO3, PO4)
Solution:
Database normalization organizes a database to reduce redundancy and improve data integrity.
Advantages:
1 HR New York
ID Name Dept_ID
1 John 1
2 Alice 1
Q9. Write a Python program to perform multithreading for running two functions simultaneously.
(K4, CO4, PO4)
Solution:
import threading
def task1():
for _ in range(5):
print("Task 1 running")
def task2():
for _ in range(5):
print("Task 2 running")
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t1.start()
t2.start()
t1.join()
t2.join()
Q10. Explain how thread synchronization works in Python. (K4, CO4, PO4)
Solution:
Thread synchronization ensures only one thread accesses a shared resource at a time using Locks.
Example:
import threading
lock = threading.Lock()
balance = 100
def withdraw(amount):
global balance
lock.acquire()
try:
balance -= amount
else:
print("Insufficient balance")
finally:
lock.release()
t1 = threading.Thread(target=withdraw, args=(50,))
t2 = threading.Thread(target=withdraw, args=(70,))
t1.start()
t2.start()
t1.join()
t2.join()
Q11. What is deadlock in multithreading? How can it be prevented? (K5, CO4, PO5)
Solution:
Deadlock occurs when two or more threads wait for each other indefinitely.
Prevention Methods:
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
def task1():
lock1.acquire()
def task2():
lock2.acquire()
lock1.acquire()
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t1.start()
t2.start()
t1.join()
t2.join()
Q12. What is the Global Interpreter Lock (GIL), and how does it affect multithreading in Python?
(K6, CO4, PO6)
Solution:
The Global Interpreter Lock (GIL) allows only one thread to execute Python bytecode at a time,
limiting true parallel execution.
Impact: