0% found this document useful (0 votes)
12 views5 pages

Python Functions for Vehicle and Courier Management

The document contains practical Python programming questions related to data handling, including functions for managing vehicle records, courier details, and book information using CSV and binary files. It also covers SQL connectivity with MySQL, demonstrating how to create a database, create and alter tables, insert, select, update, and delete records. Each section includes code snippets for implementing the described functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views5 pages

Python Functions for Vehicle and Courier Management

The document contains practical Python programming questions related to data handling, including functions for managing vehicle records, courier details, and book information using CSV and binary files. It also covers SQL connectivity with MySQL, demonstrating how to create a database, create and alter tables, insert, select, update, and delete records. Each section includes code snippets for implementing the described functionality.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#CLASS 12 PRACTICAL QUESTIONS

Q1. Write a function in Python,Push(Vehicle) where,Vehicle is a dictionary


containing details of vehicles-{Car_Name:Maker}
The function should push the name of car manufactured by "Tata" (including
all the possible cases like Tata ,TaTa,etc.) to the stack.
For example:
If the dictionary contains the following data
Vehicle={"Santro":"Hyundai","Nexon":"tata","Safari":"Tata"}
The stack should contain
Safari
Nexon
Answer
stack=[]
Vehicle={"Santro":"Hyundai","Nexon":"tata","Safari":"Tata"}
def Push(Vehicle):
for i in Vehicle:
if Vehicle[i].upper()=="TATA":
print(i)
[Link](i)

Push(Vehicle)
print(stack)

Q2. Write a program in Python that defines and calls the following user de-
fined functions
i) COURIER_ADD():It takes the values from the user and adds the details to a
csv file '[Link]'.
Each record consists of a list with field elements as cid,s_name ,Source,des-
tination to store Courier ID,Sender name,Source and destination
address respectively.
ii) COURIER_SEARCH(): Takes the destination as the input and display all the
courier records going to that destination.
Answer
import csv
def COURIER_ADD():
f1=open("[Link]","a")
st=[Link](f1)
while True:
cid=input("Enter courier id")
s_name=input("Enter sender name")
source=input("Enter source ")
destination=input("Enter destination")
l1=[cid,s_name,source,destination]
[Link](l1)
choice=input("Do you want to enter more values Yes/No")
if [Link]()=="NO":
break
[Link]()

def COURIER_SEARCH():
f1=open("[Link]","r")
destination=input("Enter destination to be searched")
rec=[Link](f1)
for i in rec:
if i[3].upper()=="DELHI":
print(i)

COURIER_ADD()
COURIER_SEARCH()
Q3. A Binary File [Link] has the following structure:
{BNO:[BANME,BTYPE]}
WHERE,
BNO-Book Number
BNAME-Book Name
Btype is Book Type
Write a user defined function,selectType(btype),that accepts as parameter
and
display all the records from the binary file [Link],that have the value
of Book Type as btype.
Answer
import pickle
f1=open("[Link]","wb")
d1={}
while True:
book_number=input("Enter book number")
book_name=input("Enter book name")
book_type=input("Enter book type")
d1[book_number]=[book_name,book_type]
choice=input("Do you want to enter more values yes/no")
if [Link]()=="NO":
break
print(d1)
[Link](d1,f1)
[Link]()

f1=open("[Link]","rb")
rec=[Link](f1)
btype=input("Enter btype")
for i in rec:
x=rec[i]
if x[1]==btype:
print("Book Number=",[i],"Book Name=",x[0],"Book Type=",x[1])"""

#PYTHON SQL CONNECTIVITY PROGRAMS

CREATE A DATABASE 'SCHOOL'

import [Link]
mydb=[Link](host="localhost",username="root",passwd="")
mycursor=[Link]()
[Link]("create database school")
print("database created")

CREATE A TABLE 'STUDENT' INSIDE THE DATABASE 'SCHOOL'

import [Link]
mydb=[Link](host="localhost",\
username="root",\
passwd="",\
database="school")
mycursor=[Link]()
[Link]("create table student(rollno int(3) primary key,name
varchar(15),gender char(1),dob date)")
print("Table created")
#ALTER TABLE 'Student' INSIDE THE DATABASE 'School' ADD COLUMN
MARKS

import [Link]
mydb=[Link](host="localhost",usern="root",passwd="",database=
"school")
mycursor=[Link]()
[Link]("alter table student add (marks int(3))")

[Link]("desc student")
for x in mycursor:
print(x)

#INSERT VALUES TO THE TABLE Student(TAKE VALUES FROM THE USER)


import [Link]
mydb=[Link](host="localhost",\
username="root",\
passwd="",\
database="school")

mycursor=[Link]()
n=int(input("Enter the number of records to be inserted in the table"))
for i in range(n):
rollno=int(input("Enter rollno"))
name=input("Enter name")
gender=input("Enter gender")
date=input("Enter date")
marks=int(input("Enter marks"))
mySql_insert_query = 'INSERT INTO student VALUES (%s, %s, %s, %s,%s) '
record = (rollno, name, gender, date,marks)
[Link](mySql_insert_query, record)
[Link]()
print("Record inserted successfully into table")"""

#SELECT DATA FROM THE TABLE Student

import [Link]
mydb=[Link](host="localhost",\
user="root",\
password="",\
database="school")
mycursor=[Link]()
[Link]("SELECT * FROM Student")
myrecords=[Link](2)
numberof_records=[Link]

print("Total no of records found are:",numberof_records)


print()
for x in myrecords:
print(x)

#SELECT DATA FROM THE TABLE Student USING LIKE OPERATOR

import [Link]
mydb=[Link](host="localhost",\
username="root",\
passwd="",\
database="school")
mycursor=[Link]()
[Link]("SELECT * FROM Student where name LIKE '_a%'")
myrecords=[Link]()
numberof_records=[Link]

print("Total no of records found are:",numberof_records)


print()
for x in myrecords:
print(x)"""

DELETE PARTICULAR DATA FROM THE TABLE Student

"""import [Link]
mydb=[Link](host="localhost",\
username="root",\
passwd="",\
database="school")
mycursor=[Link]()
[Link]("DELETE FROM Student where rollno=1")

[Link]()

print([Link],"Record(s) Deleted")"""

UPDATE PARTICULAR ROW FROM THE TABLE STUDENT

"""import [Link]
mydb=[Link](host="localhost",\
username="root",\
passwd="",\
database="school")
mycursor=[Link]()
name=input("Enter name of the student for whom the data has to be updated")
marks=input("Enter marks of the student which is to be updated")

query="UPDATE Student set marks=%s where name=%s"


data=(marks,name)
[Link](query,data)

[Link]()
print([Link],"Record(s) updated")"""

Common questions

Powered by AI

When designing a program with frequent CSV file I/O, considerations should include minimizing file access times to reduce I/O overhead—such as batching writes to reduce the number of file open/close operations. It is crucial to ensure data consistency by using locks or a database when concurrent accesses may occur. Proper error handling is important to manage I/O exceptions effectively. Considering using memory buffers or in-memory representations to handle data before writing to the file can optimize performance .

Creating databases using Python's mysql.connector library offers seamless integration with MySQL databases, allowing Python scripts to automate database creation and management tasks. This increases productivity by streamlining setup processes and batch processing. However, security implications include the risk of SQL injections if inputs are not properly sanitized, and the potential exposure of sensitive connection credentials, which can be mitigated by employing environment variables and secure connection parameters .

SQL commands like SELECT, DELETE, and UPDATE enable refined and organized management of student records in a database. SELECT allows users to retrieve specific data efficiently by using criteria such as conditions and pattern matching with operators like LIKE. DELETE facilitates data integrity by removing obsolete or incorrect entries. UPDATE ensures data currency by allowing changes to specific record fields without disturbing the rest of the database. This modularity of SQL operations helps maintain a clean, accurate, and up-to-date record system within the database .

CSV files are significant for storing courier details because they provide a simple, text-based format that is easy to read and write using Python's csv module. They allow for easy integration with spreadsheet software and databases, and their structured nature makes it straightforward to manage lists like courier records. The CSV format is also both human-readable and application-independent, making it a versatile choice for data storage compared to binary formats or specialized databases that may require more complex parsing or software dependencies .

Using transaction log-based recovery mechanisms ensures durability and reliability in databases. During an SQL UPDATE operation, transaction logs keep a record of changes, enabling the database to rollback in the event of failure, and ensure integrity and consistency of data after abrupt terminations. This is crucial in multi-user environments, where simultaneous updates can lead to data anomalies. Transaction logs also facilitate auditing, as changes can be traced back through logs .

The COURIER_SEARCH function allows for destination-based querying from records in 'courier.csv', enhancing targeted data retrieval by matching the search term (e.g., 'DELHI'). Efficiency could be improved by using dictionary or database structures for faster access, as linear search in CSV files can be slow with large datasets. Incorporating search index paradigms or caching strategies might further boost efficiency. Additionally, dynamic search refinement using user interactions or pattern matching can enhance functionality .

The selectType function utilizes binary files by first reading the entire file contents into memory using the pickle module's load function. It then iterates over the dictionary of records, checking if the book type matches the provided filter criterion. This method allows for efficient data retrieval and storage, as binary files with pickles maintain the integrity and original structure of complex Python objects. Unlike simple text files, binary files are generally faster to read/write and more compact, which is advantageous when dealing with large datasets .

The LIKE operator enables pattern matching in SQL queries, allowing flexible search criteria to be defined using wildcards. This operator is particularly useful when searching for substrings within text fields. An example from the document is the query that selects records from the Student table where names start with an 'a', which uses the query 'SELECT * FROM Student where name LIKE '_a%''. The underscore ('_') represents a single wildcard character, and the percentage ('%') represents zero or more wildcard characters, enabling robust and adaptable search capabilities .

User input validation can be enhanced by implementing checks before the input is processed. For example, ensuring 'rollno' is a unique positive integer, 'name' matches expected character patterns, 'gender' is limited to specific known values, and 'marks' fall within a reasonable range. Additionally, using try-except blocks to catch and handle exceptions like ValueError can prevent incorrect data types from causing runtime errors. Implementing such validations can reduce errors and ensure data consistency and integrity in the database .

The function Push() addresses case sensitivity by converting the manufacturer name to uppercase when comparing it with 'TATA'. This ensures that variations like 'tata', 'TaTa', and 'TATA' are all recognized as a match. The condition within the loop uses 'Vehicle[i].upper() == "TATA"' to make this comparison .

You might also like