Luleå University of Technology

LTU courses · Introduction to Programming in Python

Course D0009E

Introduction to Programming: Python assignments covering functions, data structures, object-oriented programming, and file I/O. Each task is fully interactive. Try them live below.

Python Functions Data Structures OOP File I/O 6 tasks

Lab 1: Functions & calculation

L1 · Task 1
Loan cost calculator

Calculates the total cost of a loan given principal, interest rate, and number of years.

Functions Math f-strings
Live Demo
L1_-_T1.py
def kostnad(P, R, A):
    k = P + ((A + 1) * R * P) / 2
    print(f"The total cost of the loan is:  {k} kr")

kostnad(50000, 0.03, 10)
L1 · Task 2
Recipe scaler

Scales a cake recipe to any number of people. Calculates ingredient amounts, mixing time, baking time, and total time.

Functions Arithmetic Return values
Live Demo
L1_-_T2.py
def calc_recipe(P):
    print(f"For {P} people, you will need:")
    print(f"  {(15/4)*P} g butter (shape)")
    print(f"  {int(3/4*P)} eggs")
    print(f"  {(3/4)*P} dl powdered sugar")
    print(f"  {(2/4)*P} tsp vanilla sugar")
    print(f"  {(2/4)*P} tsp baking powder")
    print(f"  {(3/4)*P} dl flour")
    print(f"  {(75/4)*P} g butter")
    print(f"  {(1/4)*P} dl water")

def calc_mix_time(P):    return 10 + P
def calc_baking_time(P): return 30 + (P * 3)

def print_recipe(P):
    calc_recipe(P)
    mix  = calc_mix_time(P)
    bake = calc_baking_time(P)
    print(f"Mixing: {mix} min  Baking: {bake} min  Total: {mix+bake} min")

print_recipe(4)

Lab 3: Data structures (three implementations)

Same problem, three different data structures

All three implement a word dictionary with insert, lookup, and delete. The live demo is on the last card, the Python dict, which is the cleanest and most natural approach.

Approach 1 · Parallel Lists Two lists synced by index position. Simple but fragile.
Approach 2 · Tuples List of (word, definition) tuples. More structured, still O(n).
Approach 3 · Dict ★ Built-in dict. O(1) lookup. The natural fit. Try it live.
L3 · Approach 1
Word book: using two lists

Two synchronized lists: words[] and defs[]. The position of a word in one list always matches its definition in the other.

Parallel ListsIndex syncO(n) lookup
L3-1.py
def insert(words, defs):
    word = input("Enter word to insert: ").strip()
    definition = input("Enter definition: ").strip()
    if word in words:
        print(f"'{word}' already exists.")
        return
    words.append(word)
    defs.append(definition)
    print(f"Inserted '{word}': '{definition}'")

def lookup(words, defs):
    word = input("Enter word to lookup: ").strip()
    if word in words:
        i = words.index(word)
        print(f"You looked up {word}: {defs[i]}")
    else:
        print(f"'{word}' not found.")

def delete(words, defs):
    word = input("Enter word to delete: ").strip()
    if word in words:
        i = words.index(word)
        words.pop(i)
        defs.pop(i)
        print(f"Deleted '{word}'.")
    else:
        print(f"'{word}' not found.")

def main_lists():
    words, defs = [], []
    while True:
        choice = input("1.Insert 2.Lookup 3.Delete 4.Exit: ").strip()
        if   choice == "1": insert(words, defs)
        elif choice == "2": lookup(words, defs)
        elif choice == "3": delete(words, defs)
        elif choice == "4": break

main_lists()
L3 · Approach 2
Word book: using tuples

Stores each entry as a (word, definition) pair inside a list. More structured than parallel lists, but still requires iterating through everything to find a match.

TuplesList of pairsO(n) lookup
L3-3.py
def insert(entries):
    word = input("Enter word to insert: ").strip()
    definition = input("Enter definition: ").strip()
    for w, d in entries:
        if w == word:
            print(f"'{word}' already exists.")
            return
    entries.append((word, definition))
    print(f"Inserted '{word}': '{definition}'")

def lookup(entries):
    word = input("Enter word to lookup: ").strip()
    for w, d in entries:
        if w == word:
            print(f"You looked up {word}: {d}")
            return
    print(f"'{word}' not found.")

def delete(entries):
    word = input("Enter word to delete: ").strip()
    for i, (w, d) in enumerate(entries):
        if w == word:
            entries.pop(i)
            print(f"Deleted '{word}'.")
            return
    print(f"'{word}' not found.")

def main_tuples():
    entries = []
    while True:
        choice = input("1.Insert 2.Lookup 3.Delete 4.Exit: ").strip()
        if   choice == "1": insert(entries)
        elif choice == "2": lookup(entries)
        elif choice == "3": delete(entries)
        elif choice == "4": break

main_tuples()
L3 · Approach 3
Word book: using a dictionary ★ Live demo

Uses Python's built-in dict, the most natural fit. Direct key→value mapping with O(1) average lookup. The cleanest of the three.

DictHash tableO(1) lookup
Live Demo
L3-2.py
def insert(d):
    word = input("Enter word to insert: ")
    definition = input("Enter definition: ")
    if word in d:
        print(f"'{word}' already exists.")
    else:
        d[word] = definition
        print(f"Inserted '{word}': '{definition}'")

def lookup(d):
    word = input("Enter word to lookup: ")
    if word in d:
        print(f"You looked up {word}: {d[word]}")
    else:
        print(f"'{word}' was not found.")

def delete(d):
    word = input("Enter word to delete: ")
    if word in d:
        del d[word]
        print(f"Deleted '{word}'.")
    else:
        print(f"'{word}' was not found.")

def main_dic():
    d = {}
    while True:
        choice = int(input("1.Insert 2.Lookup 3.Delete 4.Exit: "))
        if   choice == 1: insert(d)
        elif choice == 2: lookup(d)
        elif choice == 3: delete(d)
        elif choice == 4: break

main_dic()

Lab 4: Object-oriented programming

L4
Phonebook: OOP with file I/O

A full phonebook class. Supports multiple names (aliases) per number, persistent save/load, and a command-line interface dispatched via lambda dict.

ClassOOP File I/OAliases Lambda dispatch
Live Demo

Use the buttons below or type a command directly. Try: add · lookup · alias · change · remove · list

Phonebook ready. Select an action above or type a command.
phoneBook>
Commands add <name> <number>  ·  lookup <name>  ·  alias <name> <alias>  ·  change <name> <new_number>  ·  remove <name> <number>  ·  list
L4.py
class phoneBook:
    def __init__(self):
        self.entries = {}  # number -> list of names (aliases)

    def add(self, name, number):
        if number not in self.entries:
            self.entries[number] = []
        if name in self.entries[number]:
            print(f"{name} already exists for {number}")
        else:
            self.entries[number].append(name)
            print(f"Added {name} with number {number}")

    def lookup(self, name):
        matches = [num for num, names in self.entries.items() if name in names]
        if not matches:         print(f"{name} not found")
        elif len(matches) == 1: print(f"{name}'s number is {matches[0]}")
        else:                   print(f"{name} has multiple numbers: {', '.join(matches)}")

    def alias(self, existing_name, new_name, number=None):
        matches = [num for num, names in self.entries.items() if existing_name in names]
        if not matches: print(f"{existing_name} not found"); return
        if number is None: number = matches[0]
        if new_name in self.entries[number]:
            print(f"{new_name} already exists for {number}")
        else:
            self.entries[number].append(new_name)
            print(f"Added alias {new_name} for {existing_name} ({number})")

    def change(self, name, new_number, old_number=None):
        matches = [num for num, names in self.entries.items() if name in names]
        if not matches: print(f"{name} not found"); return
        if old_number is None: old_number = matches[0]
        self.entries[new_number] = list(self.entries[old_number])
        del self.entries[old_number]
        print(f"Changed {name}'s number from {old_number} to {new_number}")

    def remove(self, name, number):
        if number not in self.entries or name not in self.entries[number]:
            print(f"{name} with {number} not found"); return
        self.entries[number].remove(name)
        if not self.entries[number]: del self.entries[number]
        print(f"Removed {name} ({number})")

    def list_entries(self):
        for num, names in self.entries.items():
            print(f"{num}: {', '.join(names)}")

    def run(self):
        commands = {
            "add":    lambda a: self.add(a[0], a[1])    if len(a)==2 else print("add <name> <number>"),
            "lookup": lambda a: self.lookup(a[0])        if len(a)==1 else print("lookup <name>"),
            "alias":  lambda a: self.alias(*a[:3])       if 2<=len(a)<=3 else print("alias <name> <alias>"),
            "change": lambda a: self.change(*a[:3])      if 2<=len(a)<=3 else print("change <name> <number>"),
            "remove": lambda a: self.remove(a[0], a[1]) if len(a)==2 else print("remove <name> <number>"),
            "list":   lambda a: self.list_entries(),
        }
        while True:
            parts = input("phoneBook> ").strip().split()
            if not parts: continue
            if parts[0] == "quit": break
            if parts[0] in commands: commands[parts[0]](parts[1:])
            else: print("Unknown command")

phoneBook().run()

What I learned

The right data structure removes code.

The word book was written three ways: two lists, tuples and a dict. With two lists, every insert and delete has to keep both in step. With a dict that problem is gone, and lookup is faster too.

Classes keep data and rules together.

In the phonebook, the numbers and the functions that change them live in one class, so the commands only call methods and never touch the data directly.