0% found this document useful (0 votes)
26 views

Cheat Code Booklet For Alevel P4-Python New

Alevel python

Uploaded by

ialeeza02
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Cheat Code Booklet For Alevel P4-Python New

Alevel python

Uploaded by

ialeeza02
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Cheat Code Booklet

Computer Science-9618
A level – P4 9618 : Python based as per syllabus 2023-2025

Navid Saqib: +923334259883 Computer Science 9618


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A: 1D Array
Qno1:

Write a program that performs the following tasks:

1. Declare an array named product that can hold 4 elements of type string.
2. Prompt the user to input the name of a product for each of the 4 elements
in the array.
3. After all inputs are received, display the heading "Pname".
4. Print each of the 4 product names under this heading.

Provide the a python code implementation for this task.

Apply Python code:


product = [0,0,0,0]
for x in range(0,4):
print("product no : ",x+1)
product[x] = input("Enter product Name : ")
print("Pname")
for y in range(0,4):
print(product[y])

NAVID SAQIB: +923334259883 1


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno2:

Write a program that performs the following tasks:

1. Create four 1-dimensional arrays named ProductName, Qty, Price, and


Total, each containing 4 elements.
2. Use a loop to prompt the user to input data for each element in the
ProductName, Qty, and Price arrays. Calculate the Total for each product by
multiplying Qty by Price.
3. After all inputs are collected, display the appropriate headings
(ProductName, Qty, Price, Total) and output the corresponding data under
each heading.

Provide the python code implementation for this task.

Apply Python code:


pname = [0,0,0,0]
qty = [0,0,0,0]
price = [0,0,0,0]
total = [0,0,0,0]
for x in range(0,4):
pname[x] = input("Enter productName : ")
qty[x] = int(input("Enter qty : "))
price[x] = int(input("Enter price : "))
total[x] = qty[x] * price[x]

print("Pname\t","qty\t","price\t","total\t")
for y in range(0,4):
print(pname[y],"\t",qty[y],"\t",price[y],"\t",total[y])

NAVID SAQIB: +923334259883 2


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno3:

Write a program that performs the following tasks:

1. Create four 1-dimensional arrays named ProductName, Qty, Price, and


Total, each containing 4 elements.
2. Use a loop to prompt the user to input data for each element in the
ProductName, Qty, and Price arrays.
3. Calculate the Total for each product by multiplying the corresponding Qty
by Price and store the result in the Total array.
4. After all calculations, find and display the grand total, which is the sum of
all elements in the Total array.

Provide the python code implementation for this task.

Apply Python code:


pname = [0,0,0,0]
qty = [0,0,0,0]
price = [0,0,0,0]
total = [0,0,0,0]
grandtotal = 0
for x in range(0,4):
pname[x] = input("Enter productName : ")
qty[x] = int(input("Enter qty : "))
price[x] = int(input("Enter price : "))
total[x] = qty[x] * price[x]
grandtotal = grandtotal + total[x]

print("Pname\t","qty\t","price\t","total\t")
for y in range(0,4):
NAVID SAQIB: +923334259883 3
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print(pname[y],"\t",qty[y],"\t",price[y],"\t",total[y])
print("Grand Total : ", grandtotal)

NAVID SAQIB: +923334259883 4


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno4:

Write a program that performs the following tasks:

1. Create arrays named StudentName, Mark1, Mark2, Mark3, and Total. The
number of elements in each array should be determined by the user.
2. Use a loop to prompt the user to input the student's name and their marks
for Mark1, Mark2, and Mark3.
3. Implement validation to ensure that:
o Mark1 is between 0 and 25.
o Mark2 is between 0 and 35.
o Mark3 is between 0 and 45.
4. If the entered marks are within the valid range, calculate the Total marks
for each student by summing Mark1, Mark2, and Mark3.
5. Calculate the average marks (AvgMarks) for each student.
6. Display the student's name, Mark1, Mark2, Mark3, Total, and AvgMarks in a
tabular format.

Provide the pseudocode or code implementation for this task.

Apply Python code:


#validation: m1 between 0-25, m2 between 0-35, m3 between 0-45
stname = 0
m1 = 0
m2 = 0
m3 = 0
total = 0
avg = 0
student = 0
student = int(input("Enter Total number of Student in Class : "))
for x in range(student):

NAVID SAQIB: +923334259883 5


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print("Student no : ", x + 1)
stname = input("Enter Student Name : ")
m1 = int(input("Enter Subject 1 marks : "))
while m1<0 or m1>25:
m1 = int(input("Error : Re Enter Subject 1 marks between 0 to 25 : "))
m2 = int(input("Enter Subject 2 marks : "))
while m2<0 or m2>35:
m2 = int(input("Error : Re Enter Subject 2 marks between 0 to 35 : "))
m3 = int(input("Enter Subject 3 marks : "))
while m3<0 or m3>45:
m3 = int(input("Error : Re Enter Subject 3 marks between 0 to 45 : "))

total = m1 + m2 + m3
avg = total/3
print()
print("Student Name : ", stname)
print("Test 1 Marks : ", m1)
print("Test 2 Marks : ", m2)
print("Test 3 Marks : ", m3)
print("Total Marks : ", total)
print("Avg Marks : ", avg)

NAVID SAQIB: +923334259883 6


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno4a:

Write a program that performs the following tasks:

1. Accept a string input from the user.


2. Count the occurrences of a specific character, such as 'a', within the given
string.
3. Display the total number of times the character appears in the string.

Provide the python code implementation for this task.

Apply Python code:


# The main idea is to count all the occurring characters in a string.
# If you have a string like aba, then the result should be {'a': 2, 'b': 1}.
# What if the string is empty? Then the result should be empty object literal, {}

# Answer
# Here we are counting every character in a string, the number of times a
# character appears in a string that number is being output along with the
characters
# in a dictionary form
def count_characters(input_string):
# Initialize an empty dictionary to store character counts
char_count = {}
# Loop through each character in the input string
for char in input_string:

NAVID SAQIB: +923334259883 7


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

# Update the count for the current character in the dictionary


char_count[char] = char_count.get(char, 0) + 1
return char_count
# Example usage:
input_str = "wahabahmadkhan"
result = count_characters(input_str)
print(result) # Output: {'a': 2, 'b': 1}
# Example with an empty string:
empty_str = ""
empty_result = count_characters(empty_str)
print(empty_result) # Output: {}

# some other formats


#1
# from collections import Counter
# def count(string):
# return Counter(string)
#2
# def count(string):
# return {i: string.count(i) for i in string}

NAVID SAQIB: +923334259883 8


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A: 2D Arrays
Qno5:

Write a program that performs the following tasks:

1. Create a 2-dimensional array to store ProductName, Qty, Price, and Total


for 3 products.
2. Use a loop to input the data for ProductName, Qty, and Price for each
product.
3. Calculate the Total for each product by multiplying the corresponding Qty
by Price and store the result in the array.
4. Calculate and display the grand total, which is the sum of all Total values for
the products.

Provide the pseudocode or code implementation for this task.

Apply Python code:


data = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
label =["pname","Qty","price","Total"]
gt = 0
for r in range(0,3):
for c in range(0,3):
data[r][c] = input("Enter {add} data: ".format(add= label[c]))
for x in range(0,3):
data[x][3] = int(data[x][1]) * int(data[x][2])
gt = gt + data[x][3]
print("Pname\t","Qty\t","price\t","total")
for row in range(0,3):

NAVID SAQIB: +923334259883 9


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

for col in range(0,4):


print(data[row][col],end= "\t")
print()
print("Grand total : ",gt)

NAVID SAQIB: +923334259883 10


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A: Linear sreach


Qno6:

Write a program that performs the following tasks:

1. Implement a linear search algorithm for a given array containing the


elements: 23, 67, 90, 87, 45, 22.
2. Prompt the user to input an integer value to search for in the array.
3. If the integer is found in the array, display a message indicating that the
data has been found.
4. If the integer is not found in the array, display a message indicating that the
data is not in the list.

Provide the pseudocode or code implementation for this task.

Apply Python code:


item = 0
found = False
d=0
nums = [23, 67, 90, 87, 45, 22]
item = int(input("Enter number to search : "))
for x in range(0, 6):
if item == nums[x]:
found = True
d=x

if found == True:
print("Data found : ", d)
else:
print("Data not in list : ")
NAVID SAQIB: +923334259883 11
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A: 2D Arrays & 1 D Array combination


Qno6a :

Write a program that performs the following tasks:

1. Create a 1-dimensional array to store PatientID and PatientName.


2. Create a 2-dimensional array to hold the following data:
o HeartRate
o Temperature
o HeartRate/Temperature Ratio
o PatientSituation
o Calculate the heartrate/temperature ratio and if ration is greater
than 2.5 write critical in situation otherwise normal
o Dispalay out stating all

Provide the pseudocode or code implementation for this task.

Apply Python code:


# Combining the 1D and 2D Arrays in one program
# Declaring Arrays and assigning values
# 1D Array
pid = [1,2,3]
# 2D Array
pdata = [
["Abu Bakar",251,92,0,0],
["Ahmad Jamil",210,92,0,0],
["Ali Murtaza",190,85,0,0]]

# Printing the data here

NAVID SAQIB: +923334259883 12


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print("Patient ID\t","Patient Name\t","Heart Rate\t","Temperature\t","HRT


Ratio\t","Situation")
# First Loop
for r in range (0,3):
# Printing only 1D Array here
print(pid[r],end="\t")
# Calculating the ratio of 2nd and 3rd column values and placing in 4th column
pdata[r][3] = int(pdata[r][1]) / int(pdata[r][2])
# doing the comparison of ratio in 4th column to determine the patient
situation "Critical" or "Normal"
# And the placing the data in 5th column
if pdata[r][3] > float(2.5):
pdata[r][4] = "Critical"
elif pdata[r][3] < float(2.5):
pdata[r][4] = "Normal"
# Second Loop
for c in range (0,5):
# Printing the 2D Array here
print(pdata[r][c],end = "\t")
print()

NAVID SAQIB: +923334259883 13


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno7:

Write a program that performs the following tasks:

1. Implement a linear search algorithm for a given array containing the


strings: Shahid, Waqas, Waleed, Nosheen, Alina, and Sameen.
2. Prompt the user to input a string value to search for in the array.
3. If the string is found in the array, display a message indicating that the data
has been found.
4. If the string is not found in the array, display a message indicating that the
data is not in the list.

Provide the pseudocode or code implementation for this task.

Apply Python code:


item = 0
found = False
d=0
name = [“shahid”, ”waqas”, “waleed”, “nosheen”, “alina”, “sameen”]
item = input("Enter name to search : ")
for x in range(0, 6):
if item == name[x]:
found = True
d=x

if found == True:
print("Data found : ", d)
else:
print("Data not in list : ")

NAVID SAQIB: +923334259883 14


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno8:

Write a program that performs the following tasks:

1. Implement the Bubble Sort algorithm to sort a given array containing the
integers: 12, 8, 3, 1.
2. Sort the array in ascending order.
3. Display the sorted array.

Provide the pseudocode or code implementation for this task.

Apply Python code:


nums = [12,8,3,1]
temp = 0
for x in range(0,3):
for y in range(0,3):
if nums[x]>nums[x + 1]:
temp = nums[x]
nums[x] = nums[x + 1]
nums[x + 1] = temp
for a in range(0,4):
print(nums[a])

NAVID SAQIB: +923334259883 15


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno9:

Write a program that performs the following tasks:

1. Implement the Bubble Sort algorithm to sort a given array containing the
integers: 12, 8, 3, 1.
2. Provide the user with an option to sort the array either in ascending or
descending order.
3. Display the sorted array based on the user's choice.

Provide the pseudocode or code implementation for this task.

Apply Python code:


nums = [12,8,3,1]
choice =0
temp = 0
choice = input("Enter > for Ascending and < for Descending order : ")
if choice == ">":
for x in range(0,3):
for y in range(0,3):
if nums[x]>nums[x + 1]:
temp = nums[x]
nums[x] = nums[x + 1]
nums[x + 1] = temp
else:
for x in range(0,3):
for y in range(0,3):
if nums[x]<nums[x + 1]:
NAVID SAQIB: +923334259883 16
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

temp = nums[x]
nums[x] = nums[x + 1]
nums[x + 1] = temp
if choice == ">":
print("Acending order : ")
else:
print("Acending order : ")

for a in range(0,4):
print(nums[a])

NAVID SAQIB: +923334259883 17


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno10: Write a program that performs the following tasks:

1. Create a dashboard using arrays to display information about trains,


including:
o Train Names
o In Time
o Out Time
o Destination
o Number of Passengers
o Status
2. Use procedures or functions to:
o Write the train information to a file.
o Read the information back from the file and display it in the program.

Train Name In time Out time destination No of status


passenger
T1 03:15 03:15 Lahore 234 On station
T2 4:50 4:50 Karachi 235 arriving
T3 6:00 6:00 Pindi 234 departed

Create a txt file like that and then apply the given python code
Provide the python code implementation for this task.

NAVID SAQIB: +923334259883 18


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Apply Python code:


# Program for station master
# Declaring Arrays
# Pre-defined Values
train_name = ["T1","T2","T3"]
in_time = ["03:15","4:50","6:00"]
out_time = ["4:00","5:15","7:00"]
destination = ["lahore","karachi","pindi"]
no_of_passenger = ["234","235","234"]
state = ["on station","arriving","depatured"]

# # Taking input from the user


# for x in range (0,3):
# train_name[x] = input("Enter Train Name: ")
# in_time[x] = input("Enter the Arrival time of train: ")
# out_time[x] = input("Enter the Departure time of train: ")
# destination[x] = input("Enter the destination of train: ")
# no_of_passenger[x] = int(input("Enter the number of passengers: "))
# state[x] = input("Enter the train state: ")

# Giving the output


with open("Bill_Board.txt","w") as file:

NAVID SAQIB: +923334259883 19


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

a=
file.write("==========================BillBoard========================
=================")
b = file.write("\n")
c = file.write("Train\tArrival\tDeparture\tDestination\tPassengers\tCurrent
Status")
h = file.write("\n")
for y in range (0,3):
d = file.write("\n")
e=
file.write(f"{train_name[y]}\t{in_time[y]}\t{out_time[y]}\t{destination[y]}\t{no
_of_passenger[y]}\t{state[y]}")
f = file.write("\n")
g=
file.write("==========================================================
=================")
def reading():
with open("Bill_Board.txt","r") as data:
m = data.read()
print(m)
user = input("If you want to read the file, type read: ")
if user == "read":
reading()
else:
print("Error! re-run the programe")

NAVID SAQIB: +923334259883 20


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A : Binary search with iterative method


Qno11: create a binary search based ona give names of string datatype but using
iterative method
"wahab","abu bakar","shahab","ali","saad","ayan","faraz","nawaz","qasim"

Apply Python code:


# Binary search using iterative method on string values
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
# Main code
array = ["wahab","abu
bakar","shahab","ali","saad","ayan","faraz","nawaz","qasim"]
array.sort()
print(array)
x = input("Enter from list to found: ")

NAVID SAQIB: +923334259883 21


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

result = binary_search(array, x)
if result != - 1:
print("Element is present at index:", result)
else:
print("Element is not present in array")

NAVID SAQIB: +923334259883 22


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A : Binary search with iterative method


Qno12:

Write a program that performs the following tasks:

1. Implement a binary search algorithm using recursion to search for an


integer in a given list of numbers.
2. The list of numbers to search through is: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19, 20.
3. Prompt the user to input the integer to search for in the list.
4. Display the result of the search, indicating whether the integer was found
and its position in the list, or that the integer is not in the list.

Provide the pseudocode or code implementation for this task.

# Binary Search using recursive method


def binary_search(array, low, high, x):
if high >= low:
mid = (high + low) // 2
if array[mid] == x:
return mid
elif array[mid] > x:
return binary_search(array, low, mid - 1, x)
else:
return binary_search(array, mid + 1, high, x)
else:
return -1
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

NAVID SAQIB: +923334259883 23


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print(array)
x = int(input("Enter from list to found: "))
result = binary_search(array, 0, len(array)-1, x)
if result != - 1:
print("Element is present at index:", result)
else:
print("Element is not present in array")
Section A : Binary search for strings
Qno13: create a binary search based on give names of string datatype. Using
iterative method

Python Code :
# Binary search using iterative method on string values
def binary_search(arr, target):
low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1

NAVID SAQIB: +923334259883 24


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

# Main code
array = ["wahab","abu
bakar","shahab","ali","saad","ayan","faraz","nawaz","qasim"]
array.sort()
print(array)
x = input("Enter from list to found: ")
result = binary_search(array, x)
if result != - 1:
print("Element is present at index:", result)
else:
print("Element is not present in array")

NAVID SAQIB: +923334259883 25


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A : linearsearch, binary search bubble sort , insertionsort,


Qno13a:

Write a program that performs the following tasks:

1. Implement the following algorithms using functions within a single


program:
o Linear Search
o Binary Search
o Bubble Sort
o Insertion Sort
2. Use the following array for the operations:

data = [74, 12, 53, 89, 37, 68, 5, 92, 20, 46, 61, 18, 80, 3, 97, 42, 64, 9, 55,
27, 76, 34, 70, 58, 14, 48, 86, 24, 7, 99]

3. Ensure that the functions:


o Perform a linear search and return the index of the target value.
o Perform a binary search (after sorting the array) and return the index
of the target value.
o Sort the array using bubble sort.
o Sort the array using insertion sort.
4. Prompt the user to choose a search or sort operation and provide the
necessary inputs (such as the target value for searches).
5. Display the results of the search or sorting operation.

Provide the pseudocode or code implementation for this task.

NAVID SAQIB: +923334259883 26


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Python code:
# Linear search function code
def linear_search(array, item):
found = False
for x in range (0, len(array)):
if item == array[x]:
print(array[x])
found = True
if found == True:
return f"Data found: {found}"
else:
return f"Data not found"

# Bubble sort function code starts here


def bubble_sort(data):
print("Enter choice for order of sorting Ascending(Type:asc) or
Descending(Type:des) ")
choice = str(input("Enter your choice: "))
if choice == "asc":
for e in range(0,len(data)):
for c in range(0,len(data)-1):
if data[c] > data[c+1]:
temp = data[c]
data[c] = data[c+1]

NAVID SAQIB: +923334259883 27


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

data[c+1] = temp
return data

elif choice == "des":


for e in range(0,len(data)):
for c in range(0,len(data)-1):
if data[c] < data[c+1]:
temp = data[c]
data[c] = data[c+1]
data[c+1] = temp
return data

# Insertion sort function


def insertion_sort(data):
for i in range(1, len(data)):
key = data[i]
j=i-1
while j >= 0 and key < data[j]:
data[j + 1] = data[j]
j -= 1
data[j + 1] = key
return data

# Binary search

NAVID SAQIB: +923334259883 28


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

def binary_search(arr, target):


low, high = 0, len(arr) - 1
while low <= high:
mid = (low + high) // 2
mid_val = arr[mid]
if mid_val == target:
return mid # Found the target, return its index
elif mid_val < target:
low = mid + 1 # Target is in the right half
else:
high = mid - 1 # Target is in the left half

return "Data not found" # Target not found in the array

# Main code
data =
[74,12,53,89,37,68,5,92,20,46,61,18,80,3,97,42,64,9,55,27,76,34,70,58,14,48,86,
24,7,99]
print("1.linear search\n",
"2.bubble sort\n",
"3.insertion sort\n",
"4.binary search")
a = int(input("Enter procedure name you want to run:\n"))
if a == 1:

NAVID SAQIB: +923334259883 29


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print("======This is linear search======")


item = int(input("Enter item to found:\n"))
output = linear_search(data,item)
print(output)
elif a == 2:
print("======This is bubble sort======")
output = bubble_sort(data)
print(output)
elif a == 3:
print("======This is Insertion sort======")
output = insertion_sort(data)
print(output)
elif a == 4:
print("======This is Binary Search======")
targ = int(input("Enter item to found:\n"))
output = binary_search(data,targ)

NAVID SAQIB: +923334259883 30


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A : linearsearch, binary search bubble sort , insertionsort,


Qno13a:

Write a program that performs the following tasks:

1. Implement the following algorithms within a single main code block


(without using procedures or functions):
o Linear Search
o Binary Search
o Bubble Sort
o Insertion Sort
2. Use the following array for the operations:

data = [74, 12, 53, 89, 37, 68, 5, 92, 20, 46, 61, 18, 80, 3, 97, 42, 64, 9, 55,
27, 76, 34, 70, 58, 14, 48, 86, 24, 7, 99]

3. Ensure that:
o Linear Search is implemented to find the index of a target value in
the array.
o Binary Search (after sorting the array) is implemented to find the
index of a target value.
o Bubble Sort is implemented to sort the array in ascending order.
o Insertion Sort is implemented to sort the array in ascending order.
4. Include code to prompt the user to choose an operation (search or sort)
and provide the necessary inputs (such as the target value for searches).
5. Display the results of the chosen operation.

Provide the complete code implementation for this task.

Python code :
print("===============This program is running everything as main
code===============")
print("1.linear search\n",
"2.bubble sort\n",
"3.insertion sort\n",
NAVID SAQIB: +923334259883 31
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

"4.binary search")
a = int(input("Enter procedure name you want to run:\n"))
if a == 1:
# linear search in main code
print("This is linear search")
array = [74, 12, 53, 89, 37, 68, 5, 92, 20, 46, 61, 18, 80, 3, 97, 42, 64, 9, 55, 27,
76, 34, 70, 58, 14, 48, 86,
24, 7, 99]
print(f"Data: {array}")
item = int(input("Enter item to found: "))
found = False
for x in range(0, len(array)):
if item == array[x]:
print(array[x])
found = True
if found == True:
print(f"Data found: {found}")
else:
print(f"Data not found")

elif a == 2:
# bubble sort in main code
print("This is bubble sort")

NAVID SAQIB: +923334259883 32


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

data = [74, 12, 53, 89, 37, 68, 5, 92, 20, 46, 61, 18, 80, 3, 97, 42, 64, 9, 55, 27,
76, 34, 70, 58, 14, 48, 86, 24, 7, 99]
print(f"Original Data: {data}")

print("=============================================================
=======================================================")
print("Enter choice for order of sorting Ascending(Type:asc) or
Descending(Type:des) ")
choice = str(input("Enter your choice: "))
# Ascending order
if choice == "asc":
for e in range(0, len(data)):
for c in range(0, len(data) - 1):
if data[c] > data[c + 1]:
temp = data[c]
data[c] = data[c + 1]
data[c + 1] = temp
print(f"Sorted data: {data}")
# Descending Order
elif choice == "des":
for e in range(0, len(data)):
for c in range(0, len(data) - 1):
if data[c] < data[c + 1]:
temp = data[c]
data[c] = data[c + 1]

NAVID SAQIB: +923334259883 33


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

data[c + 1] = temp
print(f"Sorted data: {data}")

elif a == 3:
# Insertion sort
print("This is Insertion sort")
data = [74, 12, 53, 89, 37, 68, 5, 92, 20, 46, 61, 18, 80, 3, 97, 42, 64, 9, 55, 27,
76, 34, 70, 58, 14, 48, 86, 24,
7, 99]
print(f"Original data: {data}")

print("=============================================================
======================================================")
for i in range(1, len(data)):
key = data[i]
j=i-1
while j >= 0 and key < data[j]:
data[j + 1] = data[j]
j -= 1
data[j + 1] = key
print(f"Sorted data: {data}")

elif a == 4:
# Binary search
print("This is Binary Search")
NAVID SAQIB: +923334259883 34
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

arr = [74, 12, 53, 89, 37, 68, 5, 92, 20, 46, 61, 18, 80, 3, 97, 42, 64, 9, 55, 27, 76,
34, 70, 58, 14, 48, 86, 24,
7, 99]
print(f"Data: {arr}")
target = int(input("Enter value to found:\n"))
low, high = 0, len(arr) - 1

while low <= high:


mid = (low + high) // 2
mid_val = arr[mid]

if mid_val == target:
print(mid) # Found the target, return its index
elif mid_val < target:
low = mid + 1 # Target is in the right half
else:
high = mid - 1 # Target is in the left half

print("Data not found") # Target not found in the array

NAVID SAQIB: +923334259883 35


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno14:

Write a program that performs the following tasks:

1. Prompt the user to input a number.


2. Reverse the digits of the input number.
3. Display the reversed number.

Provide the python code implementation for this task.

Python code:
number = int(input("Enter the integer number: "))

revs_number = 0

while (number > 0):


remainder = number % 10
revs_number = (revs_number * 10) + remainder
number = number // 10

print("The reverse number is :" ,revs_number)

NAVID SAQIB: +923334259883 36


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Qno 14a:

Write a program that implements a Rock, Paper, Scissors game with the following
requirements:

1. Use IF, THEN, ELSE, and ENDIF constructs to handle game logic and decision-
making.
2. Use a WHILE loop to allow the user to play multiple rounds of the game until
they choose to exit.
3. Implement procedures (or functions) to:
o Take user input for their choice (Rock, Paper, or Scissors).
o Generate a random choice for the computer.
o Determine the winner of each round based on the rules of Rock, Paper,
Scissors.
o Display the result of each round.

Provide the Python code implementation for this task.

Python code:
import random
def menu():
print("1: Rock")
print("2: Paper")
print("3: Scissor")
def identify(choice):
item = None
if choice == 1:
item = 'Rock'
elif choice == 2:
item = 'Paper'
elif choice == 3:
NAVID SAQIB: +923334259883 37
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

item = 'Scissor'
else:
print("Error")
return item
def procedure(n):
list = ['Rock', 'Paper', 'Scissor']
r = random.choice(list)
if r == n:
print("You chose: ",n)
print("Computer chose: ",r)
print("Draw")
elif r == 'Rock' and n == 'Paper':
print("You chose: ",n)
print("Computer chose: ",r)
print("You win")
elif r == 'Rock' and n == 'Scissor':
print("You chose: ",n)
print("Computer chose: ",r)
print("Computer wins")
elif r == 'Paper' and n == 'Rock':
print("You chose: ",n)
print("Computer chose: ",r)
print("Computer wins")
elif r == 'Paper' and n == 'Scissor':

NAVID SAQIB: +923334259883 38


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print("You chose: ",n)


print("Computer chose: ",r)
print("You win")
elif r == 'Scissor' and n == 'Rock':
print("You chose: ",n)
print("Computer chose: ",r)
print("You win")
elif r == 'Scissor' and n == 'Paper':
print("You chose: ",n)
print("Computer chose: ",r)
print("Computer wins")
def run():
while True:
menu()
choice = int(input("Enter your choice as 1,2 or 3: "))
a = identify(choice)
procedure(a)
# Main Code :)
run()

NAVID SAQIB: +923334259883 39


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Stacks
Qno15:

Write a program that performs the following tasks:

1. Implement a stack data structure with the following procedures:


o PUSH: Adds an element to the top of the stack.
o POP: Removes and returns the element from the top of the stack.
2. Include a procedure to perform a linear search within the stack to find a
specified element.
3. Demonstrate the use of these procedures by:
o Pushing elements onto the stack.
o Popping elements from the stack.
o Performing a linear search to find a specific element in the stack.

Provide the Python code implementation for this task.

Python Code:
stack = [None for index in range(0,10)]
base_pointer = 0
top_pointer = -1
full_stack = 10
item = None
def linear_search(Value):
global stack
found = False
for x in range (0, len(stack)-1):
if stack[x] == Value:
found = True
return found

NAVID SAQIB: +923334259883 40


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

def pop():
global top_pointer, base_pointer, item
if top_pointer == base_pointer -1:
print("Stack is empty, cannot pop")
else:
stack[top_pointer] = None
top_pointer = top_pointer -1
def push(item):
global top_pointer
if top_pointer < full_stack - 1:
top_pointer = top_pointer + 1
stack[top_pointer] = item
else:
print("Stack is full, cannot push")
push(23)
push(34)
push(12)
push(56)
push(90)
push(67)
pop()
print(stack)
a = int(input("Enter item to found: "))

NAVID SAQIB: +923334259883 41


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

b = linear_search(a)
if b == True:
print(b, "Data present in array")
else:
print("Data not found")
Section B: Queues
Qno16: create Queues procedure of ENQUEUE and DEQUEUE in a stated Queue
of 10 elements
Python Code:
queue = [None for index in range(0, 10)]
frontPointer = 0
rearPointer = -1
queueFull = 10
queueLength = 0
def enQueue(item):
global queueLength, rearPointer
if queueLength < queueFull:
if rearPointer < len(queue) - 1:
rearPointer = rearPointer + 1
else:
rearPointer = 0
queueLength = queueLength + 1
queue[rearPointer] = item
else:

NAVID SAQIB: +923334259883 42


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print("Queue is full, cannot enqueue")


def deQueue():
global queueLength, frontPointer, item
if queueLength == 0:
print("Queue is empty,cannot dequeue")
else:
item = queue[frontPointer]
if frontPointer == len(queue) - 1:
frontPointer = 0
else:
frontPointer = frontPointer + 1
queueLength = queueLength - 1
# Main Code
enQueue(50)
enQueue(40)
enQueue(12)
enQueue(35)
for x in range(0, 10):
print(queue[x])

NAVID SAQIB: +923334259883 43


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Handling Records


Qno17:

Write a program that performs the following tasks:

1. Create a class named Car that handles the following attributes:


o CarID
o CarName
o CarModel
o CarPrice
2. Implement methods within the class to:
o Set and get the values of these attributes.
o Display the car record.
3. Demonstrate the use of the Car class by creating an instance of the class,
setting its attributes, and displaying the car record.

Provide the python code implementation for this task.

Python Model:
class car():
carid = [0,0,0,0]
carname = [0,0,0,0]
carmodel = [0,0,0,0]
carprice = [0,0,0,0]
a = car()
for x in range(0,4):
a.carid[x] = input("Enter car identification number: ")
a.carname[x] = input("Enter car's name: ")
a.carmodel[x] = input("Enter car's model: ")
a.carprice[x] = input("Enter car's price; ")

NAVID SAQIB: +923334259883 44


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print("Car id\t","Car Name\t","Car Model\t","Car Price\t")


for y in range(0,4):
print(a.carid[y],"\t",a.carname[y],"\t",a.carmodel[y],"\t",a.carprice[y])

NAVID SAQIB: +923334259883 45


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Linked List


Qno18:

Write a program that performs the following tasks:

1. Create a linked list with 12 nodes initially set to None.


2. Load the linked list with the following values: 27, 19, 36, 42, 16.
3. Implement functionality to:
o Insert new data into the linked list.
o Delete data from the linked list.
4. Maintain an array to store and display the pointers (or references) to the
nodes in the linked list.
5. Demonstrate the operations by:
o Inserting additional data into the linked list.
o Deleting specified data from the linked list.
o Displaying the updated list and the pointers.

Provide the python code implementation for this task.

Python code:
myLinkedList = [27, 19, 36, 42, 16, None, None, None, None, None, None, None]
myLinkedListPointers = [-1, 0, 1, 2, 3 ,6 ,7 ,8 ,9 ,10 ,11, -1]
startPointer = 4
nullPointer = -1
heapStartPointer = 5
def insert(itemAdd):
global startPointer, heapStartPointer
if heapStartPointer == nullPointer:
print("Linked List full")
else:
tempPointer = startPointer
NAVID SAQIB: +923334259883 46
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

startPointer = heapStartPointer
heapStartPointer = myLinkedListPointers[heapStartPointer]
myLinkedList[startPointer] = itemAdd
myLinkedListPointers[startPointer] = tempPointer
def delete(itemDelete):
global startPointer, heapStartPointer
if startPointer == nullPointer:
print("Linked List empty")
else:
oldindex = 0
index = startPointer
while myLinkedList[index] != itemDelete and index != nullPointer:
oldindex = index
index = myLinkedListPointers[index]
if index == nullPointer:
print("Item ", itemDelete, " not found")
else:
myLinkedList[index] = None
tempPointer = myLinkedListPointers[index]
myLinkedListPointers[index] = heapStartPointer
heapStartPointer = index
myLinkedListPointers[oldindex] = tempPointer
insert(23)
insert(234)

NAVID SAQIB: +923334259883 47


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

insert(34)
for x in range(0,len(myLinkedList)):
print(myLinkedList[x])

NAVID SAQIB: +923334259883 48


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: circular LinkedList


Qno19:

Write a program that performs the following tasks:

1. Create a circular linked list using two classes:


o Node: Represents a node in the circular linked list, with attributes for
storing data and a pointer to the next node.
o CircularLinkedList: Manages the circular linked list, including methods
to insert nodes and maintain the circular structure.
2. Implement a method in the CircularLinkedList class to display the elements
of the circular linked list.
3. Demonstrate the use of the CircularLinkedList class by:
o Creating an instance of the circular linked list.
o Inserting nodes into the circular linked list.
o Displaying the contents of the circular linked list using the display
method.

Provide the python code implementation for this task.

Python Code:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:

NAVID SAQIB: +923334259883 49


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

self.head = new_node
self.head.next = self.head
else:
temp = self.head
while temp.next != self.head:
temp = temp.next
temp.next = new_node
new_node.next = self.head
def display(self):
if not self.head:
print("List is empty")
return
temp = self.head
while True:
print(temp.data, end=" ")
temp = temp.next
if temp == self.head:
break
print()
# Example usage:
if __name__ == "__main__":
circular_list = CircularLinkedList()
# Appending elements to the circular linked list
circular_list.append(1)

NAVID SAQIB: +923334259883 50


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

circular_list.append(2)
circular_list.append(3)
circular_list.append(4)
# Displaying the circular linked list
print("Circular Linked List:")
circular_list.display()

NAVID SAQIB: +923334259883 51


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Object Oriented Programming : Constructor


Qno20:

Write a program that performs the following tasks:

1. Create a class named NavidSaqib.


2. Implement a constructor for the NavidSaqib class that initializes a variable
named locker.
3. Define a method named getAmount in the NavidSaqib class to display the
value of the locker variable.
4. Demonstrate the use of the NavidSaqib class by:
o Creating an instance of the class.
o Assigning a value to the locker variable through the constructor.
o Calling the getAmount method to display the value of the locker
variable.

Provide the python code implementation for this task

Python Code:
class navidsaqib():
#attribute - constructor
def __init__(self,locker):
self.locker = locker
#methods
#function get amount
def __str__(self):
return f"{self.locker}"
#main Code - Object Calling
p = navidsaqib(30000)
p.setlocker = 40000

NAVID SAQIB: +923334259883 52


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print(p)

NAVID SAQIB: +923334259883 53


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Object Oriented Programming : super class


Qno21:

Write a program that performs the following tasks:

1. Create a class named Creature.


2. Implement a constructor for the Creature class that initializes a variable
named animal.
3. Define a method named getAmount in the Creature class to display the
value of the animal variable.
4. Demonstrate the use of the Creature class by:
o Creating an instance of the class.
o Assigning a value to the animal variable through the constructor.
o Calling the getAmount method to display the value of the animal
variable.

Provide the pyton code implementation for this task.

class creature():
ctype = "earth" # attribute
#method- Constructor
def __init__(self,animal,breed,color,age):
self.animal = animal
self.breed = breed
self.color = color
self.age = age
roni = creature("dog","pug","brown",5)
pezo = creature("dog","bulldog","black",7)
mithu = creature("bird","parrot","green",2)

NAVID SAQIB: +923334259883 54


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

print("roni details : ")


print("Roni lives on :",creature.ctype)
print("roni is a ",roni.animal)
print("Breed : ",roni.breed)
print("Color : ",roni.color)
print("Age : ",roni.age)
print()
print("pezo details : ")
print("pezo lives on :",creature.ctype)
print("pezo is a ",pezo.animal)
print("Breed : ",pezo.breed)
print("Color : ",pezo.color)
print("Age : ",pezo.age)
print()
print("mithu details : ")
print("mithu lives on :",creature.ctype)
print("mithu is a ",mithu.animal)
print("Breed : ",mithu.breed)
print("Color : ",mithu.color)
print("Age : ",mithu.age)

NAVID SAQIB: +923334259883 55


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Object Oriented Programming


Qno22:

Write a program that performs the following tasks:

1. Create a class named Racing.


2. Implement a constructor for the Racing class that initializes a variable
named tank.
3. Define two methods in the Racing class:
o fueling: To add fuel to the tank.
o consumption: To reduce the tank level based on fuel consumption.
4. Create two objects of the Racing class, named Mehran and Vitz.
5. Assign and display the consumption values for both Mehran and Vitz.
6. Display the tank status for both Mehran and Vitz.

Provide the python code implementation for this task.

Python code :
class racing():
def __init__(self,tank):
self.tank = tank
def fueling(self,n):
self.tank = self.tank + n
def consumption(self,n):
self.tank = self.tank - n
#mainCode
mehran = racing(40)
vitz = racing(30)
print("mehran tank : ",mehran.tank)
print("vitz tank : ",vitz.tank)

NAVID SAQIB: +923334259883 56


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

for x in range(0,10):
mehran.consumption(1)
vitz.consumption(0.5)
print("vitz tank : ", vitz.tank)
print("mehran tank : ",mehran.tank)

NAVID SAQIB: +923334259883 57


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Object Oriented Programming


Qno23:

Write a program that performs the following tasks:

1. Create a class named Employee.


2. Implement a constructor for the Employee class that initializes the
following variables:
o name
o salary
o role
3. Define two methods in the Employee class:
o changeLeaves: To update or manage the leave balance.
o fromDash: To perform or display information related to the
dashboard.
4. Create two objects of the Employee class, named Mehran and Vitz.
5. Assign appropriate values to name, salary, and role for both Mehran and
Vitz.
6. Display the values of the name, salary, and role for both Mehran and Vitz.

Provide the python code implementation for this task.

Python code:
class Employee:
no_of_leaves = 9
def __init__(self, aname, asalary, arole):
self.name = aname
self.salry = asalary
self.role = arole
@classmethod
def change_leaves(cls, newleaves):
cls.no_of_leaves = newleaves
NAVID SAQIB: +923334259883 58
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

@classmethod
def from_dash(cls, string):
items = string.split("-")
print(items)
return cls(items[0], int(items[1]), items[2])
wahab = Employee("Wahab", 234, "Manager")
ali = Employee.from_dash("Ali-342-Student")
Employee.change_leaves(34)
print(wahab.no_of_leaves)
print(ali.__dict__)
Section B: Object Oriented Programming (single inheritance)
Qno24:

Write a program that performs the following tasks:

1. Create a base class named Parent.


2. Implement a method named func1 in the Parent class that displays the
message: "This function is in the parent class."
3. Create a child class named Child that inherits from the Parent class.
4. Implement a method named func2 in the Child class that displays the
message: "This function is in the child class."
5. Create an object named t of the Child class.
6. Use the object t to call and execute both func1 and func2.

Provide the python code implementation for this task

Python code:
# Python program to demonstrate
# Single inheritance
# Base class
NAVID SAQIB: +923334259883 59
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

class Parent:
# Methods
def func1(self):
print("This function is in parent class.")
# Derived/sub/child class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Mian Code
t = Child()
t.func1()
t.func2()

NAVID SAQIB: +923334259883 60


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Object Oriented Programming (multi inheritance)


Qno25:

Write a program that performs the following tasks:

1. Create two base classes named Father and Mother.


o In the Father class, implement a method named fatherName to
display the father's name.
o In the Mother class, implement a method named motherName to
display the mother's name.
2. Create a derived class named Son that inherits from both Father and
Mother.
o In the Son class, implement a method named displayNames to
display the names of both the father and the mother.
3. Demonstrate the use of the Son class by creating an object of the Son class
and calling the displayNames method to show the names of both parents.

Provide the python code implementation for this task

# Pyhton code
# multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
NAVID SAQIB: +923334259883 61
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Main Code
s1 = Son()
s1.fathername = "akhter"
s1.mothername = "sabeen"
s1.parents()

NAVID SAQIB: +923334259883 62


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: Object Oriented Programming (Hierarchal inheritance)


Qno26:

Write a program that performs the following tasks:

1. Create a base class named Parent with an attribute for hairColor, which is
set to "black."
2. Create a derived class named Child1 that inherits from the Parent class.
o Add an attribute to the Child1 class for eyeColor, which is set to
"blue."
3. Create another derived class named Child2 that also inherits from the
Parent class.
o Add an attribute to the Child2 class for eyeColor, which is set to
"grey."
4. Ensure that both Child1 and Child2 inherit the hairColor attribute from the
Parent class, which is "black."
5. Demonstrate the use of these classes by creating objects of Child1 and
Child2, and display the attributes for both objects to show that both
children have black hair, while Child1 has blue eyes and Child2 has grey
eyes.

Provide the python code implementation for this task.

Python code:
# Hierarichal inheritance
class Parent: # Base class
def func1(self):
print("Hair color: Black.")
# Derived class1
class Child1(Parent):
def func2(self):
print("Child 1 - eyecolor : Blue.")

NAVID SAQIB: +923334259883 63


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

# Derived class2
class Child2(Parent):
def func3(self):
print("Child 2 - eyecolor : grey.")
# Main Code
ali = Child1()
shahid = Child2()
ali.func1()
ali.func2()
shahid.func1()
shahid.func3()
Section B: Object Oriented Programming : (Record processing using file)
Qno28: If a sequential file was required, then the student records would need
to be input into an array of records first, then sorted on the key field
registerNumber, before the array of records was written to the file.
Pyhton code:
import pickle
class student:
def __init __(self):
self.name = ""
self.registerNumber = 0
self.dateOfBirth = datetime.datetime.now()
self.fullTime = True
studentRecord = student()

NAVID SAQIB: +923334259883 64


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

studentFile = open('students.DAT','w+b')
print("Please enter student details")
studentRecord.name = input("Please enter student name ")
studentRecord.registerNumber = int(input("Please enter student's register
number "))
year = int(input("Please enter student's year of birth YYYY "))
month = int(input("Please enter student's month of birth MM "))
day = int(input("Please enter student's day of birth DD "))
studentRecord.dateOfBirth = datetime.datetime(year, month, day)
studentRecord.fullTime = bool(input("Please enter True for full-time or False for
part-time "))
pickle.dump (studentRecord, studentFile)
print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth,
studentRecord.fullTime)
studentFile.close()
studentFile = open('students.DAT','rb')
studentRecord = pickle.load(studentFile)
print(studentRecord.name, studentRecord.registerNumber,
studentRecord.dateOfBirth,
studentRecord.fullTime)
studentFile.close()

NAVID SAQIB: +923334259883 65


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section B: error handling/exceptional Handling


Qno29:

Write a program that performs the following tasks:

1. Implement exception handling to manage errors when the user inputs data.
2. Specifically, if the user enters the character "w" instead of a number, the
program should trigger and handle an exception.
3. Ensure that the exception handling mechanism provides a clear and
informative message to the user when the invalid input is detected.

Provide the python code implementation for this task.

Python code:
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")

NAVID SAQIB: +923334259883 66


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

Section A: error handling/exceptional Handling


Qno28:

Write a program that performs the following tasks:

1. Implement exception handling to manage errors that occur during division


operations.
2. Specifically, handle the case where division by zero is attempted, and display
an appropriate error message.
3. If the division is valid (i.e., the denominator is not zero), the program should
perform the division and display the result.

Provide the python code implementation for this task.

def divide(x, y):


try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("executing finally clause")
divide(10,0)
divide(10,2)

NAVID SAQIB: +923334259883 67


CHEAT CODE BOOKLET COMPUTER SCIENCE-9618

using other exceptions


division by zero
10 * (1/0)
ZeroDivisionError:

NameError
4 + spam*3
NameError: name 'spam' is not defined

TypeError:
'2' + 2
TypeError: can only concatenate str (not "int") to str

NAVID SAQIB: +923334259883 68

You might also like