1 // 2 will only give you the whole numbers that have been divided
13 %= 158 calculates remaining whole numbers(I think “=” makes it only whole numbers)
13 % 11 calculates remining numbers(whole and partial).
-------------------------------------------------------------------------------------------------------------------------
-with elif, last line ends “else:” ….”if x > 1:”
Print”
2.4:Python Syntax:
Round function= round(number,2)
UNIT 3-ARRAYS
1-D arrays:
When keeping position holders (Term 4), write code where code is written for marks)
Highest = arr[x]
HighestTerm = x
2-D arrays:
when deleting from a 2-D array, be very specific(del myArray[0][3])…row 0, column 3).
For 2-D arrays, first say for column then say for row
( -> for row in MyArray:
( -> for column in MyArray:
Print(column, end = " ") the (“end = “ “) turns printing from 1 value per line to all in 1 line
11
12 -> 11 12 13
13
Step 1 : initialise first array – “rowa = []”
Step 2: run first for loop for rows “for I in range(5)”
Step3: initialise second array – “columns = []”
Step 4: run second loop for columns “for I in range(3)”
Step 5: get input to populate array “n = input()
Step 6: populate array with input “ column.append(n)
Step 7(optional): populate row array with column values “numbers.append(column)
TO PRINT EACH ROW IN THE ARRAY: [56, 90, 86]
Step 1: run for loop for x in ROW array—“for i in numbers:
Step 2: print x(place holder so it does it multiple times): “print(i)
X = [[1,2,3], [4,5,6], [7,8,9]] #declares
X = X[0][0]
Print(X)
An array is a data structure that consists of related data items (called elements) of the same data
type(string, int). cannot contain a mixture of both. Contains a fixed number of items/elements.
Locating element no.8 is the same time as locating element no.0(starts at 0). Arrays are used to store
data. Arrays need to be declared but lists do not need to be declared(they are part of python
syntax)
The highest value in a group
The lowest value in a group
The total of all values
The average value
The highest average value
The lowest average value
4 types of collection data types in the Python:
-A list/array is a collection that is ordered and changeable. allows duplicate members.
-A tuple is a collection that is ordered and unchangeable. allows duplicate members.
-A set is a collection that is unordered and not indexed. does not allow duplicate members.
-A dictionary is a collection that is unordered, changeable and indexed. no duplicate members.
EXAMPLES:
Array=[ ]
For m in range(5):
Mark = input()
Mark=int(mark)
Method Array.append(mark)#insert the mark variable into the array at the next available index.
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
Adds the elements of a list (or any iterable) to the end of the current
extend()
list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Variable.METHOD(“Data name”)
An array index tells us the position or address of a particular element in the array. The array
index is enclosed in square brackets…. Marks [0] = 60…..marks[1]=85
2-DIMENSIONAL ARRAYS
For row in array
For column in row
vxb
myArray =[[23,27,11,12],[6,10,14,5],[25,10,17,18],[8,9,15,12]] #intiliase array
for row in myArray: #iterate all rows in myArray
for column in row: #iterate all columns in myArray
print(column,end = “ “) #print each column values
print() #print each row in myArray
23 27 11
12
6 10 14 5
25 10 17
18
8 9 15 12
USING METHODS AND 2-D ARRAYS
Arrayname.method(position/function of method[values to be used])
Write rest of code normally
2 arrays =
For row in array1
For clomun in row
Updating
myArray[2] = [15,14,9,2]…#wiill reassign the values on array index 2
myArray[1][2] = 8…#will reassign the value on row 1
UNIT 4- FUNCTIONS/
-promote code maintainability, hidden from other parts of program.
Step 1: define function with parameters (def my_function(fName,sName):
Step 2: write code for function (print (fName + “ “ + sName)
Step 3: call function with arguments(my_function(“Jared”, “Christians”)32
Step 1: define function (“def my function(x)”)
Step 2: write code for function (“return 5 * x”)
Step 3: call function to return variable (return_value = my function(3))
Step 4: print return variable (print(return_value))
a function with 2 parameters(sName,sSurname) expects 2 arguments(zidaan,ballim)
-defined by def()…..”def myfunction():
Print(“hi”)
myfunction()
Recursive function-a function that calls itself(example = finding the factorial of an integer
Def factorial(x)
If x == 1
Return 1
Else:
Return (x * factorial(x-1))
Num = int(input())
print("The factorial of", num, "is", factorial(num))
UNIT 5- FILE HANDLING
Key word when opening files is open() function. The open() function takes 2 parameters: file
name and mode.
4 different modes when opening a file:
RAWX
“r”-Read- default value. Opens a file for reading. Returns an error if file does not exist.
“a”-Append- opens a file for appending, creates a file if does not exist.
“w”-Write- opens a file for writing, will overwrite any existing content, creates a file if file does not
exist.
“x”-create- creates a specified file, returns an error if the file exists.
In addition(2 at 1), you can specify if the file should be handled in binary or text mode:
“t”-Text-Default value. Text mode
“b”-Binary-Binary mode(images).
Examples:
, separates the file name and mode
‘f = open(“example.txt”)’
‘f = open(“example.txt”, “rt”)
When printing, do this… print(f.read())- the read() method returns the whole text
print(f.read(12))-12 specifies how many characters to return
print(f.readline())- returns one line by using readline() method
for line in f:
print(line)- by looping through the lines of the file, you can read the whole file, line-by-line.
f.close-closes the file
Writing to a file:
F= open(“zeze.txt”, “r”) – opens text file for reading
Data = f.read() – stores textfile contents in a variable.
f.close
f.open(“poes.txt”, “w”)
f.write(data + “\n”) – write variable(data) to the new file. “\n” indicates the end of a lin
f.write(poespoespoes)
f.close
f = open(“poes.txt”, “r”)
print(f.read())…read() method prints the whole text
print(f.read(12))…12 specifies how many characters to return
print(f.readline())…returns 1 line using readline() method
for line in f:
print(line)…by looping through lines of the file, you can read the whole file, line by line
f.close…always fucken close the fuke when done using it
bra please read file, close file then open file using append, write or create to then edit it
+ “\n” … indicates the end of a line
Step 1: open files for reading, writing or creating
Step2: write all necessary code(run loops in variable for file) (split records)(f.write to file…
paidfile.write(rec))
Step 3: close file(students.close)
Step 4: re-open file but now for reading and displaying
Step 5: print Ipaidfile.read()…whole file (paid.readline(prints only that/1 line)
Step 6: close file again
Sorting algorithms
Bubble sort is a sorting algorithm that works repeatedly stepping through lists that need to be
sorted, comparing each pair of adjacent items and swapping them if they are in the wrong
The steps to follow when sorting are:
Step 1: declare array (“arr = [64, 34, 25, 12, 22]”)
Step 2 : count how many values are in array (“n = len(arr”)
Step 3: first for loop for values before n (“for i in range(n):”)
Step 4: loop again for previous n values: (“for x in range(n-1)”)
Step 5: see if x is greater than [x+1](“if arr[x] > arr[x+1]”)
Step 6: rearrange [x], [x+1] to [x+1], [x] (“arr[x], arr[x+1] = arr[x+1], arr[x]”)
SEARCHING ALGORITHMS
Linear searching:(0(n))
1. Start from the leftmost element of arr[] and one by one compare x with each element of arr[].
2. If x matches with an element, return the index.
3.If x doesn’t match with any of the elements, return -1.
Binary searches work only on sorted lists of elements:(0(1))-elemented is located at the
midpointer almost immediately
-binary searching has the iterative method or the recursive method
Step 1: declare array (“arr = [64, 34, 25, 12, 22]”)
Step 2 : declare what we are searching for ( x = 10)
Step 3: declare n to be length of the array (“n = len(arr)”)
Step 4: declare the result if element is not found(“result = -1”)
Step 5: loop for values in I in range(n) (“ for I in range(n):”)
Step 6 : find if arr[i] == x (“arr[i]== x:”) then say (“result = I”) then insert a (“break”)
Step 7: display outputs (“if result == -1”)
Print(“element is not present in array”)
ELSE
Print(“Element is present at index”, result)
Pretty much
-run first loop in function code(for i in range(n):
-check if array in position I is = x (if arr[i] == x: )
-declare to return i (return i)
-declare to return -1 after returning place holder(return -1)(same indent as “return i” line).