Case Study
Case Study
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
age INTEGER
)
''')
users = [
{"name": "Alice", "email": "[email protected]", "age": 25},
{"name": "Bob", "email": "[email protected]", "age": 30},
{"name": "Charlie", "email": "[email protected]", "age": 28},
{"name": "Diana", "email": "[email protected]", "age": 35},
]
insert_query = '''
INSERT INTO users (name, email, age)
VALUES (:name, :email, :age)
'''
cursor.executemany(insert_query, users)
conn.commit()
conn.close()
2.)
import sqlite3
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute('CREATE TABLE emp (id INTEGER, name TEXT, age INTEGER, salary REAL)')
c.executemany('INSERT INTO emp VALUES (?, ?, ?, ?)', [
(1, 'Alice Johnson', 28, 60000),
(2, 'Bob Smith', 35, 75000),
(3, 'Charlie Green', 40, 50000),
(4, 'David Johnson', 30, 68000),
(5, 'Eve Jackson', 45, 85000)
])
show("SELECT * FROM emp WHERE age BETWEEN ? AND ?", (30, 40))
conn.close()
-----------------------------------------------------------------------------------
-----
3.)
class InvalidAgeError(Exception):
def __init__(self, age, msg="Age must be between 0 and 120"):
self.age = age
self.msg = msg
super().__init__(self.msg)
def __str__(self):
return f'{self.age} -> {self.msg}'
def set_age(age):
if age < 0 or age > 120:
raise InvalidAgeError(age)
else:
print(f"Age set to: {age}")
try:
set_age(150) # This will raise the custom exception
except InvalidAgeError as e:
print(e)
-----------------------------------------------------------------------------------
-----------
4.)
def divide(a, b):
try:
result = a / b
print(" Division successful.")
except ZeroDivisionError:
print(" Cannot divide by zero.")
else:
print(" No errors occurred.")
finally:
print(" This block always runs.")
-----------------------------------------------------------------------------------
--------------
5.)
def outer_function():
try:
try:
1/0 # Raises ZeroDivisionError
except ZeroDivisionError:
print("Division by zero")
1/0 # Raises ZeroDivisionError again in except block
except Exception as e:
print(f"Another error: {e}")
except ZeroDivisionError:
print("Handling the propagated exception")
except Exception as e:
print(f"General error: {e}")
outer_function()
-----------------------------------------------------------------------------------
----------------------------------------------------------------
6.)To append data to an existing file, open the file in append mode and then write
the new data
# Append-adds at last
file1 = open("myfile.txt", "a") # append mode
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.read())
print()
file1.close()
-----------------------------------------------------------------------------------
------------------------------
7.)In Python, we can read a file line by line without loading the entire file into
memory using a with statement and a for loop. This is efficient and memory-
friendly, especially for large files.