Python Programming Basics Guide
Python Programming Basics Guide
Any software where you can code the source code (English like code-high level language) and it assists
with decoding of the source code into object code.
Data Storage :
1. Constants (That may not change within the program) e.g., pi=3.1416
2. Variables (That may change within the program, mostly the values taken from the user)
Data Types:
Python can automatically select data types, but it is a good approach to mention the data types.
NOTE : If you are taking data from the user, and you have not mentioned a data type, string data type
will be selected as default.
1. String
a) Alphabets (haseeb)
b) Alphabets + numbers (haseeb123)
c) Alphabets + numbers + symbols (haseeb4@[Link])
d) Non-calculative data (phone number, ids, serial numbers)
2. Integer
a) Whole number (56,99,101)
3. Float
a) Fractional Part (56.55,99.01,101.98)
4. Boolean
a) Two states.
5. Date
a) Date(Formats)
6. Time
a) Time (Formats)
Arithmetic Operators:
1. = (Assign a value)
2. == (compare two values if they are equal)
3. All the Boolean operators (true or false) (1st letter would be capital) (True, False)
4. > ( Greater than)
5. < (Less than)
6. >=
7. <=
8. != (un equal to)
Logical Operators:
1. AND (both the conditions to be satisfied)
2. OR (either one of the conditions to be satisfied)
3. NOT (Exclude)
OUTPUT :
print(“hello how are you”) (string are encapsulated in double quotations) ….. Display : hello how are you
print (num1) (variables, constants or any data structure is never encapsulated in double quotations)
INPUT :
Num1=input(“please enter a number”)
Home work :
1) Subtract two numbers
2) Divide two numbers
Topic 1:
Conditional Statements:
1. If
2. Case (Does not exists in python)
IF : Whenever there is a need of two possible outcomes of a condition,
Structure :
#lets take two numbers and find out highest of the numbers
num1=int(input("please enter 1st number"))
num2=int(input("please enter second number"))
if num1>num2:
print("largest number is,",num1) #true outcome
else:
print("largest number is,",num2) #false outcome
Homework: [Link]
Convert codes from pseudocode to python:
Example 1,2,3
Example 15,16,17,18
Project 1:
Create a calculator, to add, subtract, multiply and divide on user’s choice.
Take two numbers from the user, and perform the required operation.
Grades Table:
Take marks from a student, display A* if the marks entered are greater than 90, A if the marks entered
are greater than 80, B if the marks entered are greater than 70, and “please try again” if the marks
entered are less than 70.
(YOU GOT 10 Minutes to do it)
marks=int(input("Please enter your marks"))
if marks>90:
print("A*")
elif marks>80:
print("A")
elif marks>70:
print("B")
else:
print("please try again")
NOTE:
You can end an if statement by elif as well:
marks=int(input("Please enter your marks"))
if marks>90:
print("A*")
elif marks>80:
print("A")
elif marks>70:
print("B")
elif marks<70:
print("please try again")
Project 1: Solution:
num1=int(input("please enter 1st
number"))
num2=int(input("please enter second
number"))
choice=input("please enter your choice,
+,-,*,/")
if choice=="+":
result=num1+num2
elif choice=="-":
result=num1-num2
elif choice=="*":
result=num1*num2
else:
result=num1/num2
print("Your choice was:",choice,"and the
result is:",result)
alternate:
#DECLARE num1,num2,result : INTEGER
num1 = int(input("ek number enter krna
"))
num2 = int(input("ek aur number enter
krna "))
choice = input("please select an
operation, +,-,*,/")
if choice == "+":
result = num1 + num2
elif choice == "-":
result = num1 - num2
elif choice == "*":
result = num1 * num2
elif choice == "/":
result = num1 / num2
if choice == "+":
name = "SUM"
elif choice == "-":
name = "SUB"
elif choice == "*":
name = "MULTIPLY"
elif choice == "/":
name = "DIVISION"
#The sum of 15 and 20 is 35
print("The",name,"of",num1,"and",num2,"is
",result)
Loops/Iterations/Repetitions:
Whenever you need a program to run again and again, till a justified point.
When you have huge amount of numbers to handle, or infinite numbers, you use loops.
While : pre conditioned loop: condition will be given at the start of the loop: conditions given are
depicting a true state.
count=0 #initialization
while count < 100:
print(count)
count=count+1
Total=0
Total = total + num
Highest=0
If num>highest:
Highest=num
Lowest=9999
IF num<lowest:
Lowest=num
#highest of 10 numbers
#lowest of 10 numbers
highest=-1
lowest=999999
count=0
while count<=9:
num=int(input("please enter a
number"))
if num>highest:
highest=num
if num<lowest:
lowest=num
count=count+1
print("Highest number is: ", highest)
print("Lowest number is: ",lowest)
Take 10 numbers, from the user, add the numbers, find out the highest and lowest of the numbers,
output the average of the numbers, sum of the numbers, highest of the numbers, lowest of the
numbers, and the range i.e., the difference between highest and lowest number.
10 minutes:
count=0
highest=-1
lowest=99999
total=0
while count<=9:
num=int(input("number enter karooo :)"))
total=total+num
if num>highest:
highest=num
if num<lowest:
lowest=num
count=count+1
average=total/10
range=highest-lowest
print("The sum of the numbers is: ",total)
print("The average of the numbers is: ",average)
print("The highest number is: ",highest)
print("The lowest number is: ",lowest)
print("The range is: ", range)
Homework:
Example 7-12
Project :
Try creating a simple game of your own choice using a while loop.
Automatic checking for errors, the data entered meets specific criteria…! 😊
Example:
Take marks from the students, find out the average of the marks entered, reject all invalid entries, count
how many entries were invalid.
total=0
invalidentries=0
count=0
while count<=9:
marks=int(input("please enter your marks"))
while marks<0 or marks>100:#validation #RANGE CHECK
#6 Types Minimum!
marks=int(input("Invalid marks entered, please
re-enter in between 0 and 100 inclusive"))
invalidentries=invalidentries+1
total=total+marks
if marks>=90:
print("A*")
elif marks>=80:
print("A")
elif marks>=70:
print("B")
else:
print("You need to work hard")
count=count+1
average=total/10
print("Average is: ",average)
print("Invalid Entries are: ",invalidentries)
FOR Loop:
No NEXT statement.
All you need to do is to start the loop only and give the range for how many times the loop should run.
HOME WORK 1: Try printing 1st 50 even numbers and odd numbers using for loop.
total=0
for x in range(5):
num=int(input("number enter karo"))
total=total+num
avg=total/5
print(avg)
[Link]:
Solve example 1-20, and all exam style questions, put all the codes in word document.
fastest=0
slowest=9999
totalfinal=0
for count in range(1,6):
time=int(input("please enter time"))
finalspeed=int(200/time)
print("Final speed of car ", count, " is ",
finalspeed,"km/h")
if finalspeed>fastest:
fastest=finalspeed
if finalspeed<slowest:
slowest=finalspeed
totalfinal=totalfinal+finalspeed
avgspeed=totalfinal/5
print("Highest Speed is: ",fastest)
print("Lowest Speed is: ",slowest)
print("Average speed is: ",avgspeed)
x=0
y=10
print(f"my name is {x} and {y}")
my name is 0 and 10
Question7:
totalitemcost=0
for x in range(10):
itemtype=int(input("please input the item
type"))
partscost=float(input("please input the cost"))
if itemtype==1:
itemcost=partscost*1.5
elif itemtype==2:
itemcost=partscost*2.5
elif itemtype==3:
itemcost=partscost*5.0
print("Your item cost is: ",itemcost)
totalitemcost=totalitemcost+itemcost
averagecost=totalitemcost/10
print("Average cost is: ",averagecost)
[Link] :
Arrays:
Data Structure:
1) Variables
2) Constants
3) Array
A data structure that can store multiple values, of same data type.
Haseeb Asd
Asdaq Asd
Ibraeem Sdgs
Hijab Asdf
Ahmed Asda
Reem Asd
Afeera Ads
Haider Asd
50 numbers:
INPUT Games[1]
INPUT Games[2]
INPUT Games[3]
INPUT Games[4]
INPUT Games[5]
GTA
TEKKEN
Xyz
COD
FIFA
games=[]
for x in range(5):
gamename=input("Please enter game name?")
[Link](gamename)
print(games)
let’s take 10 numbers from the user, store them into the array, and find out the average of the numbers.
0.11
1.12
2.
3.
4.
5.
6.
7.
8.
9.
Total=0+11+12
nums=[]
total=0
for x in range(10):
num=int(input("please enter
10 numbers"))
[Link](num)
total=total+nums[x]
avg=total/10
print(nums)
print(avg)
Store marks of 15 students in an array, find out the highest and lowest marks, the average marks.
Output the grade based on the marks. Count how many students got As and A*s.
marks=[]
highest=-1
lowest=101
total=0
count1=0
count2=0
for x in range(5):
num=int(input("please enter your
marks"))
[Link](num)
if marks[x]>highest:
highest=marks[x]
if marks[x]<lowest:
lowest=marks[x]
total=total+marks[x]
if marks[x]>=90:
Grade="A*"
count1=count1+1
elif marks[x]>=80:
Grade="A"
count2=count2+1
else:
Grade="You need to work hard,
always score more than 80"
print("Your Grade is: ", Grade)
average=total/5
print("Average Marks is: ", average)
print("Highest: ",highest)
print("Lowest: ",lowest)
print("Total A*'s are: ",count1)
print("Total A's are: ",count2)
Store 5 numbers in an array, then take a value from the user, compare if the value exists in the array or
not, if it does, output the value followed by an appropriate prompt, else output “the value isn’t there”.
1) LINEAR SEARCH
nums=[]
for x in range(5):
number=int(input("please enter 5
numbers"))
[Link](number)
searchvalue=int(input("please enter a
number you wanna search"))
for x in range(5):
if nums[x]==searchvalue:
print(nums[x])
print("I found it")
else:
print("Not found at: ",x)
# this is why we need FLAG
LOOPING.......
#set up an array to store marks of
5 students
#output the highest,lowest and
average marks
#output the grades based on the
marks
#A*,A,Try again
marks=[]*5
total=0
highest=0
lowest=9999
for x in range(5):
number=int(input("please enter
your marks"))
[Link](number)
total = total + marks[x]
if marks[x] > highest:
highest=marks[x]
if marks[x] < lowest:
lowest=marks[x]
if marks[x]>=90:
grade="A*"
elif marks[x]>=80:
grade="A"
else:
grade="try again"
print("Grade is:",grade)
avg=total/5
print("Average is:",avg)
print("Highest is:",highest)
print("Lowest is:",lowest)
#set up an array to store marks of 5 students
#output the highest,lowest and average marks
#output the grades based on the marks
#A*,A,Try again
marks=[]*5
total=0
highest=0
lowest=9999
grade=[""]*5
name=[]*5
for x in range(5):
studentname=input("please enter your name")
[Link](studentname)
number=int(input("please enter your marks"))
[Link](number)
total = total + marks[x]
if marks[x] > highest:
highest=marks[x]
if marks[x] < lowest:
lowest=marks[x]
if marks[x]>=90:
grade[x]="A*"
elif marks[x]>=80:
grade[x]="A"
else:
grade[x]="try again"
avg=total/5
print("Average is:",avg)
print("Highest is:",highest)
print("Lowest is:",lowest)
for x in range(5):
print("Name:",name[x],"has scored",marks[x],"with grade",grade[x])
Search through the array:
Linear Search:
#Searching through the array:
nums=[]*5
for x in range(5):
num=int(input("please enter a
number"))
[Link](num)
count=0
found=False
searchvalue=int(input("please enter a
number you are looking for"))
while count<5 and found==False:
if searchvalue==nums[count]:
found=True
else:
count=count+1
if found==True:
print("yayyy i found it")
print("i found it at: ",count)
else:
print("i didnt found it")
Bubble Sort:
[Link]
swap=False
2D Arrays 😊
Linear search and bubble sort
practice…!
2D Array :
We will have two dimensions..:)
For example you want to store names:
nums=[""]*5
nums=[0]*5
nums=[0.0]*5
2d ARRAY:
Set up a 1D array to store 3 names from the user, and output the names…!
names=[]*3
for x in range(3):
name=input("please enter your name")
[Link](name)
print(names)
rows, cols=(5,5)
information=[[0]*cols]*rows
for row in range(5):
for col in range(5):
print(information[row][col])
Set up a 2D array to store names and passwords of 5 employees and output the data as well.
Dimensions : 2
Indexes : 5
rows, cols=(5,2)
information=[[None]*cols for _ in
range(rows)]
for row in range(5):
name=input("please enter your name")
information[row][0]=name
password=input("please enter your
password")
information[row][1]=password
print(information)
Set up an 2D array to store 5 names and 5 passwords output the contents of the array.
Set up a 2D array for 3 rows and 7 columns and initialize all the array elements as “EMPTY”.
PRACTICE 2D Arrays 😊
students=["haseeb","ibraheem","hijab","a
sdaq"]
print(students)
students=["haseeb","ibraheem","hijab","a
sdaq"]
for x in range(4):
print(students[x])
students=[]
for x in range(4):
studentname=input("please enter your
name")
[Link](studentname)
for x in range(4):
print(students[x])
Operation 1: Append
Operation 3: Copy
Operation 4: Count
students=["haseeb","hijab","ibraheem","h
ijab","asdaq","haseeb","haseeb"]
name=[Link]("hijab")
print(name)
Operation 5: Extend:
students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link](students)
print(teachers)
Operation 6: Index
students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
position=[Link]("ibraheem")
position2=[Link]("haider")
print(position)
print(position2)
Operation 7: Insert
students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link](0,"lenovo")
[Link](3,"hp")
print(students)
Operation 8 : Pop
Remove an element from a specified position. Always mention the position i.e., index.
students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link](0)
[Link](2)
print(students)
Operation 9 : Remove
Removes the element from the index. (You may use the element name)
students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link]("haseeb")
[Link]("asdaq")
print(students)
Operation 10 : Reverse
Reverses the order of array.
students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link]()
print(students)
[Link]()
print(teachers)
Operation 11 : Sort
students=["haseeb","hijab","ibraheem","h
ijab","asdaq"]
teachers=["fatima","haider","husain"]
[Link]()
[Link]()
print(students)
print(teachers)
rows,cols=(5,2)
information=[[None]*cols for _ in
range(rows)]
for row in range(5):
name=input("Please enter your name")
email=input("Please enter your
email")
information[row][0]=name
information[row][1]=email
print(information)
Practice 2D Arrays: 😊
Set up a 2D array, for 100 rows and 4 columns, set all elements of the array as “empty”.
rows=100
cols=4
data=[["empty" for _ in range(cols)]for
_ in range(rows)]
print(data)
Set up a 2D array to store names, emails and passwords for 5 clients. Output the contents of the array,
check either has123 exists in the passwords or not. If it does output “confirmed”, else “output password
does not match”.
rows=5
cols=3
data=[[None for _ in range(cols)]for _ in
range(rows)]
for row in range(5):
name=input("please enter your name")
email=input("please enter your email")
password=input("please enter your
password")
data[row][0]=name
data[row][1]=email
data[row][2]=password
found=False
index=0
while index<4 and found==False:
if data[index][2]=="has123":
found=True
else:
index=index+1
if found==True:
print("confirmed")
else:
print("password does not match")
for row in range(5):
for col in range(3):
print (data[row][col])
rows=5
cols=3
marks=[[None for _ in range(cols)]for _ in
range(rows)]
for row in range(5):
subject1=(int(input("please enter your
marks for subject 1 ")))
subject2 = (int(input("please enter your
marks for subject 2 ")))
subject3 = (int(input("please enter your
marks for subject 3 ")))
marks[row][0]=subject1
marks[row][1] = subject2
marks[row][2] = subject3
totalmarks=[0 for _ in range(rows)]
for row in range(5):
for col in range(3):
totalmarks[row]=totalmarks[row]
+marks[row][col]
average=totalmarks[row]/5
print("Average of Student ", row+1, " is ",
average)
(HOMEWORK…!)
Set up a 2D array to store marks of 5 students studying 3 subjects each, add the marks and store them
into a 1D array, find out the average of each student individually.
Set up a 2D array info to store names and emails for 5 employees, populate the array and sort the array
in order of emails using bubble sort.
Stacks:
LIFO (Last in First Out) (The data being added first would be the last one to be removed)
1) LIFO
2) Two pointers : top pointer, base pointer
3) Top pointer : last element of the stack
4) Base pointer : 1st element of the stack
5) If you want to add a data element the process is called ‘push’.
6) If you want to delete a data element the process is called ‘pop’.
7) Push : top + 1 (increment the top pointer) and then add the data element.
8) Pop : Remove the data element and then top – 1.
9) Whenever trying to push an element always make sure stack is not full.
10) Whenever trying to pop an element always make sure stack is not empty.
The element added 1st is the last one to be removed.
Code :
top pointer = -1
top pointer = 5
global stackdata
stackdata=[0]*10
global stackpointer
stackpointer=0
def printing():
global stackdata
global stackpointer
print("Stack Pointer: ", stackpointer)
print("Stack Data:")
for x in range(10):
print(stackdata[x])
def push(datatoadd):
global stackdata
global stackpointer
if stackpointer==10:
return False
else:
stackdata[stackpointer]=datatoadd
stackpointer=stackpointer+1
return True
def pop():
global stackdata
global stackpointer
if stackpointer==0:
return -1
else:
temp=stackdata[stackpointer-1]
stackdata[stackpointer-1]=0
stackpointer=stackpointer-1
return temp
for x in range(11):
numbers=int(input("please enter a
number"))
if push(numbers)==True:
print("Data added successfully")
else:
print("Stack is full cannot push")
printing()
for x in range(2):
result=pop()
if result==-1:
print("Stack is empty cannot pop")
else:
print("The deleted element is: ",
result)
printing()
Stacks Videos:
[Link]
Queues:
NOTE : Always check the queue is not full when enqueuing and not empty when dequeuing.
Queues video
[Link]
1) Queue works on FIFO.
2) Operations :
a) Enqueue
b) Dequeue
3) Pointers
a) Front Pointer (Point to the 1st element of the queue)
b) Rear Pointer (Point to the last element of the queue)
4) Enqueue : Queue is not full
Queue will be full when rearpointer = queuefull (maximum number of elements in the queue,
according to array)
5) Dequeue : Queue should not be empty
Queue will be empty when rear pointer is equals t0 -1.
6) How to enqueue : Rearpointer +1, add the element.
7) How to dequeue: remove the element, you may store it into temp, set the index to zero,
frontpointer +1.
8) Concentric behavior of queues.
While removing or adding, it is possible that elements are at the start of the queue.
In that situation, if rear pointer or front pointer is equals to queuefull, then rather adding one
into the pointers, set the pointers to 1.
Code:
global queue
global frontpointer
global rearpointer
global queuefull
global queuelength
queue=[None for _ in range(5)]
frontpointer=0
rearpointer=-1
queuefull=5
queuelength=0
def subprintkrwado():
global queue
global frontpointer
global rearpointer
for x in range(5):
print("Index: ",x," ",queue[x])
print("FrontPointer: ",frontpointer)
print("RearPointer: ",rearpointer)
def enqueue():
global queue
global frontpointer
global rearpointer
global queuefull
global queuelength
if queuelength==queuefull:
print("Queue is full, cannot
enqueue")
return False
else:
if rearpointer==queuefull:
rearpointer=1
else:
rearpointer=rearpointer+1
num=int(input("please enter a data
element to add"))
[Link](rearpointer,num)
queuelength=queuelength+1
return True
def dequeue():
global queue
global frontpointer
global rearpointer
global queuefull
global queuelength
if queuelength==0:
print("Queue is empty, cannot
dequeue")
return False
else:
temp=queue[frontpointer]
queue[frontpointer]=0
if frontpointer==queuefull:
frontpointer=1
else:
frontpointer=frontpointer+1
queuelength=queuelength-1
return temp
elements=int(input("how many elements you
want to store in the queue"))
while elements<0 or elements>5:
elements = int(input("please enter in
between 0 and 5"))
for x in range(elements):
if enqueue()==True:
print("element added successfully")
else:
print("Queue is full")
subprintkrwado()
removeelements=int(input("how many elements
you want to dequeue"))
while removeelements<0 or removeelements>5:
removeelements = int(input("please enter
in between 0 and 5"))
for x in range(removeelements):
elementremoved=dequeue()
if elementremoved==False:
print("Queue is empty, no more
elements to dequeue")
else:
print("The element removed is:
",elementremoved)
subprintkrwado()
# Linked List : (Notes)
With Modules:
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
Setup, adding an element, and searching through a linked list:
# Linked List
#Set up of Linked List
data=[None for _ in range(5)]
pointers=[None for _ in range(5)]
startpointer=-1
heapstartpointer=0
for index in range(4):
pointers[index]=index+1
pointers[4]=-1
#printing of setup
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
#adding an element into the linked list
numbers=int(input("please enter how many
numbers you want to add"))
while numbers<0 or numbers>5:
numbers = int(input("please enter in
between 0 and 5"))
for x in range(numbers):
additem=int(input("please enter an
element you want to add"))
if heapstartpointer==-1:
print("List is full")
else:
temp=startpointer
startpointer=heapstartpointer
heapstartpointer=pointers[heapstartpointer]
data[startpointer]=additem
pointers[startpointer]=temp
#printing after adding
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
#searching through the linked list
searchvalue=int(input("please enter a value
you want to search"))
itempointer=startpointer
found=False
while itempointer!=-1 and found==False:
if data[itempointer]==searchvalue:
found=True
else:
itempointer=pointers[itempointer]
if found==True:
print("Item found at: ",itempointer)
else:
print("Item not found")
Modular Code:
# Linked List
#Set up of Linked List
global data
global pointers
global startpointer
global heapstartpointer
data=[None for _ in range(5)]
pointers=[None for _ in range(5)]
startpointer=-1
heapstartpointer=0
for index in range(4):
pointers[index]=index+1
pointers[4]=-1
#printing of setup
def printing():
global data
global pointers
global startpointer
global heapstartpointer
for x in range(5):
print("Index: ",
x,"=>",data[x],"=>",pointers[x])
print("Heap Start Pointer: ",
heapstartpointer)
print("Start Pointer: ",startpointer)
printing()
#adding an element into the linked list
def addelement():
global data
global pointers
global startpointer
global heapstartpointer
numbers=int(input("please enter how
many numbers you want to add"))
while numbers<0 or numbers>5:
numbers = int(input("please enter
in between 0 and 5"))
for x in range(numbers):
additem=int(input("please enter an
element you want to add"))
if heapstartpointer==-1:
print("List is full")
else:
temp=startpointer
startpointer=heapstartpointer
heapstartpointer=pointers[heapstartpointer]
data[startpointer]=additem
pointers[startpointer]=temp
addelement()
#printing after adding
printing()
#searching through the linked list
def searching():
searchvalue=int(input("please enter a
value you want to search"))
itempointer=startpointer
found=False
while itempointer!=-1 and found==False:
if data[itempointer]==searchvalue:
found=True
else:
itempointer=pointers[itempointer]
if found==True:
print("Item found at:
",itempointer)
else:
print("Item not found")
searching()
Introduction:
Visualize:
1) Ali
2) Haseeb
3) Ibraheem
4) Laiba
5) Zainab
6) Asad
7) Ahmed
8) Bilal
Example:
TYPE Information
DECLARE Name : STRING
DECLARE Subject : STRING
DECLARE Age : INTEGER
DECLARE DoB : DATE
DECALRE SalaryPaid : BOOLEAN
END TYPE
Numbers[index].Age=10
Numbers[3].Age=15
Numbers[3].Name=”Haseeb”
data=information("haseeb",15)
print([Link])
print([Link])
Create two variables of Data, take values from the user, and output the values as well.
class data:
def __init__(self,n,e,p):
[Link]=n
[Link]=e
[Link]=p
class data:
def __init__(self,n,e,p):
[Link]=n
[Link]=e
[Link]=p
for x in range(2):
value1=input("please enter your name")
value2=input("please enter your email")
value3=input("please enter your password")
data1=data(value1,value2,value3)
print([Link])
print([Link])
print([Link])
array
class teacherdata:
def __init__(self,n,a,s,add):
[Link]=n
[Link]=a
[Link]=s
[Link]=add
teachers=[]*2
for x in range(2):
val1=input("please enter your name ")
val2 = int(input("please enter your age "))
val3 = float(input("please enter you
salary"))
val4 = input("please enter your address ")
teacher=teacherdata(val1,val2,val3,val4)
[Link](teacher)
for x in range(2):
print(teachers[x].name)
print(teachers[x].age)
print(teachers[x].salary)
print(teachers[x].address)
Binary Tree:
rootpointer
free pointer
when the tree is empty, free pointer will point to nothing that is it will be equal to zero
and when the tree is full, it will point to the null pointer
and all the values of free pointer are updated using the left pointer rather than incrementing
class treenode:
def __init__(self,l,d,r):
[Link]=l
[Link]=d
[Link]=r
tree=[]*6
nullpointer=-1
freepointer=0
rootpointer=-1
for x in range(5):
index=x+1
data=treenode(index,"",0)
[Link](data)
data2=treenode(-1,"",0)
[Link](6,data2)
for x in range(6):
print("Index: ",x,"-
>",tree[x].leftpointer,"->",tree[x].data,"-
>",tree[x].rightpointer)
class treenode:
def __init__(self,l,d,r):
[Link]=l
[Link]=d
[Link]=r
tree[newnodepointer].rightpointer=-1
#checking if the tree was empty and
this is 1st data element
if rootpointer==nullpointer:
rootpointer=newnodepointer
for x in range(6):
print("Index: ",x,"-
>",tree[x].leftpointer,"-
>",tree[x].data,"-
>",tree[x].rightpointer)
#adding an element into binary tree
class treenode:
def __init__(self,l,d,r):
[Link]=l
[Link]=d
[Link]=r
thisnodepointer=tree[thisnodepointer].leftpointer
else:
turnedleft=False
thisnodepointer=tree[thisnodepointer].rightpointer
if turnedleft==True:
tree[previousnodepointer].leftpointer=newnodepointer
else:
tree[previousnodepointer].rightpointer=newnodepointer
for x in range(10):
print("Index: ",x,"->",tree[x].leftpointer,"-
>",tree[x].data,"->",tree[x].rightpointer)
#search an element
searchelement=input("please enter an element to search")
index=rootpointer
while index!=nullpointer and tree[index].data!
=searchelement:
if tree[index].data>searchelement:
index=tree[index].leftpointer
else:
index=tree[index].rightpointer
if index==nullpointer:
print("The element is not in the tree")
else:
print("Element found at: ", index)
Homework:
class dog:
def __init__(self,n,a):
self.__name=n
self.__age=a
def bark(self):
print(self.__name," says
woooooooffff")
def getage(self):
return self.__age
mydog=dog("Scooby",3)
print([Link]())
mydogage=[Link]()
print("Age: ",mydogage)
python
# Define a class named `Person`
class Person:
# Constructor to initialize the person's name and age
def __init__(self, name, age):
[Link] = name
[Link] = age
2. *Inheritance*
python
# Define a base class named `Animal`
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print(f"{[Link]} makes a sound")
# Define a derived class named `Dog` that inherits from `Animal`
class Dog(Animal):
def speak(self):
print(f"{[Link]} barks")
3. *Encapsulation*
python
# Define a class named `BankAccount`
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private attribute
def get_balance(self):
return self.__balance
Question 11:
import datetime
class Character:
#self.__CharacterName : STRING
#self.__DateOfBirth : DATE
#self.__Intelligence : REAL
#self.__Speed : INTEGER
def __init__(self,cn,db,integ,sp):
self.__CharacterName=cn
self.__DateOfBirth=db
self.__Intelligence=integ
self.__Speed=sp
def GetIntelligence(self):
return self.__Intelligence
def GetName(self):
return self.__CharacterName
def SetIntelligence(self,value):
self.__Intelligence=value
def Learn(self):
self.__Intelligence=self.__Intelligence*1.1
def ReturnAge(self):
return 2023-self.__DateOfBirth.year
class MagicCharacter(Character):
def __init__(self,elem,cn,db,integ,sp):
super(). __init__(cn,db,integ,sp)
self.__Element=elem
def Learn(self):
if self.__Element=="Fire" or
self.__Element=="Water":
super().SetIntelligence(super().GetIntelligence(
)*1.2)
elif self.__Element=="Earth":
super().SetIntelligence(super().GetIntelligence(
) * 1.3)
else:
super().SetIntelligence(super().GetIntelligence(
) * 1.1)
FirstCharacter=Character("Royal",[Link]
me(2019,1,1),70,30)
[Link]()
print("Name of the character is:
",[Link](),",the age is
",[Link]()," with intelligence
",[Link]())
FirstMagic=(MagicCharacter("Fire","Light",dateti
[Link](2018,3,3),75,22))
[Link]()
print("Name is: ",[Link](),"and age
is",[Link](),"with a intelligence
of",[Link]())
global DataArray
DataArray=[None for _ in range(100)]
def ReadFile():
try:
reader = open(r"C:\Users\123\Desktop\
[Link]", "r")
for x in range(100):
DataArray[x]=[Link]()
DataArray[x].rstrip('/n')
DataArray[x]=int(DataArray[x])
[Link]()
except IOError:
print("file not found")
ReadFile()
print(DataArray)
#left,right,mid,len
reader=open(r"file path","mode")
then use reader
same goes for writer and if you want to append
Question 1:
TheData=[20,3,4,8,12,99,4,26,4]
def searchsearch(TheData):
num=int(input("please enter a
number"))
found=False
index=0
while found==False and index<9:
if TheData[index]==num:
print("Found")
found=True
return True
else:
index=index+1
print("Not Found")
return False
searchsearch(TheData)
def PrintArray(DataArray):
print(DataArray)
def
LinearSearch(DataArray,searchval
ue):
count=0
for x in range(25):
if
DataArray[x]==searchvalue:
count=count+1
return count
DataArray=[]
try:
reader=open(r"C:\Users\123\
Desktop\[Link]","r")
for Line in reader:
[Link](int(Line))
[Link]()
except IOError:
print("File not found")
PrintArray(DataArray)
searchnum=int(input("please
enter a number in between 0 and
100"))
while searchnum<0 or
searchnum>100:
searchnum =
int(input("please enter a number
in between 0 and 100"))
times=LinearSearch(DataArray,sea
rchnum)
print("The number",searchnum,"is
found",times)
def output():
global StackData
global StackPointer
for x in range(10):
print(x,"=>",StackData[x])
print("Stack Pointer:",StackPointer)
def push(num): #integer
global StackData
global StackPointer
if StackPointer==10:
return False
else:
StackData[StackPointer]=num
StackPointer=StackPointer+1
return True
def pop():
global StackData
global StackPointer
if StackPointer==0:
return -1
else:
temp=StackData[StackPointer-1]
StackPointer=StackPointer-1
return temp
printing()
exit=False
while exit==False:
choice=int(input("Press 1 to search,
Press 2 to Sort, Press 3 to exit"))
if choice==1:
nextchoice1=int(input("Press 1
for Linear Search, Press 2 for Binary
Search"))
if nextchoice1==1:
linearsearch()
else:
binarysearch()
elif choice==2:
nextchoice2=int(input("Press 1
for Bubble Sort, Press 2 for Insertion
Sort"))
if nextchoice2==1:
bubblesort()
printing()
else:
insertionsort()
printing()
else:
print("Press Enter again")
exit=True