Source Code

import csv

print("Unit 5")

def main():
    print("Welcome to the Main Function")
    print("Menu")
    print("E1 - Example 1")
    print("Q  - Quit")
    choice = input("Choice: ")
    match choice:
        case "E1":
            example1()
        case "E2":
            example2()
        case "E3":
            example3()
        case "E4":
            example4()
        case "E5":
            example5()
        case "E6":
            example6()
        case "E7":
            example7()
        case "E8":
            example8()
        case "E9":
            example9()
        case "E10":
            example10()
        case "E11":
            example11()
        case "E12":
            example12()
        case "E13":
            example13()
        case "E14":
            example14()
        case "E15":
            example15()
        case "E16":
            example16()
        case "E17":
            example17()
        case "E18":
            example18()
        case "E19":
            example19()
        case "E20":
            example20()
        case "Q":
            print("Quitting!")
        # default case
        case _:
            print("Invalid, try again!")

# define Example 1 Function
def example1():
    # Method 1: Literal notation
    numbers = [1, 2, 3, 4, 5]

    # for loop v1
    print("Index\tValue")
    for i in range(len(numbers)):
        print(str(i) + "\t" + str(numbers[i]))

    # for loop v2
    print("Elements")
    for n in numbers:
        print(n)

# define Example 2 Function
def example2():
    # Create an Empty List
    empty_list = list()
    print(empty_list)  # Output: []

    # Convert a String
    chars = list("hello")
    print(chars)  # Output: ['h', 'e', 'l', 'l', 'o']

    # Convert a Range
    numbers = list(range(1, 6))  # [1, 2, 3, 4, 5]
    print(numbers)

# define Example 3 Function
def example3():
    # Traditional way
    squares = []
    for x in range(5):
        squares.append(x**2)
    print(squares)  # [0, 1, 4, 9, 16]

    # List comprehension
    squares = [x**2 for x in range(5)]
    print(squares)  # [0, 1, 4, 9, 16]

# define Example 4 Function
def example4():
    # Traditional way
    evens = []
    for x in numbers:
        if x % 2 == 0:  # Filter condition
            evens.append(x)

    # Get only even numbers
    numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    evens = [x for x in numbers if x % 2 == 0]
    print(evens)  # [2, 4, 6, 8, 10]

# define Example 5 Function
def example5():
    # Traditional way
    even_squares = []
    for x in numbers:
        if x % 2 == 0:  # First filter
            even_squares.append(x**2)  # Then transform

    # Square only the even numbers
    numbers = [1, 2, 3, 4, 5, 6]
    even_squares = [x**2 for x in numbers if x % 2 == 0]
    print(even_squares)  # [4, 16, 36]

# define Example 6 Function
def example6():
    numbers = [5, 12, 18, 25, 30, 42, 55, 68]

    # Numbers between 15 and 50
    in_range = [x for x in numbers if 15 <= x <= 50]
    print(in_range)  # [18, 25, 30, 42]

# define Example 7 Function
def example7():
    # Method 4: Empty list with planned additions
    my_list = []
    my_list.append(10)
    print(my_list)

# define Example 8 Function
def example8():
    numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    # Get elements from index 2 to 5 (5 not included)
    print(numbers[2:5])    # [2, 3, 4]

    # Get elements from index 0 to 4
    print(numbers[0:4])    # [0, 1, 2, 3]

    # Get elements from index 5 to 8
    print(numbers[5:8])    # [5, 6, 7]

    # From beginning to index 5
    print(numbers[:5])     # [0, 1, 2, 3, 4]

    # Same as
    print(numbers[0:5])    # [0, 1, 2, 3, 4]

    # From index 7 to end
    print(numbers[7:])     # [7, 8, 9]

    # Same as
    print(numbers[7:10])   # [7, 8, 9]

    # Last 3 elements
    print(numbers[-3:])       # [7, 8, 9]

    # All except last 2
    print(numbers[:-2])       # [0, 1, 2, 3, 4, 5, 6, 7]

    # From -7 to -3
    print(numbers[-7:-3])     # [3, 4, 5, 6]

# define Example 9 Function
def example9():
    numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    # Every other element
    print(numbers[::2])       # [0, 2, 4, 6, 8]

    # Every third element
    print(numbers[::3])       # [0, 3, 6, 9]

    # From index 1 to 8, step by 2
    print(numbers[1:8:2])     # [1, 3, 5, 7]

    # From index 0 to 10, step by 3
    print(numbers[0:10:3])    # [0, 3, 6, 9]

# define Example 10 Function
def example10():
    numbers = [0, 1, 2, 3, 4, 5]

    # Reverse entire list
    print(numbers[::-1])      # [5, 4, 3, 2, 1, 0]

    # Reverse from index 1 to 5
    print(numbers[5:1:-1])    # [5, 4, 3, 2]

    # Every other element, reversed
    print(numbers[::-2])      # [5, 3, 1]

# define Example 11 Function
def example11():
    fruits = ["apple", "banana"]

    # append() - adds single element to end
    fruits.append("cherry")
    # ["apple", "banana", "cherry"]

    # insert() - adds element at specific index
    fruits.insert(1, "orange")
    # ["apple", "orange", "banana", "cherry"]

    # extend() - adds multiple elements
    fruits.extend(["grape", "mango"])
    # ["apple", "orange", "banana", "cherry", "grape", "mango"]

    # + operator - concatenation
    more_fruits = fruits + ["kiwi", "peach"]

# define Example 12 Function
def example12():
    numbers = [10, 20, 30, 40, 50, 30]

    # remove() - removes first occurrence of value
    numbers.remove(30)  # [10, 20, 40, 50, 30]

    # pop() - removes and returns element at index
    last = numbers.pop()      # returns 30, list: [10, 20, 40, 50]
    second = numbers.pop(1)   # returns 20, list: [10, 40, 50]

    # del statement - removes element(s) by index
    del numbers[0]            # [40, 50]
    del numbers[0:2]          # removes slice

    # clear() - removes all elements
    numbers.clear()           # []

# define Example 13 Function
def example13():
    numbers = [3, 1, 4, 1, 5, 9, 2, 6]

    # Sorting
    numbers.sort()              # Sorts in place: [1, 1, 2, 3, 4, 5, 6, 9]
    sorted_copy = sorted(numbers)  # Returns new sorted list

    # Reversing
    numbers.reverse()           # Reverses in place

    # Counting and finding
    count = numbers.count(1)    # Returns 2
    index = numbers.index(4)    # Returns index of first occurrence

    # Copying
    shallow = numbers.copy()    # Creates shallow copy
    deep = numbers[:]           # Another way to copy

# define Example 14 Function
def example14():
    names  = ["Alice",  "Bob",  "Carol",  "David"]
    grades = [92,       74,     58,       85     ]
    passed = [True,     True,   False,    True   ]

    # zip() function pairs up items from multiple lists automatically
    for name, grade, passed in zip(names, grades, passed):
        print(f"{name}: {grade} ({passed})")

# define Example 15 Function
def example15():
    # declare a 2D list
    matrix = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
    ]

    print_matrix(matrix)

    # iterate over each row
    for row in matrix:
        print(row)

    # iterate over each column
    cols = len(matrix[0]) # number of columns
    for j in range(cols):
        for i in range(len(matrix)):
            print(matrix[i][j], end=" ")
        print()

# print_matrix function
def print_matrix(matrix):
    # iterate over each element
    for row in matrix:
        for element in row:
            print(element, end=" ")
        print()

# define Example 16 Function
def example16():
    # Method 1: Literal notation with parentheses
    point = (3, 4)

    # Method 2: Without parentheses (tuple packing)
    rgb = 255, 128, 0

    # Method 3: Using tuple() constructor
    numbers = tuple([1, 2, 3, 4, 5])
    from_string = tuple("hello")  # ('h', 'e', 'l', 'l', 'o')

    # Important: Single element tuple needs comma!
    not_tuple = (5)      # This is just an integer
    is_tuple = (5,)      # This is a tuple

# define Example 17 Function
def example17():
    dimensions = (1920, 1080, 60, "landscape")

    # Positive indexing
    print(dimensions[0])      # 1920
    print(dimensions[2])      # 60

    # Negative indexing
    print(dimensions[-1])     # "landscape"
    print(dimensions[-2])     # 60

    # Slicing (same as lists)
    print(dimensions[1:3])    # (1080, 60)
    print(dimensions[:2])     # (1920, 1080)
    print(dimensions[::2])    # (1920, 60)

# define Example 18 Function
def example18():
    numbers = (1, 2, 3, 2, 4, 2, 5)

    # count() - counts occurrences
    count = numbers.count(2)      # Returns 3

    # index() - finds first occurrence
    position = numbers.index(4)   # Returns 4

    # Common operations (similar to lists)
    length = len(numbers)         # 7
    maximum = max(numbers)        # 5
    minimum = min(numbers)        # 1
    total = sum(numbers)          # 19

    # in operator
    exists = 3 in numbers         # True

# define Example 19 Function
def example19():
    # open the csv file
    file = open('scores.csv', 'r')

    # create a csv reader
    csv_reader = csv.reader(file)

    # read the header
    header = next(csv_reader)
    print(header[0] + "\t" + header[1] + "\t" + header[2] + "\t" + header[3])

    # iterate over the remaining rows
    for row in csv_reader:
        print(row[0] + "\t" + row[1] + "\t" + row[2] + "\t" + row[3])

    # close the file
    file.close()

# define Example 20 Function
def example20():
    # open a file in write mode
    with open('people.csv', mode='w', newline='') as file:
        writer = csv.writer(file)

    # write header row
        writer.writerow(["Name", "Age", "City"])

    # write data rows
        writer.writerow(["Alice", 30, "New York"])
        writer.writerow(["Bob", 25, "Los Angeles"])
        writer.writerow(["Charlie", 35, "Chicago"])

# do not delete!
main()

scores.csv

Last updated