Professional Documents
Culture Documents
Python Class Codes (Recovered)
Python Class Codes (Recovered)
Python Comments
#This is a comment
print("Hello, World!") #This is a comment
Creating Variables
Python has no command for declaring a variable.
Variables in Python
x = 5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even
change type after they have been set.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Global Variables
Variables that are created outside of a function (as in all of the examples above)
are known as global variables.
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
If you create a variable with the same name inside a function, this variable will
be local, and can only be used inside the function. The global variable with the
same name will remain as it was, global and with the original value.
Random Number
Python does not have a random() function to make a random number, but Python
has a built-in module called random that can be used to make random numbers:
Generating Random number
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
However, Python does not have a character data type, a single character is
simply a string with a length of 1.
Example
Get the character at position 1 (remember that the first character has the
position 0):
a = "Hello, World!"
print(a[1])
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part
of the string.
MID Function
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[:5])
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example
Get the characters:
b = "Hello, World!"
print(b[-5:-2])
a = "Hello, World!"
print(a.upper())
a = "Hello, World!"
print(a.lower())
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Logical Operators
Logical operators are used to combine conditional statements:
not Reverse the result, returns False if the not(x < 5 and x
result is true < 10)
Creating an ARRAY
Create a List/Array:
Example
Return the third, fourth, and fifth item:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
Note: The search will start at index 2 (included) and end at index 5 (not
included).
Example
Using the append() method to append an item:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
IF THEN ELSE
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Nested If
You can have if statements inside if statements, this is
called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Example
Using the start parameter:
Example
Increment the sequence with 3 (default is 1):
Creating a Function
In Python a function is defined using the def keyword:
Example
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You
can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the
function is called, we pass along a first name, which is used inside the function
to print the full name:
Example
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
E.g. if you send a List as an argument, it will still be a List when it reaches the
function:
my_function(fruits)
Create a Class
To create a class, use the keyword class:
Creating a CLASS
Create a class named MyClass, with a property named x:
class MyClass:
x = 5
All classes have a function called init (), which is always executed when the
class is being initiated.
class Person:
def init (self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Note: The init () function is called automatically every time the class is
being used to create a new object.
Object Methods
Objects can also contain methods. Methods in objects are functions that belong
to the object.
Example
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def init (self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Note: The self parameter is a reference to the current instance of the class,
and is used to access variables that belong to the class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived
class.
Inheritance Example
Create a class named Person, with firstname and lastname properties, and
a printname method:
class Person:
def init (self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
#Use the Person class to create an object, and then execute the printname
method:
x = Person("John", "Doe")
x.printname()
Declaring Attributes as PRIVATE
class Person:
def init (self, fname, lname):
self. firstname = fname
self. lastname = lname
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties
or methods to the class.
Now the Student class has the same properties and methods as the Person
class.
Example
Use the Student class to create an object, and then execute
the printname method:
x = Student("Mike", "Olsen")
x.printname()
Note: The init () function is called automatically every time the class is
being used to create a new object.
Example
Add the init () function to the Student class:
class Student(Person):
def init (self, fname, lname):
#add properties etc.
When you add the init () function, the child class will no longer inherit the
parent's init () function.
To keep the inheritance of the parent's init () function, add a call to the
parent's init () function:
Example
class Student(Person):
def init (self, fname, lname):
Person. init (self, fname, lname)
Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and
generate an error message.
Exception Code
The try block will generate an exception, because x is not defined:
try:
print(x)
except:
print("An exception occurred")
Since the try block raises an error, the except block will be executed.
Without the try block, the program will crash and raise an error:
Example
This statement will raise an error, because x is not defined:
print(x)
Example
Print one message if the try block raises a NameError and another for other
errors:
try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
File Handling
The key function for working with files in Python is the open() function.
"r" - Read - Default value. Opens a file for reading, error if the file does not
exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
Example
f = open("demofile.txt", "r")
print(f.read())
Read Lines
You can return one line by using the readline() method:
Reading a Line from File
Read one line of the file:
f = open("demofile.txt", "r")
print(f.readline())
By calling readline() two times, you can read the two first lines:
Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finish with it:
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Note: You should always close your files, in some cases, due to buffering,
changes made to a file may not show until you close the file.
Example
Open the file "demofile2.txt" and append content to the file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
Create a New
File
To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
self. age =
age def
grettunranmsee(lsf.elf)n: ame
Random Files
import pickle
class record:
def init (self,name,age):
self.name = name
self.age = age
student = [record("MAK",12),record("zaki",34),record("mino",33)]
pickle.dump(student[0],studentfile)
pickle.dump(student[1],studentfile)
pickle.dump(student[2],studentfile)
studentfile.close()
readfile = open('cedarfile.dat','r+b')
newstudent = []
for x in range(3):
newstudent.append(pickle.load(readfile))
print(newstudent[2].name)
import pickle
class record:
self.name = name
self.age = age
self.grno = grno
student = [record("mak",23,10),record("zaki",34,11),record("shah",55,23)]
f = open('randomfile.dat', 'w+b')
address = hash(student[1].grno)
f.seek(address)
pickle.dump(student[1],f)
f.close()
newstudent = record("",0,0)
f = open('randomfile.dat', 'rb')
address = hash(11)
f.seek(address)
newstudent = pickle.load(f)
print(newstudent.name)
print(Output)
while len(username) != 3:
newfile = open('newhighscore','w')
for x in range(10):
newfile.writelines(FileData[x][0] + "\n")
newfile.writelines(FileData[x][1] + "\n")
newfile.close()
WriteTopTen()
#Bubble Sort
mylist = [23,1,20,15,100,18,19]
print(mylist)
ub = len(mylist)
swap = True
while swap == True and ub > 0:
swap = False
for index in
range(ub - 1):
if mylist[index] > mylist[index+1]:
temp = mylist[index]
mylist[index] = mylist[index +
1]
mylist[index + 1 ] = temp
swap = True
ub = ub - 1
print(mylist)
Linear Search
#String manipulation
name = "Muhammad Ali Khan"
x = len*name) # Calculating number of characters in string
print( name[:]) # all characters
print(name[9:12])
print(name[:12])
print(name[9:])
print(name[0:2])
print(name[:4])
print(name[9:])
#Count number of characters A and S in a
name numa = 0
nums = 0
name = input("Enter Your name ")
for x in range(len(name)):
if name[x] == "a":
numa = numa
+ 1 elif name[x] ==
nums = nums +
1"s":
print("Number of a characters = ", numa)
print("Number of s Characters = ", nums)
stack = [0] * 10
topofstack = -1
stackfull = 10
freepointer = 0
print(stack)
def push(item):
global topofstack , stack , stackfull
if topofstack <stackfull - 1:
topofstack = topofstack + 1
stack[topofstack] = item
else:
print("Stack is full ")
def enQueue(item):
global queuelength ,
endofqueue if queuelength <
queuefull:
if endofqueue < len(queue) -
1: endofqueue = endofqueue
+1
else:
endofqueue = 0
queuelength = queuelength +
1 queue[endofqueue] = item
else:
print("Queue is FULL
") enQueue("MAK")
print(queue)
def deQueue():
global queuelength , frontpointer ,
item if queuelength == 0:
print("Queue is Empty
") else:
queue[frontpointer] = None
frontpointer = frontpointer +
1
queuelength = queuelength -1
deQueue()
deQueue()
print(queue)
#Linked List
mylist = [None] * 10 mylistpointer =
[None] * 10 freeP = 0
startP = -1
for x in range(10):
mylistpointer[x] = x +
1
mylistpointer[9] = -1
mylist = [27,19,36,None,None]
mylistpointer = [-1,0,1,4,5]
startpointer = 2
nullpointer = -1
def find(item):
found = False
itempointer = startpointer
while itempointer != nullpointer and found ==
Falseif: mylist[itempointer]
== item:
found = True
else: itempointer =
mylistpointer[itempointer] return
itempointer
print(find(27))
def insert(item):
global startP , freeP , mylistpointer , mylist
if freeP == -1:
print("Linked list is
full") else:
tempP = startP
startP = freeP
freeP = mylistpointer[freeP]
mylist[startP] = item
mylistpointer[startP] = tempP
print(mylist)
insert(23)
insert(40)
insert(41)
print(mylist)
#Deleting an item from Linked List
def delete(itemdelete):
global startP , freeP
if startP == -1:
print("list is empty
") else:
index = startP
while mylist[index] != itemdelete and
index != -1:
oldindex = index
index = mylistpointer[index]
if index == -1:
print("item not found")
else: mylist[index] = None
temp = mylistpointer[index]
mylistpointer[index] = freeP
freeP = index
mylistpointer[oldindex] =
temp
#Object Oriented Programming
class college:
def __init__(self, name,
age): self.__name = name
self.__age = age
def getname(self):
return self.__name
class
section(college):
def __int__(self,name,age):
college.__init__(self,name,ag
e)
group1 =
section("mak",44)
print(group1.getname())
p1 = college("MAK",
36)
print(p1.getname())
#Polyporphism
class Shape:
def __init__(self,
name): self.name =
name
def area(self):
pass
def shapename(self):
print(self.name)
class Square(Shape):
def __init__(self, length):
Shape.__init__(self,"Square"
) self.length = length
def area(self):
return self.length**2
class Circle(Shape):
def __init__(self,radius):
Shape.__init__(self,"Circle
") self.radius = radius
student =
[record("MAK",12),record("zaki",34),record("mino",33)]
studentfile = open('cedarfile.dat', 'w+b')
pickle.dump(student[0],studentfile)
pickle.dump(student[1],studentfile)
pickle.dump(student[2],studentfile)
studentfile.close()
readfile =
open('cedarfile.dat','r+b')
newstudent = []
for x in range(3):
newstudent.append(pickle.load(readfile))
print(newstudent[2].name)
import pickle
class record:
def __init__(self, name, age, grno):
self.name =
name self.age =
age self.grno =
grno
student =
[record("mak",23,10),record("zaki",34,11),record("shah",55,23)] f =
open('randomfile.dat', 'w+b')
address =
hash(student[1].grno)
f.seek(address)
pickle.dump(student[1],f)
f.close()
newstudent = record("",0,0)
f = open('randomfile.dat',
'rb') address = hash(11)
f.seek(address)
newstudent =
pickle.load(f)
print(newstudent.name)
#MJ21P4
class TreasureChest:
def
__init__(self,questionP,answerP,pointP):
self.__question = questionP
self.__answer =
answerP self.__point =
pointP
def getQuest(self):
return
self.__question def
checkans(self,ans):
if ans == self.__answer:
return True
else:
return False
def getpoints(self,attempts):
if attempts == 1:
return
self.__point elif
attempts == 2:
return self.__point//2
arrayTreasure = []
def readData():
f = open('TreasureChestData.txt','r')
dataquest = f.readline()
while dataquest != "":
dataans = int(f.readline())
datapoints = int(f.readline())
arrayTreasure.append(TreasureChest(dataquest,dataans,datapoints))
dataquest = f.readline()
f.close()
readData()
return num
#open a text file for reading TreasureChestData
#store all data from text file in an array called Regatta
#print array , index by index
file = open('TreasureChestData.txt','r')
line = file.readline()
Regatta = []
while line !=
"":
Regatta.append(line)
line = file.readline()
file.close()
for x in range(len(Regatta)):
print(Regatta[x])
print(Highbrow("Azaaan"))
#Copy All data from text file into an array and display the Array index by index
file = open('TreasureChestData.txt','r')
line = file.readline()
Cedar = []
while line !=
"":
Cedar.append(line)
line = file.readline()
file.close()
for x in range(len(Cedar)): print(Cedar[x])
#create a procedure called Value that will ask
user #name age and marks
#store them in a text file called Test.txt
def Value():
name = input("Enter your Name")
age = int(input("Enter your Age"))
marks = int(input("Enter Marks "))
file = open('Test.txt','w')
file.writelines(name + '\n')
file.writelines(str(age) + '\n')
file.writelines(str(marks)+ '\n')
file.close()
Value()
#MayJune2022P4Question1
FileData = [[""] *2 for i in range(11)] #string
def ReadHighScores():
Filename = "HighScore.txt"
File = open(Filename, 'r')
for x in range(0, 10):
FileData[x][0] = File.readline().strip()
FileData[x][1] = File.readline()
File.close
def OutputHighScores ():
for x in range(0, 10):
Output = FileData[x][0] + " " + FileData[x][1]
print(Output)
ReadHighScores()
print(str(ArrayNodes[RootNode][1]))
if ArrayNodes[RootNode][2] != -1:
InOrder(ArrayNodes[RootNode][2])
def PreOrder(RootNode):
print(str(ArrayNodes[RootNode][1]))
if ArrayNodes[RootNode][0] != -1:
PreOrder(ArrayNodes[RootNode][0])
if ArrayNodes[RootNode][2] != -1:
PreOrder(ArrayNodes[RootNode][2])
#Binary Search using Recursion
Python
def recursiveBinarySearch(lowerbound, upperbound, searchValue):
mid = lowerbound + int((upperbound - lowerbound)/2) if upperbound <
lowerbound:
return -1
else:
if Array[mid] < searchValue:
return recursiveBinarySearch(mid + 1, upperbound,
searchValue)
elif Array[mid] > searchValue:
return recursiveBinarySearch(lowerbound, mid - 1,
searchValue)
else:
return mid
#Insertion SORT Code
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
return arr
class TreeNode:
def init (self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right