0% found this document useful (0 votes)
5 views26 pages

Practical Record

The document lists various Python programming exercises demonstrating concepts such as random module usage, function types, variable scopes, file handling, and data processing. Each exercise includes a brief description and sample code to illustrate the functionality being taught. Topics range from basic operations to file manipulation and exception handling.

Uploaded by

bijujerin68
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)
5 views26 pages

Practical Record

The document lists various Python programming exercises demonstrating concepts such as random module usage, function types, variable scopes, file handling, and data processing. Each exercise includes a brief description and sample code to illustrate the functionality being taught. Topics range from basic operations to file manipulation and exception handling.

Uploaded by

bijujerin68
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
You are on page 1/ 26

List of programs

1. Demonstrating the working of random module and randint() function


2. Demonstrating the working fruitful and void functions
3. Demonstrating the working local and global variables
4. Demonstrating the working of positional and keyword parameters
5. Demonstrating working of default parameters
6. Demonstrating exception handling
7. Demonstrating absolute and relative file paths
8. Demonstrating character by character analysis of text file
9. Demonstrating line by line analysis of text file
10. Demonstrating line by line analysis of text file
11. Demonstrating the working of .tell() and .seek() methods on a text file
12. Demonstrating write, read and append lists to and from a binary file
13. Demonstrating write, read & append dictionary to and from a binary file using 'rb' and 'wb' modes.
14. Demonstrating write, read & append dictionary to and from a binary file using 'rb+' mode.
15. Demonstrating write, read data to and from a csv file.
16. Demonstrating write and read data and making calculations on numeric data from a csv file.
17. Demonstrating simple operations on a stack.
1. Demonstrating the working of random module and randint() function
To play at a casino, you have to pay Re. 1. Two dice are thrown. If the two die show the same numbers,
you get Rs. 5; else you lose your Re. 1. WAPS to simulate 1000 throws of two dice and show an instance of
the player winning and another of the player losing.

from random import randint # Importing module

won, lost = 0, 0
for i in range(1000): # Repeat 1000 times
die1 = randint(1, 6)
die2 = randint(1, 6)

if die1 == die2: # Player wins


won += 1
else: # Player loses
lost += 1

print("You won", won, "and lost", lost) # Display score


winnings = won * 5 - lost

if winnings >= 0:
print("You won Rs.", winnings) # Display winnings
else:
print("You lost Rs.", -winnings) # Display losing
2. Demonstrating the working fruitful and void functions
Write a Python script to create a fruitful function calculator1(a, b, oper) that returns the value of a + b if
oper is +, a - b if oper is -, etc ... Also write a void function calculator2(a, b, oper) that prints the answer
instead of returning.

def calculator1(a, b, oper):


if oper == '+':
return a + b
elif oper == '-':
return a - b
elif oper == '*':
return a * b
elif oper == '/':
return a / b

def calculator2(a, b, oper):


if oper == '+':
print(a + b)
elif oper == '-':
print(a - b)
elif oper == '*':
print(a * b)
elif oper == '/':
print(a / b)

print(calculator1(3, 8, '*'))
calculator2(2, 4, '-')
3. Demonstrating the working local and global variables
Write a Python script that creates func1() with a local variable, func2() to access a global variable and
func3() to modify a global variable.

def func1():
x = 5 # Local variable
print(x)

def func2():
print(x) # Accessing global variable

def func3():
global x
x = 20 # Modifying global variable
print(x)

x = 10
print(x)
func1()
print(x)
func2()
print(x)
func3()
print(x)
4. Demonstrating the working of positional and keyword parameters
Write a Python script to create func() that takes 2 parameters a & b. Invoke it using positional parameters,
keyword parameters and mix of both positional and keyword parameters.

def func(a, b):


print(a - b)

a, b = 10, 20
func(a, b) # Positional arguments
func(b, a) # Outputs differ

print()

func(a=10, b=20) # Keyword arguments


func(b=20, a=10) # Outputs will be same

print()

func(10, b=20) # Mix of positional & keyword parameter(s)


# Positional arguments must come before keyword arguments

print()

# func(a=10, 20) # Won’t work since positional arguments


# are given after keyword arguments
5. Demonstrating working of default parameters
Write simpleInterest() which takes 3 default parameters → P=1000, R=5, T=1 and returns the simple
interest on those values.

def simpleInterest(P=1000, R=5, T=1):

return P * R * T / 100

print(simpleInterest())

print(simpleInterest(2000))

print(simpleInterest(2000, 2))

print(simpleInterest(2000, 2, 2))

6. Demonstrating exception handling


Write a script to demonstrate the handling of exceptions.

def calculateWeeks():
try:
days = int(input("Enter no. of days: "))
if days < 0:
print("Enter positive number")
else:
weeks = days // 7
print("Weeks for entered days is", weeks)
except ValueError: # Will be encountered if there non-integer is entered
print("Enter integers only")
else: # Will be encountered if there are no exceptions
print("No exceptions raised")
finally: # Will always be encountered
print("Thank you for using this program")

calculateWeeks()

7. Demonstrating absolute and relative file paths


You have the folder hierarchy as shown above. Your Python code is in "Source.py".
Write the Python statements to open "Abc.txt" in read mode, using absolute and relative paths.

Absolute Path:
inn = open("C:\\User\\Abc.txt")
inn = open("\\User\\Abc.txt")

inn = open("C:/User/Abc.txt")
inn = open("/User/Abc.txt")

inn = open(r"C:\User\Abc.txt")
inn = open(r"\User\Abc.txt")

Relative Path:
inn = open("..\\User\\Abc.txt")
inn = open("../User/Abc.txt")
inn = open(r"..\User\Abc.txt")

8. Demonstrating character by character analysis of text file


Write a script to read a text file "Story.txt" and display the number of vowels, consonants, digits,
uppercase characters, lowercase characters and special characters in the file.
If "Story.txt" contains:

Once there was a thirsty crow.


It flew 20 km to find some water to drink.

inn = open("Story.txt")
s = inn.read()
inn.close()
u, l, v, c, d, sp = 0, 0, 0, 0, 0, 0
for char in s:
if char.isalpha():
if char.isupper():
u += 1
elif char.islower():
l += 1
if char in "aeiouAEIOU":
v += 1
else:
c += 1
elif char.isdigit():
d += 1
else:
sp += 1

print(u, "upper case letters")


print(l, "lower case letters")
print(v, "vowels")
print(c, "consonants")
print(d, "digits")
print(sp, "special characters")
9. Demonstrating line by line analysis of text file
Write a script to read a text file "Story.txt" and display the number of lines in the file.
If "Story.txt" contains:

Once there was a thirsty crow.


It flew 20 km to find some water to drink.

inn = open("Story.txt")
ctr = 0

while True:
line = inn.readline()
if line == "":
break
ctr += 1

inn.close()
print(ctr, "lines")

10. Demonstrating line by line analysis of text file


Write a script to read a text file "Story.txt" and display the number of lines in the file that begin with a
vowel.
If "Story.txt" contains:

Once there was a thirsty crow.


It flew 20 km to find some water to drink.
Finally, it saw a pot of water on the horizon.

inn = open("Story.txt")
L = inn.readlines()
inn.close()

for line in L:
if line[0] in "aeiouAEIOU":
print(line, end='')

11. Demonstrating the working of .tell() and .seek() methods on a text file
Write a script to write and read to a text file and show the working of .tell() and .seek().
io = open("Authors.txt", 'a+') # Open in append & read mode
io.write("Homer Shaw ") # Write string to file
print(io.tell())
io.seek(0) # Re-position file pointer to BOF
print(io.tell()) # Print file pointer position
io.write("Shakespeare ") # Writes to EOF
io.seek(0)
print(io.read()) # Print file contents
print(io.tell())
io.close() # Close file

12. Demonstrating writing, reading and appending lists to and from a binary file
 Write writeBin() to create 3 lists, each with the name and capital of a country. Write each list to a binary file
"Nations1.bin". Invoke the function.
 Write readBin() to read the contents of "Nations1.bin" and display the same. Invoke it.
 Write addBin() to create a list with the name and capital of 1 country. Write the list to "Nations1.bin". Invoke it.
 Invoke readBin() again, to display the latest file contents.

import pickle # Import required module

def writeBin():
with open("Nations1.bin", 'wb') as out: # Open file for write with context
manager
pickle.dump(["India", "New Delhi"], out) # Write individual lists to binary
file
pickle.dump(["Pakistan", "Islamabad"], out)
pickle.dump(["China", "Beijing"], out)

def readBin():
with open("Nations1.bin", 'rb') as inn: # Open file for read with context
manager
try:
while True: # Loop to read all objects in file
obj = pickle.load(inn) # Read each object
print(obj)
except EOFError: # Catching EOF exception
pass

def addBin():
with open("Nations1.bin", 'ab') as out: # Open file for append with context
manager
pickle.dump(["Nepal", "Kathmandu"], out)

writeBin()
readBin()
print()
addBin()
readBin()
13. Demonstrating write, read & appending dictionary to and from a binary file using 'rb' and 'wb' modes.
 Write writeBin() to create a dictionary containing names and capitals of 3 countries. Write the same as a single
object to a binary file "Nations2.bin". Invoke the function.
 Write readBin() to read the contents of "Nations2.bin" and display the same. Invoke it.
 Write addBin() to add the name and capital of 1 country to the dictionary in "Nations2.bin". Invoke the function.
 Invoke readBin() again, to display the file contents.

import pickle # Import required module

def writeBin():
with open("Nations2.bin", 'wb') as out: # Open file for binary write
D = {"India": "New Delhi", "Pakistan": "Islamabad", "China": "Beijing"}
pickle.dump(D, out) # Write single dictionary to file

def readBin():
with open("Nations2.bin", 'rb') as inn: # Open file for binary read
D = pickle.load(inn) # Read the only object in file
for k, v in D.items():
print(k, v)

def addBin():
with open("Nations2.bin", 'rb') as inn: # Open file for binary read
D = pickle.load(inn)
D.update({"Nepal": "Kathmandu"}) # Update dictionary
with open("Nations2.bin", 'wb') as out: # 'wb' mode deletes previous
contents
pickle.dump(D, out) # Write updated dictionary

writeBin()
readBin()
print()
addBin()
readBin()
14. Demonstrating write, read & appending dictionary to and from a binary file using 'rb+' mode.
 Write writeBin() to create a dictionary containing names and capitals of 3 countries. Write the same as a single
object to a binary file "Nations2.bin". Invoke the function.
 Write readBin() to read the contents of "Nations2.bin" and display the same. Invoke it.
 Write addBin() to add the name and capital of 1 country to the dictionary in "Nations2.bin". Invoke the function.
 Invoke readBin() again, to display the file contents.

import pickle # Import required module

def writeBin():
with open("Nations2.bin", 'wb') as out: # Open file for binary write
D = {"India": "New Delhi", "Pakistan": "Islamabad", "China": "Beijing"}
pickle.dump(D, out) # Write single dictionary to file

def readBin():
with open("Nations2.bin", 'rb') as inn: # Open file for binary read
D = pickle.load(inn) # Read the only object in file
for k, v in D.items():
print(k, v)

def addBin():
with open("Nations2.bin", 'rb+') as inout: # Open file for binary read and
write
D = pickle.load(inout)
D.update({"Nepal": "Kathmandu"}) # Update dictionary
inout.seek(0) # Reposition file pointer to BOF
pickle.dump(D, inout) # Write updated dictionary

writeBin()
readBin()
print()
addBin()
readBin()
15. Demonstrating writing and reading data to and from a csv file.
 Write WriteCSV() to write the names and marks of 3 students to a csv file "Stud.csv". The file should
also contain an appropriate header. Invoke the function.
 Write ReadCSV() to read the contents of "Stud.csv" and display the same. Invoke the function.

import csv # Import necessary module

def WriteCSV(): # Function to write


with open("Stud.csv", 'w', newline='') as out: # Create & open csv file for writing
W = csv.writer(out, delimiter=',') # Create writer object
W.writerow(["Name", "Marks"]) # Write single row
W.writerow(["Adisesh", 23])
W.writerows([["Crisvin", 18], # Write multiple rows
["Gautam", 14]
])

WriteCSV() # Invoke function

def ReadCSV(): # Function to read


with open("Stud.csv", 'r', newline='') as inn: # Open csv file for reading
R = csv.reader(inn, delimiter=',') # Create reader object
L = list(R) # Convert to list
for row in L: # Iterate over each row
print(row[0], row[1])

ReadCSV() # Invoke function


16. Demonstrating writing and reading data and making calculations on numeric data from a csv file.
 Write addHeader() to write the header consisting of the following fields ["Name", "Eng", "Phy", "Chem",
"Math", "CS"] to a csv file "Marks.csv".
 Write addDetails() to write a list containing the following tuples to "Marks.csv".
[("K. Mathews", 65, 56, 54, 65, 45),
("A. George", 55, 45, 65, 45, 65),
("N. Thomas", 85, 77, 64, 65, 78)
]
 Write ReadCSV() to read the contents of "Stud.csv" and display the same, including subject average for each
student. Invoke the function.

import csv

def addHeader():
with open("Marks.csv", 'w', newline='') as out:
W = csv.writer(out, delimiter=',')
W.writerow(["Name", "Eng", "Phy", "Chem", "Math", "CS"])
addHeader()

def addDetails():
with open("Marks.csv", 'a', newline='') as out:
W = csv.writer(out, delimiter=',')
W.writerows([("K. Mathews", 65, 56, 54, 65, 45),
("A. George", 55, 45, 65, 45, 65),
("N. Thomas", 85, 77, 64, 65, 78)
])
addDetails()
def showDetails():
with open("Marks.csv", 'r', newline='') as inn:
R = csv.reader(inn, delimiter=',')
H = next(R)
print("%-12s%5s%5s%5s%5s%5s%6s" % (H[0],H[1],H[2],H[3],H[4],H[5],"Avg"))
L = list(R)
for row in L:
space = row[0].find(' ')
print("%-12s%5s%5s%5s%5s%5s" % (row[0],row[1],row[2],row[3],row[4],row[5]),
end='')
tot = 0
for i in range(1, 6):
tot += int(row[i])
print("%6s" % (tot/5))
showDetails()
17. Demonstrating simple operations on a stack.

stack = []

def Push(val):
stack.append(val)

def Display():
if len(stack) == 0:
print("Empty stack")
else:
print("Stack contains")
for i in range(-1, -len(stack)-1, -1):
print(stack[i])
print()

def Pop():
if not stack:
print("Stack underflow")
else:
val = stack.pop()
print(val, "popped\n")
Push(4); Push(9); Push(3)
Display()
Pop()
Display()
Push(-5)
Display()
Pop()
Display()
18. Demonstrating SQL commands on a single table.
a) Write SQL statements on relation ‘Company’ to do the following:

Table: Company
+------+--------+-----------+------------+
| cid | cname | ho | contact |
+------+--------+-----------+------------+
| 1 | Titan | Okhla | C. B. Ajit |
| 2 | Ajanta | Jajafgarh | R. Mehta |
| 3 | Maxima | Shahdara | B. Kohli |
| 4 | Seiko | Okhla | R. Chadha |
| 5 | Ricoh | Shahdara | J. Kishore |
+------+--------+-----------+------------+
i. To see the structure of the table "Company".

DESC company;

ii. To display all details of table "Company".

SELECT * FROM company;

iii. To display cid & cname of table "Company".

SELECT cid, cname FROM company;

iv. To display all ho’s in table "Company".

SELECT ho FROM company;

v. To display all ho’s in table "Company" without repetition.

SELECT DISTINCT ho FROM company;

vi. To display details of companies whose "ho" is Okhla.

SELECT * FROM company WHERE ho = "Okhla";


vii. To display details of companies whose "ho" is not Okhla (using IN keyword).

SELECT * FROM company WHERE NOT ho IN ("Okhla");

viii. To display cid, cname of companies whose "contact" names end with 'a'.

SELECT cid, cname FROM company WHERE contact LIKE "%a";

ix. Write the command to display details of companies in ascending order of contact.

SELECT * FROM company ORDER BY contact;

x. To display details of companies in descending order of "ho".

SELECT * FROM company ORDER BY ho DESC;


b) Predict the output of:

xi. SELECT COUNT(ho) FROM company;

xii. SELECT COUNT(DISTINCT ho) FROM company;

xiii. SELECT cid, cname FROM company WHERE cid IN (1, 3);

1 Titan
3 Maxima

xiv. SELECT cid, cname FROM company WHERE cid BETWEEN 1 AND 3;

1 Titan
2 Ajanta
3 Maxima

xv. SELECT * FROM company WHERE cid > 1 AND cid < 3;

2 Ajanta Jajafgarh R. Mehta


Demonstrating SQL commands on 2 tables joined by a common attribute.
a) Write SQL statements on relations ‘Student’ and ‘Houses’ linked by a common attribute ‘house’:
Table: student Table: houses
+------+-----------+---------- +-----------+--------+--------------+
+-----------+ | house | color | master |
| roll | fname | lname | house +-----------+--------+--------------+
| | Amber | Yellow | Aneesh |
+------+-----------+---------- | Crimson | Red | Tushar |
+-----------+ | Indigo | Blue | Kavitha |
| 1 | Adishesh | Nair | Amber | Lavender | Purple | Thomas |
| | Tangerine | Orange | Baiju |
| 2 | Crisvin | Regi | Lavender | Viridian | Green | Hari Pradeep |
| +-----------+--------+--------------+
| 3 | Gautham | G Kurup | Viridian
|
| 4 | Govardhan | Ramesh | Amber
|
| 5 | Henry | Raju A | Indigo
|
| 6 | Joel | Isaac | Lavender
|
| 7 | Joshua | Abhraham | Viridian
|
| 8 | Joshua | Soji | Amber
|
| 9 | Madhav | Manoj | Crimson
|
| 10 | Midhun | K Madhu | Indigo
|
| 11 | Nahum | Thomas | Lavender
|
| 12 | Ruben | Joemon | Viridian
|
| 13 | Shawn | Joshua | Crimson
|
| 14 | Ann | Grace | Crimson
|
| 15 | Dhiya | Mariam | Lavender
|
| 16 | Diya | Susan |
Tangerine |
| 17 | Irene | Alice | Viridian
|
| 18 | Lorena | Avelyn | Indigo
|
| 19 | Raveena | Nambiar |
Tangerine |
+------+-----------+----------
+-----------+
i. The Cartesian Product of the two tables.
SELECT * FROM student, houses;
ii. Details of students whose houses are not Lavender, Indigo or Amber sorted by house.
SELECT * from student NATURAL JOIN houses WHERE house NOT IN
("Lavender", "Indigo", "Amber") ORDER BY house;
iii. Details of students from roll 5 to 15 from table student.
SELECT * FROM student WHERE roll BETWEEN 5 AND 15;
iv. Display details of the highest roll number.
SELECT * FROM student where roll = (SELECT MAX(roll) FROM
student);
v. Display details of students belonging to Amber house with house master's name.
SELECT roll, fname, lname, house, master FROM houses NATURAL
JOIN student WHERE house = 'Amber';
vi. Display no. of students whose house master is "Thomas".
SELECT COUNT(*) FROM student NATURAL JOIN houses WHERE master
= 'Thomas';
vii. House master's names, color and their corresponding houses.
SELECT DISTINCT master, color from houses;
viii. Details of students & houses having house master whose name start with 'T'.
SELECT * FROM student NATURAL JOIN houses WHERE master LIKE 'T
%';
ix. Display names of students with their respective houses and house master.
SELECT fname, house, master FROM student natural join houses;
x. Details of students in "Tangerine" house.
SELECT * FROM student NATURAL JOIN houses WHERE house = "Tangerine";
b) Predict the output of:

xi. SELECT * from student WHERE roll = 10;


+------+--------+---------+--------+
| roll | fname | lname | house |
+------+--------+---------+--------+
| 10 | Midhun | K Madhu | Indigo |
+------+--------+---------+--------+
xii. SELECT * from student NATURAL JOIN houses WHERE house = 'Lavender';
+----------+------+---------+--------+--------+--------+
| house | roll | fname | lname | color | master |
+----------+------+---------+--------+--------+--------+
| Lavender | 2 | Crisvin | Regi | Purple | Thomas |
| Lavender | 6 | Joel | Isaac | Purple | Thomas |
| Lavender | 11 | Nahum | Thomas | Purple | Thomas |
| Lavender | 15 | Dhiya | Mariam | Purple | Thomas |
+----------+------+---------+--------+--------+--------+
xiii. SELECT * FROM student s NATURAL JOIN houses h WHERE roll > 2 AND roll < 5 AND s.house = h.house
ORDER BY fname DESC;
+----------+------+-----------+---------+--------+--------------
+
| house | roll | fname | lname | color | master
|
+----------+------+-----------+---------+--------+--------------
+
| Amber | 4 | Govardhan | Ramesh | Yellow | Aneesh
|
| Viridian | 3 | Gautham | G Kurup | Green | Hari Pradeep
|
+----------+------+-----------+---------+--------+--------------
+
xiv. SELECT house, COUNT(*), master FROM student NATURAL JOIN houses GROUP BY house;
+-----------+----------+--------------+
| house | COUNT(*) | master |
+-----------+----------+--------------+
| Amber | 3 | Aneesh |
| Crimson | 3 | Tushar |
| Indigo | 3 | Kavitha |
| Lavender | 4 | Thomas |
| Tangerine | 2 | Baiju |
| Viridian | 4 | Hari Pradeep |
+-----------+----------+--------------+

19. Answer the four queries allotted to you, with reference to tables accessories and shoppe.

Table: Accessories Table: Shoppe


+-----+-------------+------- +------+--------------------
+------+ +-------------+
| no | name | price | id | id | sname | area
| |
+-----+-------------+------- +------+--------------------
+------+ +-------------+
| A01 | Motherboard | 12000 | S001 | S001 | ABC Computronics | CP Nagar
| |
| A02 | Hard Disk | 5000 | S001 | S002 | All Infotech Medic | GK II
| |
| A03 | Keyboard | 500 | S002 | S003 | Tech Shoppe | CP Nagar
| |
| A04 | Mouse | NULL | S001 | S004 | Geeks Techno Soft | Nehru
| Place |
| A05 | Motherboard | 13000 | S002 | S005 | Geeks Hitech Store | Nehru
| Place |
| A06 | Keyboard | 400 | S003 +------+--------------------
| +-------------+
| A07 | LCD | 6000 | S004
|
| A08 | LCD | 5500 | S005
|
| A09 | Mouse | 350 | S005
|
| A10 | Hard Disk | 4500 | S003
|
+-----+-------------+-------
+------+

1. To display id and sname of shops from table shoppe located in 'GK II'.
2. To display shoppe names from table shoppe which contains the word 'Tech'.
3. To display each accessory name without repetition.
4. To display name, id & sname of accessories sold by Tech Shoppe.
5. To display details of accessories whose price is more than 10000.
6. To display shop names whose name begins with 'G'.
7. To display the Natural Join of the 2 tables for id S001.
8. To display details from both tables where price is not known.

You might also like