INF1-IP: Week 3
Lecture 4 - Repetition 1: Loops
- Lecture slides
- Self-guided notebook (right-click → Save As... then remove the .txt part so it is saved as an .ipynb)
Learning outcomes
- Repeating code with
whileandforloops - Generating sequences of integers with
range() - Building totals and counts with accumulators
- Altering loop flow with
breakandcontinue - Using
passas a placeholder for an unfinished body - Tracing nested loops
Key terms
Click to expand.
Iteration
The act of repeating a process.
Loop
A control flow structure that repeats code according to a particular condition
Iterable
An object that can be iterated over, such as a list, string, or
range().Accumulator
A variable whose value is gradually constructed over the course of multiple iterations of a loop.
Nesting
Putting multiple control flow structures inside of one another.
Infinite loop
A loop that never ends, often completely consuming or even crashing the program that runs it.
New syntax
Click to expand.
whileA loop that repeats its body while the condition in its header is true (unless its body exits early with
break).forA loop that runs its body once for each item supplied by an iterable.
inA keyword used in the head of a
forloop to iterate through a sequence.range(start, stop, step)A function that generates integers from
startup to but not includingstop, takingstepsteps at a time. When not provided,startdefaults to 0 andstepto 1.breakA keyword that immediately exits the nearest enclosing loop.
continueA keyword used to skip the rest of the current iteration of a loop and begin the next one.
passA keyword that does nothing and can be used as a placeholder for an unfinished body. It does not skip an iteration; that's
continue!
Further practice
- Official Python tutorial:
forandrange()andbreakandcontinue - W3Schools:
whileloops,forloops, andrange - Helsinki Python MOOC: Simple loops, Loops with conditions, and More loops
Lecture 5 - Collections 1: Lists, sets, and dictionaries
- Lecture slides
- Self-guided notebook (right-click → Save As... then remove the .txt part so it is saved as an .ipynb)
Learning outcomes
- Storing data in lists, sets, and dictionaries
- Creating, accessing, and updating each type of collection
- Looping over elements in each type of collection
- Different ways of copying and changing each type of collection
Key terms
Click to expand.
List
A data structure (
list) that keeps data in order using integer indices.Set
A data structure (
set) that keeps data unordered and deduplicated.Dictionary
A data structure (
dict) that keeps data in an ordered collection of key-value pairs.Index
A unique value that points to an item in a collection. In a list, this is an integer; in a dictionary, this is the key.
Key
A value used to look up an entry in a dictionary. Can be a string or a number.
Immutable type
A type whose objects cannot be changed after creation. Includes
str,int,float, andbool.Mutable type
A type whose objects can be changed after creation. Includes
list,set, anddict. Multiple names can refer to the same mutable object, so changes may be visible through all of them.Shallow copy
A copy of a collection, created using
.copy(), that only creates a copy of the top-level collection, leaving any nested collections to point to their original locations in memory.
New syntax
Click to expand.
[a, b, c]A list containing the items
a,b, andc; indexed by the integers0,1, and2.{a, b, c}A set containing the items
a,b, andc. Adding an item already present leaves the set unchanged.{a: 1, b: 2, c: 3}A dictionary containing the keys
a,b, andc, mapping on to the values1,2, and3, respectively.list()A function that (when empty) creates a new list or (when passed a set) converts a set to a list.
set()A function that (when empty) creates a new set or (when passed a list) converts a list to a set.
list[index],dict[key], andstring[index]Accessing a list item by its index, a dictionary value by its key, and a string character by its index. Remember, indices in Python start at 0!
len()Returns the length of a string, list, set, or dictionary.
in(when used outwithforloops)Membership operator that checks whether an item is present in a list, set, or dictionary.
KeyErrorA type of error that highlights when you're trying to access a non-existing key in a dictionary
List methods
list.append(item)Add
itemto the end oflist.list.insert(index, item)Add
itemtolistat positionindex.list.extend(list_2)Adds the items from
list_2individually to the end oflist.list.pop(index)Remove the item at position
indexfromlist. If not providedindex, removes the last item in the list.list.remove(item)Removes the first occurrence of
itemfromlist.list.copy()Creates a shallow copy of
list.
Dictionary methods
dict.values()Provides a view of the values in
dictfor iteration. It does not create a list.dict.update({key: value})Adds or updates each key-value pair from the supplied dictionary. Any new keys are added and existing keys receive the new values.
dict.pop(key)Remove the key-value pair at
keyfromdict.dict.copy()Creates a shallow copy of
dict.
Set methods
set.add(item)Adds
itemtosetif it is not already present.set.copy()Creates a shallow copy of
set.
Further practice
- Official Python tutorial: Data structures - only sections 5.1 "More on Lists", 5.4 "Sets", and 5.5 "Dictionaries"; the others will come in later lectures.
- W3Schools: Lists, Sets, and Dictionaries.
- Helsinki Python MOOC: Lists, Dictionary, and References (up to and including "Copying a list").
Tutorial
Tutorial 2: EDIZA has you practice the content of the first three weeks of the semester while diving into the early history of AI chatbots.
- Interactive notebook (right-click → Save As... then remove the .txt part so it is saved as an .ipynb)
- Note that this notebook was created to be used in Notable; its interactive checker cells might not work in every environment.
Key terms
Click to expand.
Symbolic AI
An approach to AI that represents information explicitly using symbols and rules for manipulating them.
ELIZA
Joseph Weizenbaum's early chatbot, described in 1966. Its DOCTOR script used patterns and response rules to imitate aspects of a psychotherapist's conversation.
Tokenisation
Breaking text into smaller pieces, called tokens, for a program to process. EDIZA uses words as tokens; other systems may use smaller pieces.
Barnum effect
Treating a broad personal description as if it were specifically accurate about you.
ELIZA effect
Attributing understanding to a computer because of the responses it gives.
Assessment
No assessment this week.