Python 3 Reference Guide

This article is a quick guide that goes over syntax and concepts taught in the Python 3 course.

Last updated - July 22, 2024

Table of Contents 

Reading Files
Reading Parts of a File
Editing and Writing Files
    Append a Line to a Text File
    File Write Mode
Lists
    Multi-dimensional Lists
    Nested For Loops
Iterating through 2D Lists
Creating a Class
Creating an Instance
Stacks
Recursion
Recursion vs Iteration
Sorting Algorithms
    Bubble Sort
    Selection Sort
    Insertion Sort
    Merge Sort

Reading Files

To read a file, you will need to use 3 methods, open(), file.read() and file.close(). The open() method will contain the name of the text file, a comma, and the letter "r." The "r" makes the file read only. The file.read() method reads through the file. The file.close() method closes out the file to free up working memory.

file = open("example.txt", "r")
print(file.read())
file.close()

Output: This text is from the example file!

Reading Parts of a File

To only read a certain amount of characters, you can enter a number into the file.read() method.

file = open("example.txt", "r")
print(file.read(5))
file.close()

Output: This

To read entire lines of a file, use the file.readline() method. Using it once will return the first line. Using it multiple times will return multiple lines starting with the first.

file = open("example.txt", "r")
print(file.readline())
print(file.readline())
file.close()

Output: This text is from the example file!
This is the second line!

Append a Line to a Text File

To append a text file, you will need to replace the "r" in the open("example.txt", "r") with an "a." The "a" appends to a file. This will add content to the end of the file without deleting anything.

file = open("example.txt", "a")
print(file.write("Here is a new line of text!"))
file.close()

file = open("example.txt", "r")
print(file.read())
file.close()

Output: This text is from the example file!
This is the second line!
Here is a new line of text!

File Write Mode

To access file write mode, we will change the "a" to a "w" for write. This mode completely overwrites the content of a file. This can also be used to create a new file. Type the name of the file in the open() method.

file = open("example.txt", "w")
file.write("This is the new text!")
file.close()

file = open("example.txt", "r")
print(file.read())
file.close()

Output: This is the new text!

Multi-dimensional Lists

Lists can be multi-dimensional and contain other lists. Below is an example of how to create a multi-dimensional list using for loops.

rows = [1, 2, 3]
cols = ["red", "orange", "yellow", "green"]
list = []
for i in rows:
col = []
for j in columns:
columns.append(j)
list.append(j)
print(list)

Output: [['red', 'orange', 'yellow', 'green'],
['red', 'orange', 'yellow', 'green'],
['red', 'orange', 'yellow', 'green']]

Nested For Loops

Nested for loops are when we have a loop inside another loop.

fruit = ["apple", "pear", "blueberry"]
desserts = ["pie", "crumble", "strudel"]

for i in fruit:
for j in desserts:
print(i, j)

Output: apple pie
apple crumble
apple strudel
pear pie
pear crumble
pear strudel
blueberry pie
blueberry crumble
blueberry strudel

Iterating Through 2D Lists

Using nested for loops, we're able to iterate through a 2D list. The below example multiplies 2 to each number in the 2D list.

my_list = [[0, 1, 2], [10, 15, 20], [100, 200, 300], [5, 6, 7]]
rows = 4
cols = 3

for i in range(rows):
for j in range(cols):
my_list[i][j] = my_list[i][j] * 2

print(my_list)

Output: [[0, 2, 4], [20, 30 , 40], [200, 400, 600], [10, 12, 14]]

Creating a Class

A class is a blueprint of an object. After creating a class, we are able to create as many objects as we want using the blueprint. A class is defined with the "class" keyword. Inside the class, we will add the __init__ method(). The "self" parameter needs to be included in the __init__() method.

class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job

Creating an Instance

After a class is created, we can create an instance of that class. To do this we will need to add our own arguments.

class Person:
def __init__(self, name, age, job):
self.name = name
self.age = age
self.job = job

first_person = Person("Bill", 17, "Cashier")
second_person = Person("Jamie", "15, "Student")

print(first_person.age)
print(second_person.name)

Output: 17
Jamie

Stacks

A stack is an essential data structure. A data structure is a data storage technique. In a stack, the last piece of data is the first piece that can be removed. An example of this is a stack of plates. The last plate added to the pile is also the first removed. Data is added to a stack using the append() method and removed with the pop() method.

stack = []

stack.append("a")
stack.append("b")
stack.append("c")
stack.pop()

print(stack)

Output: ['a', 'b']

Recursion

Recursion is when a function calls itself from within itself. Recursive functions will include a "base case" that will stop the function from calling itself. A base case is usually a conditional statement.

def my_function(num):
if (num >= 10):
return
print(num)
my_function(num + 1)

my_function(4)

Output: 4
5
6
7
8
9

Recursion vs. Iteration

This example shows how recursion can simplify a function. The following examples find the factorial of an inputted number. The first example uses iteration and the second uses recursion.

def iterative_factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
print(result)

iterative_factorial(4)

Output: 24
def factorial(n):
if n <= 1:
return 1
else:
return n * (factorial(n - 1))

print(factorial(4))

Output: 24

Bubble Sort

Bubble sort is a sorting algorithm that compares adjacent numbers to sort a list. The algorithm continually loops until the numbers are ordered from lowest to highest.

def bubblesort(list):
    for i in range(len(list) - 1, 0, -1):
        for j in range(i):
            if list[j] > list[j + 1]:
                temp = list[j]
                list[j] = list[j + 1]
                list[j + 1] = temp
                
    print(list)
    
bubblesort([9, 4, 6, 5, 2, 7])

Output: [2, 4, 5, 6, 7, 9]

Selection Sort

Selection sort finds the smallest number in an inputted list and adds it to the sorted section of the list. The next lowest number is added to the beginning of the unsorted list section on and on until all list items have been looped through.

my_list = [10, 32, 4, 90, 15, 20]


def selectionSort(sort_list):
    for i in range(len(sort_list)):
        smaller_index = i
        for j in range(i+1, len(sort_list)):
            if sort_list[smaller_index] > sort_list[j]:
                smaller_index = j       
        sort_list[i], sort_list[smaller_index] = sort_list[smaller_index],
sort_list[i]

selectionSort(my_list)
print(my_list)

Output: [4, 10, 15, 20, 42, 90]

Insertion Sort

Insertion sort takes the smallest number and inserts it into the correct position in the list. The function continually inserts the next smallest number until the list is sorted.

my_list = [10, 22, 5, 76, 12, 54]

def insertionSort(sort_list):
    for i in range(1, len(sort_list)):
        key = sort_list[i]
        j = i-1
        while j >= 0 and key < sort_list[j] :
            sort_list[j + 1] = sort_list[j]
            j -= 1
        sort_list[j + 1] = key
        
insertionSort(arr)

Output: [5, 10, 12, 22, 54, 76]

Merge Sort

Merge sort is a recursive algorithm that continues to make smaller lists until all items in the individual lists are in the correct order. The algorithm then combines all of the small lists into one sorted list.

my_list = [10, 22, 5, 76, 12, 54]

def mergeSort(sort_list):
    if len(sort_list) > 1:
 
        mid = len(sort_list)//2
        L = sort_list[:mid]
        R = sort_list[mid:]
        mergeSort(L)
        mergeSort(R)
 
        i = j = k = 0
        
        while i < len(L) and j < len(R):
            if L[i] < R[j]:
                sort_list[k] = L[i]
                i += 1
            else:
                sort_list[k] = R[j]
                j += 1
            k += 1

        while i < len(L):
            sort_list[k] = L[i]
            i += 1
            k += 1
 
        while j < len(R):
            sort_list[k] = R[j]
            j += 1
            k += 1
            
mergeSort(my_list) 
print(my_list)

Output: [5, 10, 12, 22, 54, 76]