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.
Lab 1: Functions & calculation
Calculates the total cost of a loan given principal, interest rate, and number of years.
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)
Scales a cake recipe to any number of people. Calculates ingredient amounts, mixing time, baking time, and total time.
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.
Two synchronized lists: words[] and defs[]. The position of a word in one list always matches its definition in the other.
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()
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.
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()
Uses Python's built-in dict, the most natural fit. Direct key→value mapping with O(1) average lookup. The cleanest of the three.
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
A full phonebook class. Supports multiple names (aliases) per number, persistent save/load, and a command-line interface dispatched via lambda dict.
Use the buttons below or type a command directly. Try: add · lookup · alias · change · remove · list
add <name> <number> ·
lookup <name> ·
alias <name> <alias> ·
change <name> <new_number> ·
remove <name> <number> ·
list
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 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.
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.