Cheat Code Booklet For Alevel P4-Python New
Cheat Code Booklet For Alevel P4-Python New
Computer Science-9618
A level – P4 9618 : Python based as per syllabus 2023-2025
Section A: 1D Array
Qno1:
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.
Qno2:
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])
Qno3:
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)
Qno4:
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.
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)
Qno4a:
# 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:
Section A: 2D Arrays
Qno5:
if found == True:
print("Data found : ", d)
else:
print("Data not in list : ")
NAVID SAQIB: +923334259883 11
CHEAT CODE BOOKLET COMPUTER SCIENCE-9618
Qno7:
if found == True:
print("Data found : ", d)
else:
print("Data not in list : ")
Qno8:
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.
Qno9:
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.
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])
Create a txt file like that and then apply the given python code
Provide the python code implementation for this task.
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")
result = binary_search(array, x)
if result != - 1:
print("Element is present at index:", result)
else:
print("Element is not present in array")
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
# 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")
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]
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"
data[c+1] = temp
return data
# Binary search
# 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:
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.
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")
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]
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
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
Qno14:
Python code:
number = int(input("Enter the integer number: "))
revs_number = 0
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.
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':
Section B: Stacks
Qno15:
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
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: "))
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:
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; ")
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)
insert(34)
for x in range(0,len(myLinkedList)):
print(myLinkedList[x])
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:
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)
circular_list.append(2)
circular_list.append(3)
circular_list.append(4)
# Displaying the circular linked list
print("Circular Linked List:")
circular_list.display()
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
print(p)
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)
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)
for x in range(0,10):
mehran.consumption(1)
vitz.consumption(0.5)
print("vitz tank : ", vitz.tank)
print("mehran tank : ",mehran.tank)
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:
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()
# 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()
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.
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.")
# 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()
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()
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.
Python code:
while True:
try:
x = int(input("Please enter a number: "))
break
except ValueError:
print("Oops! That was no valid number. Try again...")
NameError
4 + spam*3
NameError: name 'spam' is not defined
TypeError:
'2' + 2
TypeError: can only concatenate str (not "int") to str