Practical Record
Practical Record
won, lost = 0, 0
for i in range(1000): # Repeat 1000 times
die1 = randint(1, 6)
die2 = randint(1, 6)
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.
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.
a, b = 10, 20
func(a, b) # Positional arguments
func(b, a) # Outputs differ
print()
print()
print()
return P * R * T / 100
print(simpleInterest())
print(simpleInterest(2000))
print(simpleInterest(2000, 2))
print(simpleInterest(2000, 2, 2))
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()
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")
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
inn = open("Story.txt")
ctr = 0
while True:
line = inn.readline()
if line == "":
break
ctr += 1
inn.close()
print(ctr, "lines")
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.
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.
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.
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
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;
viii. To display cid, cname of companies whose "contact" names end with 'a'.
ix. Write the command to display details of companies in ascending order of contact.
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;
19. Answer the four queries allotted to you, with reference to tables accessories and shoppe.
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.