1
MCA 2nd SEM PYTHON PROGRAMMING PAPER 2023
PART - A
1. State any four applications where python is more popular.
1. Web Development 🌐
🔹 Why? Python has powerful frameworks like Django, Flask, and FastAPI that
make web development easier.
🔹 Examples:
Instagram (built using Django)
Reddit (originally written in Python)
Spotify (backend services use Python)
2. Data Science & Machine Learning 📊🤖
🔹 Why? Python has libraries like NumPy, Pandas, Matplotlib, TensorFlow, and
Scikit-learn, making it ideal for data analysis and AI.
🔹 Examples:
Predicting stock prices
Image recognition (Face ID, object detection)
Chatbots and voice assistants (Siri, Alexa)
3. Automation & Scripting ⚙️
🔹 Why? Python is used for writing scripts to automate repetitive tasks like file
handling, data extraction, and testing.
🔹 Examples:
Automating emails & reports
2
Web scraping with BeautifulSoup & Selenium
Automating Excel tasks using openpyxl & pandas
4. Cybersecurity & Ethical Hacking 🔒
🔹 Why? Python is used in cybersecurity for penetration testing, malware
analysis, and network security.
🔹 Examples:
Writing penetration testing tools (Scapy, Nmap)
Password cracking scripts
Analyzing malware behavior
Other Popular Applications:
✔ Game Development (Pygame, Panda3D) 🎮
✔ Internet of Things (IoT) (MicroPython, Raspberry Pi) 🌍
✔ Scientific Computing (SciPy, SymPy) 🔬
✔ Blockchain & Cryptography 🔗
2. What are the uses of file object?
3
Common Uses of File Objects:
1. Reading Files ('r' mode) 📖
Used to read data from a file.
file = open("example.txt", "r") # Open file in
read mode
content = file.read() # Read full file content
print(content)
file.close()
✅ Methods: read(), readline(), readlines()
2. Writing to Files ('w' or 'a' mode) ✍️
Used to write or append data to a file.
file = open("example.txt", "w") # Open file in
write mode
file.write("Hello, Python!") # Write data
file.close()
✅ Modes:
'w' → Overwrites the file
'a' → Appends to the file
4
3. Working with Binary Files ('rb', 'wb') 📂
Used for images, videos, PDFs, etc.
file = open("image.jpg", "rb") # Open file in
binary read mode
data = file.read()
file.close()
4. Using File Objects with with Statement (Auto-close) 🚀
with open("example.txt", "r") as file:
content = file.read()
print(content) # File closes automatically
after exiting the block
✅ No need to call file.close() manually.
5. Iterating Over File Lines 📜
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # Read line by line
3. State the basic functionality of match () function.
5
Basic Functionality of match() Function in Python 🔍
The match() function in Python is provided by the re (regular expressions)
module. It is used to check if a string starts with a specific pattern.
Syntax:
import re
result = re.match(pattern, string)
pattern: The regular expression to match.
string: The input string to check.
result: Returns a match object if the pattern is found at the beginning of
the string, otherwise None.
Example 1: Matching a Word at the Start of a String
import re
text = "Hello, World!"
pattern = r"Hello"
match = re.match(pattern, text)
if match:
print("Match found:", match.group()) # Output:
Match found: Hello
else:
print("No match")
Example 2: Matching a Number at the Start of a String
import re
6
text = "123abc"
pattern = r"\d+" # Matches one or more digits at the
beginning
match = re.match(pattern, text)
if match:
print("Matched:", match.group()) # Output:
Matched: 123
else:
print("No match")
Key Features of match()
✔ Only checks the beginning of the string.
✔ Returns a match object if successful, otherwise None.
✔ Use .group() to extract the matched part.
✔ If the pattern is not at the start, match() returns None.
Difference Between match() and search()
re.match(pattern, string) → Only matches at the beginning of
the string.
re.search(pattern, string) → Searches anywhere in the string.
4. What is Assertions?
Assertions in Python (assert Statement) 🚀
7
Assertion is a way to add debugging checks in Python. It is used to test
assumptions about the program while it is running.
Syntax of assert Statement
python
CopyEdit
assert condition, "Optional error message"
condition: The expression that should be True. If False, an
AssertionError is raised.
"Optional error message": (Optional) A message to
display if the assertion fails.
Example 1: Basic Assertion
python
CopyEdit
x = 10
assert x > 5 # ✅ Passes, as 10 > 5
Example 2: Failing Assertion with Error Message
python
CopyEdit
x = 2
assert x > 5, "x is not greater than 5" # ❌
Fails, raises AssertionError
💥 Output:
vbnet
CopyEdit
8
Traceback (most recent call last):
File "script.py", line 2, in <module>
assert x > 5, "x is not greater than 5"
AssertionError: x is not greater than 5
Why Use Assertions?
✔ Helps in debugging by catching errors early.
✔ Ensures correctness by validating inputs or results.
✔ Used for unit testing in Python.
5. What is Pass statement?
Pass Statement in Python (pass) 🚀
The pass statement in Python is a placeholder that allows the program
to run without doing anything. It is used when a statement is
syntactically required but no action is needed.
Syntax:
pass
When to Use pass?
1. Empty Functions (To be implemented later)
9
python
CopyEdit
def future_function():
pass # Placeholder for future code
2. Empty Class Definitions
class MyClass:
pass # Placeholder for class body
3. Empty Loops (For Future Code)
for i in range(5):
pass # No action yet
4. Empty Conditional Statements
x = 10
if x > 5:
pass # No action, but avoids syntax errors
Key Features of pass:
✔ Prevents syntax errors in empty blocks.
✔ Acts as a temporary placeholder for future code.
✔ Does nothing when executed.
Difference Between pass and Other Statements
Statement Purpose
pass Does nothing; used as a placeholder.
continue Skips the rest of the loop iteration and moves to the next
10
Statement Purpose
iteration.
break Exits the loop completely.
6. What is Command Line Argument?
Command Line Arguments in Python 🖥️
A command-line argument is an input passed to a Python script when it is
executed from the terminal or command prompt.
How to Pass Command Line Arguments?
When running a Python script, arguments are given after the script name in the
terminal.
Example:
sh
CopyEdit
python script.py arg1 arg2 arg3
Here, arg1, arg2, and arg3 are command-line arguments passed to
script.py.
Accessing Command Line Arguments in Python
Python provides the sys module to work with command-line arguments.
Example: Using sys.argv
python
CopyEdit
11
import sys
print("Script Name:", sys.argv[0]) # First argument is
always the script name
print("First Argument:", sys.argv[1])
print("Second Argument:", sys.argv[2])
✅ Run the script in the terminal:
sh
CopyEdit
python script.py hello world
✅ Output:
yaml
CopyEdit
Script Name: script.py
First Argument: hello
Second Argument: world
Key Points About sys.argv
✔ sys.argv is a list where:
sys.argv[0] → Always the script name.
sys.argv[1], sys.argv[2], etc. → Actual arguments. ✔ Arguments
are treated as strings. ✔ Accessing an index that doesn’t exist will raise an
IndexError.
7. What do you understand by Polymorphism?
Polymorphism in Python 🐍
12
Polymorphism means "many forms." It allows objects of different
classes to be treated as objects of a common superclass. It enables the
same method or operator to behave differently based on the object
type.
Types of Polymorphism in Python
1. Method Overriding (Runtime Polymorphism) 🎭
When a subclass redefines a method from its parent class.
Example: Overriding in Inheritance
class Animal:
def sound(self):
print("Animals make sounds")
class Dog(Animal):
def sound(self): # Overriding the parent
method
print("Dog barks")
class Cat(Animal):
def sound(self):
print("Cat meows")
# Polymorphism in action
animals = [Dog(), Cat()]
for animal in animals:
animal.sound()
✅ Output:
Dog barks
13
Cat meows
8. What is String-Only Operators?
String-Only Operators in Python 🔤
Python provides some operators that are specifically designed for strings and do
not work with other data types. These are called string-only operators.
1. Concatenation Operator (+) ➕
Joins two or more strings together.
Only works with strings, not numbers or other data types.
Example:
str1 = "Hello"
str2 = " World"
result = str1 + str2
print(result) # Output: Hello World
🚨 Incorrect Usage (TypeError):
print("Age: " + 25) # ❌ TypeError: can only
concatenate str (not "int") to str
✅ Correct Way:
print("Age: " + str(25)) # ✅ Output: Age: 25
2. Repetition Operator (*) ✖️
Repeats a string multiple times.
14
Right operand must be an integer.
Example:
word = "Hello "
result = word * 3
print(result) # Output: Hello Hello Hello
🚨 Incorrect Usage (TypeError):
print("Hello" * "2") # ❌ TypeError: can't multiply
sequence by non-int
✅ Correct Way:
print("Hello" * 2) # ✅ Output: HelloHello
3. Membership Operators (in and not in) 🔍
Checks if a substring exists within a string.
Example:
text = "Python is amazing"
print("Python" in text) # ✅ True
print("java" in text) # ❌ False
print("amazing" not in text) # ❌ False
4. String Comparison Operators (==, !=, <, >, <=, >=)
Compare strings based on lexicographical (dictionary) order.
Example:
print("apple" == "apple") # ✅ True
print("apple" != "orange") # ✅ True
print("apple" < "banana") # ✅ True (because 'a' < 'b'
in ASCII)
print("hello" > "Hello") # ✅ True ('h' has a higher
ASCII value than 'H')
15
Summary Table 📋
Operator Description Example Output
"Hello
+ Concatenation "Hello" + " World"
World"
"Hello
* Repetition "Hello " * 3 Hello
Hello "
in Membership Check "Py" in "Python" True
Non-Membership "Java" not in
not in True
Check "Python"
== Equality "abc" == "abc" True
!= Inequality "abc" != "xyz" True
<, >, <=, Lexicographical
"apple" < "banana" True
>= Comparison
9. What are Exceptions?
Exceptions in Python 🚨
An exception in Python is an error that occurs during program
execution that disrupts the normal flow of instructions. Instead of
crashing the program immediately, Python allows us to handle
exceptions using try-except blocks.
16
Types of Errors in Python
1. Syntax Errors (Compilation Errors) 🚫
These occur when the code has incorrect syntax and prevents
execution.
Example:
print("Hello" # Missing closing parenthesis
✅ Python will give a SyntaxError:
SyntaxError: unexpected EOF while parsing
2. Exceptions (Runtime Errors) ⚡
These occur during program execution and can be handled using
try-except.
Example:
x = 10 / 0 # Division by zero
✅ Python raises:
ZeroDivisionError: division by zero
Common Built-in Exceptions in Python
Exception Cause
ZeroDivisionError Division by zero (10/0)
TypeError Invalid operation between different types
17
Exception Cause
("5" + 5)
Invalid argument for a function
ValueError
(int("abc"))
IndexError Accessing an out-of-range index (list[10])
Accessing a non-existent dictionary key
KeyError
(dict["xyz"])
FileNotFoundError File does not exist (open("abc.txt"))
NameError Using an undefined variable (print(xyz))
Accessing an invalid attribute
AttributeError
(None.some_method())
Handling Exceptions in Python
1. Using try-except 🛠️
try:
result = 10 / 0 # Error
except ZeroDivisionError:
print("Cannot divide by zero!")
✅ Output:
Cannot divide by zero!
2. Handling Multiple Exceptions
try:
18
x = int("abc") # ValueError
except (ZeroDivisionError, ValueError) as e:
print(f"Error Occurred: {e}")
✅ Output:
Error Occurred: invalid literal for int() with
base 10: 'abc'
10. What do you understand by class variables?
Class Variables in Python 🏛️
A class variable is a variable that is shared among all instances of a
class. It is defined inside the class but outside any instance methods
and has the same value for all objects unless explicitly changed.
1. Characteristics of Class Variables
✅ Shared across all instances – Unlike instance variables, they are not
unique to each object.
✅ Declared within the class (not inside methods).
✅ Modified at the class level (affects all instances).
✅ Can be accessed using ClassName.variable_name or
self.variable_name.
2. Example of a Class Variable
class Car:
wheels = 4 # Class variable (shared by all
instances)
def __init__(self, brand, color):
19
self.brand = brand # Instance variable
self.color = color # Instance variable
# Creating objects
car1 = Car("Toyota", "Red")
car2 = Car("Honda", "Blue")
print(car1.wheels) # Output: 4
print(car2.wheels) # Output: 4
🔹 Both car1 and car2 have wheels = 4 because it's a class
variable.
Difference Between Class and Instance Variables
Instance Variable (brand,
Feature Class Variable (wheels)
color)
Defined in Inside class, outside methods Inside __init__ method
Shared by All objects Unique to each object
Accessed ClassName.var or
self.var
by self.var
Modified ClassName.var = self.var =
by new_value new_value
Example Car.wheels = 4 self.color = "Red"
When to Use Class Variables?
✔️When the value is common across all instances (e.g., wheels in a
car).
20
✔️To store constant values like a default setting.
✔️For tracking shared information, like counting objects.
PART – B
1. Explain the Identifiers, Keywords, Statements, Expressions, and
Variables in Python Programming language with examples.
Identifiers, Keywords, Statements, Expressions, and
Variables in Python
Python is a high-level programming language that follows a structured
and readable syntax. Here’s an explanation of some fundamental
concepts:
1. Identifiers
An identifier is the name used to identify variables, functions, classes,
modules, and objects.
Rules for Identifiers
✔️Can contain letters (A-Z, a-z), digits (0-9), and underscores (_)
only.
✔️Cannot start with a digit (e.g., 2name ❌ is invalid).
✔️Cannot use Python keywords (e.g., class = 5 ❌ is invalid).
✔️Case-sensitive (myVar and myvar are different).
Examples of Identifiers
21
name = "Alice" # Valid identifier
_age = 25 # Valid (underscore allowed)
totalAmount = 1000 # Valid (camel case)
2days = "Monday" # Invalid (cannot start with
a digit)
class = "Python" # Invalid (keyword used)
2. Keywords
Python keywords are reserved words that have a special meaning and
cannot be used as identifiers.
Examples of Python Keywords
import keyword
print(keyword.kwlist) # List of all Python
keywords
✅ Output:
python
CopyEdit
['False', 'None', 'True', 'and', 'as', 'assert',
'async', 'await',
'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
🚨 Example of Incorrect Keyword Usage:
if = 10 # ❌ SyntaxError: invalid syntax
22
3. Statements
A statement is a single line of code that performs an action.
Types of Statements
1. Assignment Statement
x = 10 # Assigning 10 to x
2. Conditional Statement
if x > 5:
print("x is greater than 5")
3. Loop Statement
for i in range(3):
print(i)
4. Expressions
An expression is a combination of variables, operators, and values that
produces a single result.
Examples of Expressions
x = 10 + 5 # Expression (evaluates to 15)
y = x * 2 # Expression (evaluates to 30)
print(y > 20) # Expression (evaluates to True)
✔ Expressions return a value, whereas statements perform an action.
5. Variables
A variable is a named storage in memory that holds a value.
23
Rules for Variables
✔ A variable name must start with a letter or an underscore (_).
✔ It cannot be a keyword.
✔ It can store different types of data (int, float, string, list, etc.).
Examples of Variables
name = "John" # String
age = 25 # Integer
salary = 5000.50 # Float
is_active = True # Boolean
2. Discuss the relation between tuples and lists, tuples and
dictionaries in detail.
Relation Between Tuples and Lists, Tuples and
Dictionaries in Python
1. Tuples vs. Lists
Both tuples and lists are sequence data types in Python that store
collections of items. However, they have some key differences.
Similarities Between Tuples and Lists
✔ Ordered – Both maintain the order of elements.
✔ Allow duplicates – Both can contain repeated values.
✔ Support indexing and slicing – You can access elements using
indexing and retrieve sublists/sublists using slicing.
24
✔ Can store multiple data types – Both can contain elements of
different data types (int, float, string, etc.).
Differences Between Tuples and Lists
Feature Tuples (tuple) Lists (list)
Immutable (Cannot Mutable (Can add, remove,
Mutability
change after creation) or modify elements)
Defined using Defined using square
Syntax
parentheses ( ) brackets [ ]
Faster due to Slower because of
Performance
immutability mutability
Used when data should Used when data can
Use Case
not change change
Memory Usage Takes less memory Takes more memory
Operations No insert, delete, or Can insert, delete, and
Allowed modify operations modify elements
Example of Tuple vs. List
# List (Mutable)
my_list = [1, 2, 3]
my_list.append(4) # ✅ Allowed
my_list[0] = 100 # ✅ Allowed
print(my_list) # Output: [100, 2, 3, 4]
# Tuple (Immutable)
my_tuple = (1, 2, 3)
# my_tuple[0] = 100 ❌ Not Allowed (TypeError)
25
# my_tuple.append(4) ❌ Not Allowed
(AttributeError)
print(my_tuple) # Output: (1, 2, 3)
When to Use Tuples Over Lists?
✅ When the data should not change, such as database records or fixed
configurations.
✅ When performance matters, as tuples are faster.
✅ When you want to use a dictionary key, since tuples are hashable
and lists are not.
2. Tuples vs. Dictionaries
Tuples and dictionaries are fundamentally different because:
Tuples are ordered collections, while dictionaries are unordered
key-value pairs.
Tuples store individual values, whereas dictionaries store key-
value pairs.
Similarities Between Tuples and Dictionaries
✔ Both can store heterogeneous data types (int, float, string, etc.).
✔ Both can be used as elements in another tuple or list.
✔ Both support iteration using loops.
Differences Between Tuples and Dictionaries
Feature Tuples (tuple) Dictionaries (dict)
Unordered collection of
Data Structure Ordered sequence
key-value pairs
Accessing Access by index Access by key
26
Feature Tuples (tuple) Dictionaries (dict)
Elements
Mutable (Can add,
Immutable (Cannot change
Mutability remove, or update key-
elements)
value pairs)
Syntax Defined using ( ) Defined using { }
Optimized for fast
Performance Faster for storing fixed data
lookup
{'name':
Example (1, 2, 3) 'Alice', 'age':
25}
Example of Tuple vs. Dictionary
# Tuple (Ordered, Immutable)
my_tuple = (10, 20, 30)
print(my_tuple[0]) # Output: 10
# Dictionary (Key-Value Pairs, Mutable)
my_dict = {"name": "Alice", "age": 25}
print(my_dict["name"]) # Output: Alice
my_dict["age"] = 30 # ✅ Allowed (modifying
dictionary)
When to Use Tuples Over Dictionaries?
✅ When storing a collection of values without labels (e.g.,
(latitude, longitude)).
✅ When you need to store immutable data.
✅ When using it as a dictionary key, since dictionaries require
hashable keys (lists are not hashable, but tuples are).
27
3. Explain File Built - in function and File Built-in Methods in detail.
File Built-in Functions and File Built-in Methods in Python
1. File Built-in Functions
Python provides several built-in functions to work with files. The
primary function used for file handling is the open() function.
open() Function
The open() function is used to open a file and returns a file object.
Syntax
file_object = open(file_name, mode)
file_name: Name of the file to open (e.g., "data.txt").
mode: The mode in which to open the file.
Modes for Opening a File
Mode Meaning
Read (default mode) – Opens the file for reading; error if file
'r'
doesn’t exist.
Write – Opens the file for writing; creates the file if it doesn’t
'w'
exist, overwrites if it does.
Append – Opens the file for writing; creates if not exists, adds
'a'
data at the end if exists.
'x' Exclusive Creation – Creates a file; error if file already exists.
'b' Binary Mode – Opens file in binary mode (e.g., images, videos).
28
Mode Meaning
't' Text Mode (default) – Opens file in text mode.
'r+' Read and Write – Allows both reading and writing.
'w+' Write and Read – Overwrites the file and allows reading.
'a+' Append and Read – Opens file for appending and reading.
Example
file = open("example.txt", "w") # Opens a file
in write mode
file.write("Hello, Python!") # Writes to the
file
file.close() # Closes the file
2. File Built-in Methods
Once a file is opened, you can use different file methods to read, write,
and manipulate files.
1. read() – Read the entire content
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
✔ Reads entire file content as a string.
2. readline() – Read one line at a time
file = open("example.txt", "r")
line = file.readline()
print(line) # Reads only the first line
29
file.close()
✔ Reads one line at a time.
3. readlines() – Read all lines into a list
file = open("example.txt", "r")
lines = file.readlines()
print(lines) # Output: ['Hello, Python!\n',
'Welcome to file handling.\n']
file.close()
✔ Returns a list where each line is an element.
4. write() – Write to a file
file = open("example.txt", "w")
file.write("This is a new line.")
file.close()
✔ Overwrites the file with the new content.
5. writelines() – Write multiple lines
file = open("example.txt", "w")
file.writelines(["Hello\n", "Python\n", "File
Handling\n"])
file.close()
✔ Writes multiple lines to the file.
6. append() – Append data to an existing file
file = open("example.txt", "a")
file.write("\nAppending this line.")
file.close()
30
✔ Adds content at the end of the file without deleting existing content.
7. tell() – Get the current cursor position
file = open("example.txt", "r")
print(file.tell()) # Output: 0 (Start of the
file)
file.read(5)
print(file.tell()) # Output: 5 (After reading 5
characters)
file.close()
✔ Returns the current position of the file pointer.
8. seek() – Move the file pointer to a specific position
file = open("example.txt", "r")
file.seek(7) # Move to the 7th byte in the file
print(file.read()) # Reads from the new position
file.close()
✔ Used to reposition the cursor in a file.
9. flush() – Force write buffer to disk
file = open("example.txt", "w")
file.write("Some text")
file.flush() # Forces the file to be written to
disk immediately
file.close()
✔ Ensures data is written to the file immediately without waiting for
close.
10. close() – Close the file
file = open("example.txt", "r")
31
file.close() # Closes the file and frees system
resources
✔ Always close a file to prevent data loss or corruption.
4. Discuss the SQL commands/statements used for creating, using and
dropping a database.
Managing SQL Databases in Python using MySQL and
SQLite
Python allows interaction with SQL databases using libraries such as
MySQL Connector (for MySQL) and SQLite (for lightweight
databases). The key SQL commands for creating, using, and dropping
databases can be executed using Python.
1. Using MySQL with Python (mysql-connector-python)
To manage MySQL databases in Python, install the required package if
not already installed:
pip install mysql-connector-python
(A) Creating a Database in MySQL
32
import mysql.connector
# Connect to MySQL Server (without specifying a
database)
conn = mysql.connector.connect(
host="localhost",
user="root",
password="yourpassword"
)
cursor = conn.cursor()
# Create a database
cursor.execute("CREATE DATABASE SchoolDB")
# Show databases
cursor.execute("SHOW DATABASES")
for db in cursor:
print(db)
# Close connection
cursor.close()
conn.close()
✔ This connects to MySQL, creates a database named SchoolDB,
and displays all available databases.
(B) Using a Database
After creating a database, you need to select it before creating tables and
inserting data.
conn = mysql.connector.connect(
33
host="localhost",
user="root",
password="yourpassword",
database="SchoolDB" # Selecting the
database
)
cursor = conn.cursor()
cursor.execute("USE SchoolDB") # Optional, as
the database is already selected
print("Database in use: SchoolDB")
cursor.close()
conn.close()
✔ This connects to SchoolDB and sets it as the active database.
(C) Dropping a Database in MySQL
To delete a database using Python:
conn = mysql.connector.connect(
host="localhost",
user="root",
password="yourpassword"
)
cursor = conn.cursor()
# Drop database if it exists
cursor.execute("DROP DATABASE IF EXISTS
SchoolDB")
34
print("Database SchoolDB dropped successfully.")
cursor.close()
conn.close()
✔ This removes the SchoolDB database permanently.
2. Using SQLite with Python (sqlite3)
For local applications, SQLite is an excellent choice since it does not
require a separate server.
SQLite is built into Python, so no installation is required.
(A) Creating an SQLite Database
import sqlite3
# Connect to SQLite (Creates database if it
doesn't exist)
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
print("Database created successfully.")
cursor.close()
conn.close()
✔ SQLite creates a file-based database (school.db) automatically.
(B) Using an SQLite Database
35
Unlike MySQL, in SQLite, once the database file is created, you can
immediately execute commands.
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
# Creating a table inside the database
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
""")
print("Table created successfully.")
cursor.close()
conn.close()
✔ This creates a students table inside school.db.
(C) Dropping an SQLite Database
Unlike MySQL, you cannot drop an entire SQLite database using
SQL commands. Instead, you delete the database file manually:
import os
db_file = "school.db"
if os.path.exists(db_file):
os.remove(db_file)
print("Database deleted successfully.")
else:
36
print("Database file does not exist.")
✔ This removes the school.db file, deleting the database.
5. Explain the process of creating and searching tables in Python.
Creating and Searching Tables in Python using SQL
Python allows interaction with databases like MySQL and SQLite to
create and search tables efficiently. Below, I’ll explain how to create
tables and search data using both MySQL (mysql-connector-
python) and SQLite (sqlite3).
1. Using MySQL (mysql-connector-python)
To interact with MySQL, install the required package (if not already
installed):
pip install mysql-connector-python
(A) Creating a Table in MySQL
import mysql.connector
37
# Connect to MySQL Server and use a database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="yourpassword",
database="SchoolDB"
)
cursor = conn.cursor()
# Create a table named 'students'
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT,
grade VARCHAR(10)
)
""")
print("Table 'students' created successfully.")
cursor.close()
conn.close()
✔ This creates a students table with columns id, name, age, and
grade.
(B) Inserting Data into MySQL Table
conn = mysql.connector.connect(
host="localhost",
38
user="root",
password="yourpassword",
database="SchoolDB"
)
cursor = conn.cursor()
# Insert a record
cursor.execute("INSERT INTO students (name, age,
grade) VALUES (%s, %s, %s)", ("Alice", 20, "A"))
conn.commit()
print("Data inserted successfully.")
cursor.close()
conn.close()
✔ This adds a student record (Alice, 20, A) into the students
table.
(C) Searching Data in MySQL Table
conn = mysql.connector.connect(
host="localhost",
user="root",
password="yourpassword",
database="SchoolDB"
)
cursor = conn.cursor()
# Search for students with grade 'A'
39
cursor.execute("SELECT * FROM students WHERE
grade = 'A'")
# Fetch and display results
for row in cursor.fetchall():
print(row)
cursor.close()
conn.close()
✔ This retrieves and prints all students with grade 'A'.
2. Using SQLite (sqlite3)
SQLite is built into Python, so no installation is required.
(A) Creating a Table in SQLite
import sqlite3
# Connect to SQLite database (creates file if it
doesn't exist)
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
# Create table 'students'
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
age INTEGER,
grade TEXT
)
""")
40
print("Table 'students' created successfully.")
cursor.close()
conn.close()
✔ This creates a students table in an SQLite database
(school.db).
(B) Inserting Data into SQLite Table
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
# Insert a record
cursor.execute("INSERT INTO students (name, age,
grade) VALUES (?, ?, ?)", ("Alice", 20, "A"))
conn.commit()
print("Data inserted successfully.")
cursor.close()
conn.close()
✔ This adds a student record (Alice, 20, A) into SQLite.
(C) Searching Data in SQLite Table
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
41
# Search for students with grade 'A'
cursor.execute("SELECT * FROM students WHERE
grade = 'A'")
# Fetch and display results
for row in cursor.fetchall():
print(row)
cursor.close()
conn.close()
✔ This retrieves and prints all students with grade 'A' from SQLite.
PART – C
1. Explain While loop, Break statement and Continue statement in
python with example.
Loops and Control Statements in Python
Python provides looping constructs like the while loop and control
statements like break and continue to manage program flow
effectively. Let's explore them one by one with examples.
1. while Loop in Python
The while loop is used to execute a block of code repeatedly as long
as the given condition is True.
42
Syntax:
while condition:
# Code block to execute
Example: Printing numbers from 1 to 5
i = 1 # Initialization
while i <= 5: # Condition
print(i)
i += 1 # Increment
Output:
1
2
3
4
5
✔ The loop runs **as long as i is ≤ 5**, increasing i` each time.
2. break Statement in Python
The break statement is used to exit a loop prematurely when a certain
condition is met.
Example: Breaking a loop when i == 3
i = 1
while i <= 5:
if i == 3:
print("Loop terminated at", i)
43
break # Stops loop execution
print(i)
i += 1
Output:
1
2
Loop terminated at 3
✔ The loop stops when i == 3.
3. continue Statement in Python
The continue statement skips the current iteration and moves to the
next iteration of the loop.
Example: Skipping number 3 in the loop
i = 0
while i < 5:
i += 1
if i == 3:
print("Skipping", i)
continue # Skips the rest of the loop
body for this iteration
print(i)
Output:
1
2
Skipping 3
4
44
✔ When i == 3, the continue statement skips printing 3 and
moves to the next iteration.
2. Write a program to concatenate the content of two files into a
single file.
Here's a Python program that reads the content of two files and writes
them into a new file by concatenating their contents.
Program to Concatenate Two Files
# Function to concatenate two files
def concatenate_files(file1, file2,
output_file):
try:
# Open the first file in read mode
with open(file1, 'r') as f1:
content1 = f1.read()
# Open the second file in read mode
with open(file2, 'r') as f2:
content2 = f2.read()
# Write both contents into the output file
with open(output_file, 'w') as out:
out.write(content1 + "\n") # Adding
newline for separation
out.write(content2)
45
print(f"Files '{file1}' and '{file2}' have been
concatenated into '{output_file}'.")
except FileNotFoundError:
print("One or more files not found.
Please check the filenames and try again.")
except Exception as e:
print(f"An error occurred: {e}")
# Provide filenames
file1 = "file1.txt" # First input file
file2 = "file2.txt" # Second input file
output_file = "output.txt" # Output file
# Call function to concatenate files
concatenate_files(file1, file2, output_file)
How the Program Works
1. Opens both input files (file1.txt, file2.txt) in read
mode and reads their content.
2. Creates a new file (output.txt) and writes the combined
content.
3. Handles errors if files are missing.
Example Input
file1.txt
Hello, this is the first file.
file2.txt
And this is the second file.
46
Output in output.txt
Hello, this is the first file.
And this is the second file.
Would you like modifications, such as appending to an existing file
instead of overwriting? 😊
3. What are Exceptions? Explain detecting and handling exceptions in
Python.
Exceptions in Python
What are Exceptions?
Exceptions are runtime errors that occur during program execution,
causing it to stop unexpectedly. They happen when Python encounters
an unexpected situation, such as:
Dividing by zero (ZeroDivisionError)
Accessing an undefined variable (NameError)
Performing an invalid operation (TypeError)
Example of an Exception
a = 10 / 0 # ZeroDivisionError
print(a)
✅ Output:
ZeroDivisionError: division by zero
47
✔ Since dividing by zero is not allowed, Python throws an exception
and stops execution.
Detecting and Handling Exceptions in Python
Python provides try-except blocks to handle exceptions gracefully and
prevent program crashes.
1. Basic Exception Handling (try-except)
try:
a = 10 / 0 # Risky operation
except ZeroDivisionError:
print("You cannot divide by zero!")
✅ Output:
You cannot divide by zero!
✔ The program does not crash and handles the error properly.
2. Handling Multiple Exceptions
You can handle multiple exception types separately.
try:
num = int("hello") # Invalid conversion
result = 10 / 0 # Division by zero
except ZeroDivisionError:
print("Error: Division by zero is not
allowed.")
except ValueError:
48
print("Error: Cannot convert string to
integer.")
✅ Output:
Error: Cannot convert string to integer.
✔ Only the first matching exception is executed.
3. Using except Exception to Catch Any Error
If you don't know the exact error, use Exception to catch all
exceptions.
try:
x = 10 / 0
except Exception as e:
print("An error occurred:", e)
✅ Output:
An error occurred: division by zero
✔ The error message is printed without crashing the program.
4. Using finally Block
The finally block always executes (even if an exception occurs).
49
try:
print(10 / 2) # No error
except ZeroDivisionError:
print("You cannot divide by zero.")
finally:
print("This will always run.")
✅ Output:
5.0
This will always run.
✔ The finally block executes no matter what.
5. Using else Block
The else block executes if no exception occurs.
try:
num = int("100") # No error
print("Conversion successful:", num)
except ValueError:
print("Invalid input!")
else:
print("No exception occurred!")
✅ Output:
Conversion successful: 100
No exception occurred!
✔ else executes since no exception occurred.
50
4. Explain the process of SQL database connection using Python in
detail and Explain multithreading in Python.
1. SQL Database Connection Using Python
Python provides sqlite3, MySQL Connector, and psycopg2 (for
PostgreSQL) modules to connect to databases. Below, we will explain
how to connect to a MySQL database using mysql-connector-
python.
Step-by-Step Process of SQL Database Connection Using
Python
Step 1: Install the Required Module
Ensure you have installed the mysql-connector-python package:
pip install mysql-connector-python
Step 2: Import the Required Library
import mysql.connector
Step 3: Establish a Connection to the Database
conn = mysql.connector.connect(
51
host="localhost", # Database server (or IP
address)
user="root", # Your MySQL username
password="password", # Your MySQL password
database="test_db" # Database name
)
print("Database connected successfully!")
✔ If the connection is successful, no error is raised.
✔ If credentials are incorrect, an error will be raised.
Step 4: Create a Cursor Object
A cursor allows us to execute SQL queries.
cursor = conn.cursor()
Step 5: Execute SQL Queries
Creating a Table
cursor.execute("CREATE TABLE students (id INT
AUTO_INCREMENT PRIMARY KEY, name VARCHAR(50),
age INT)")
print("Table created successfully!")
Inserting Data into Table
52
cursor.execute("INSERT INTO students (name, age)
VALUES ('Alice', 20)")
conn.commit() # Save changes
print("Data inserted successfully!")
Retrieving Data
cursor.execute("SELECT * FROM students")
for row in cursor.fetchall():
print(row) # Print each row
Step 6: Close the Connection
cursor.close()
conn.close()
print("Database connection closed.")
Complete Code for MySQL Connection in Python
import mysql.connector
try:
# Step 1: Establish connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="password",
database="test_db"
)
print("Database connected successfully!")
# Step 2: Create cursor
cursor = conn.cursor()
# Step 3: Execute queries
53
cursor.execute("SELECT * FROM students")
for row in cursor.fetchall():
print(row)
except mysql.connector.Error as e:
print("Error:", e)
finally:
# Step 4: Close connection
if 'cursor' in locals():
cursor.close()
if 'conn' in locals():
conn.close()
print("Database connection closed.")
✔ This ensures proper connection handling!
2. Multithreading in Python
Multithreading is a technique that allows multiple tasks to run
concurrently in a program.
Why Use Multithreading?
Improves performance for I/O-bound tasks (like downloading
files, database operations).
Helps in parallel execution.
Efficiently uses CPU resources.
Creating and Running a Thread in Python
Python provides the threading module for multithreading.
import threading
54
def print_numbers():
for i in range(1, 6):
print(f"Number: {i}")
# Creating a thread
thread = threading.Thread(target=print_numbers)
# Starting the thread
thread.start()
# Waiting for thread to complete
thread.join()
print("Main thread execution completed.")
✅ Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Main thread execution completed.
✔ The print_numbers function runs concurrently in a separate
thread.
Using Multiple Threads
import threading
def print_numbers():
for i in range(1, 6):
print(f"Number: {i}")
55
def print_letters():
for letter in "ABCDE":
print(f"Letter: {letter}")
# Creating two threads
thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_letters)
# Starting both threads
thread1.start()
thread2.start()
# Waiting for both threads to complete
thread1.join()
thread2.join()
print("Both threads have finished execution.")
✅ Output (order may vary due to concurrency):
Number: 1
Letter: A
Number: 2
Letter: B
Number: 3
Letter: C
Number: 4
Letter: D
Number: 5
Letter: E
Both threads have finished execution.
56
✔ The threads run in parallel, interleaving output.
Thread Synchronization (Avoiding Race Conditions)
When multiple threads access shared resources, conflicts may occur.
To prevent issues, use Locks (threading.Lock()).
import threading
lock = threading.Lock()
count = 0
def increment():
global count
for _ in range(100000):
with lock: # Locking ensures only one
thread modifies 'count' at a time
count += 1
# Creating two threads
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)
t1.start()
t2.start()
t1.join()
t2.join()
print("Final Count:", count)
✔ Locks prevent data corruption in multithreaded programs.
57
Key Differences: Single Thread vs Multithreading
Feature Single Thread Multithreading
Execution Sequential Parallel
Performance Slower (for I/O tasks) Faster
Resource Utilization Low High
Needs
Data Safety No conflicts
synchronization
5. Explain Python data types and local and global scope of variable in
Python by taking suitable examples.
Python Data Types & Variable Scope (Local & Global)
Python provides various data types and defines variable scope to
determine where a variable can be accessed. Let's explore both topics in
detail.
1. Python Data Types
Python has several built-in data types, categorized as follows:
A. Numeric Data Types
58
Data Type Description Example
int Whole numbers a = 10
float Decimal numbers b = 3.14
complex Complex numbers c = 2 + 3j
🔹 Example:
x = 5 # Integer
y = 3.14 # Float
z = 2 + 3j # Complex number
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'complex'>
B. Sequence Data Types
Data Type Description Example
str Text (immutable) s = "Hello"
list Ordered, mutable collection l = [1, 2, 3]
tuple Ordered, immutable collection t = (1, 2, 3)
🔹 Example:
s = "Hello"
l = [1, 2, 3]
t = (1, 2, 3)
print(type(s)) # <class 'str'>
59
print(type(l)) # <class 'list'>
print(type(t)) # <class 'tuple'>
C. Set Data Types
Data Type Description Example
Unordered, unique
set s = {1, 2, 3}
elements
fs = frozenset([1, 2,
frozenset Immutable set
3])
🔹 Example:
s = {1, 2, 3}
fs = frozenset([1, 2, 3])
print(type(s)) # <class 'set'>
print(type(fs)) # <class 'frozenset'>
D. Mapping Data Type
Data Type Description Example
d = {"name": "Alice", "age":
dict Key-value pairs
25}
🔹 Example:
d = {"name": "Alice", "age": 25}
print(type(d)) # <class 'dict'>
E. Boolean & None Types
60
Data Type Description Example
bool True or False b = True
NoneType Represents no value n = None
🔹 Example:
b = True
n = None
print(type(b)) # <class 'bool'>
print(type(n)) # <class 'NoneType'>
2. Local and Global Scope of Variables in Python
A variable's scope determines where it can be accessed.
A. Local Scope
A local variable is declared inside a function.
It cannot be accessed outside the function.
🔹 Example:
def my_function():
x = 10 # Local variable
print("Inside function:", x)
my_function()
# print(x) # This will cause an error (x is not
defined globally)
✅ Output:
61
Inside function: 10
🚫 Error if we try to print x outside the function.
B. Global Scope
A global variable is declared outside any function.
It can be accessed both inside and outside functions.
🔹 Example:
x = 10 # Global variable
def my_function():
print("Inside function:", x) # Accessing
global variable
my_function()
print("Outside function:", x) # Accessible
everywhere
✅ Output:
Inside function: 10
Outside function: 10
✔ Global variables are accessible anywhere.
C. Using global Keyword
To modify a global variable inside a function, use global.
62
🔹 Example:
x = 10 # Global variable
def modify_global():
global x
x = 20 # Modifying global variable
print("Inside function:", x)
modify_global()
print("Outside function:", x) # Value changed
globally
✅ Output:
Inside function: 20
Outside function: 20
✔ The global keyword allows modifying the global variable.
D. Nested Functions and nonlocal Keyword
The nonlocal keyword allows modifying a variable from an
enclosing (non-global) function.
🔹 Example:
def outer_function():
x = 10 # Enclosing variable
def inner_function():
nonlocal x # Modify outer function's
variable
x = 20
print("Inside inner function:", x)
63
inner_function()
print("Inside outer function:", x)
outer_function()
✅ Output:
Inside inner function: 20
Inside outer function: 20
✔ nonlocal modifies variables from an outer function, not the
global scope.
Summary Table
Concept Description Example
Variable inside a function, not def f(): x =
Local Scope
accessible outside 10
Variable declared outside functions,
Global Scope x = 10
accessible everywhere
global Allows modification of a global
global x
Keyword variable inside a function
nonlocal Modifies a variable from an enclosing
nonlocal x
Keyword function