0% found this document useful (0 votes)
2 views4 pages

Case Study

The document contains multiple Python code snippets demonstrating various functionalities such as creating and manipulating SQLite databases, handling exceptions, and file operations. It includes examples of custom exceptions, error handling with try-except blocks, and reading/writing files efficiently. Each section illustrates different programming concepts and best practices in Python.

Uploaded by

M Tarun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views4 pages

Case Study

The document contains multiple Python code snippets demonstrating various functionalities such as creating and manipulating SQLite databases, handling exceptions, and file operations. It includes examples of custom exceptions, error handling with try-except blocks, and reading/writing files efficiently. Each section illustrates different programming concepts and best practices in Python.

Uploaded by

M Tarun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

1.

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()

print("Database created, and records inserted successfully.")


-----------------------------------------------------------------------------------
-----------

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)
])

def show(query, params=()):


c.execute(query, params)
rows = c.fetchall()
headers = [desc[0] for desc in c.description]
print("\n", " | ".join(f"{h:<15}" for h in headers))
print("-" * 60)
for r in rows:
print(" | ".join(f"{str(col):<15}" for col in r))

show("SELECT * FROM emp WHERE name LIKE ?", ("%Johnson",))

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.")

print("Test 1: divide(10, 2)")


divide(10, 2)

print("Test 2: divide(10, 0)")


divide(10, 0)

What happens if an exception occurs in try?


➤ The except block runs. The rest of the try and else blocks are skipped.

Does else execute if there’s an exception?


➤ No. The else block only runs if the try block completes without any exception.
Is finally always executed?
➤ Yes, finally always runs — whether or not there was an exception, and even if you
use return, break, or continue.

-----------------------------------------------------------------------------------
--------------
5.)

If an exception occurs within an except block in Python, it propagates upwards to


the next surrounding try block. If no further try block exists, the program
terminates with the original unhandled exception's traceback.
In essence, if an exception occurs in an except block, it's treated as if the
except block itself is the source of the error, and the program flow returns to the
point of the last enclosing try block.

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()

How to avoid it?


1.)Use else blocks:
If you have code that should only run if no exceptions occurred in the try block,
put it in an else block.
2.) Use finally blocks:
Use finally blocks for cleanup actions (like closing files or releasing resources)
to ensure they are always executed, regardless of exceptions.
3.) Avoid nested try-except blocks excessively:
If you have deeply nested try-except blocks, it can make the code harder to read
and understand. Try to flatten the structure whenever possible.

-----------------------------------------------------------------------------------
----------------------------------------------------------------
6.)To append data to an existing file, open the file in append mode and then write
the new data

file1 = open("myfile.txt", "w")


L = ["This is Delhi \n", "This is Paris \n", "This is London"]
file1.writelines(L)
file1.close()

# 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.

with open('your_file.txt', 'r') as file:


while True:
line = file.readline()
if not line:
break
print(line.strip())

You might also like