Introduction to Computer Science
A first course in programming, in Python, for someone who has never programmed. Values and variables, decisions, loops, functions, lists and dictionaries, files, a first look at recursion and at classes, and how to read an error, test your code and break a problem into small steps. Every program is watched running, one line at a time, and you run your own.
Lessons
- Your first program: A program is a list of instructions that the computer follows one at a time, from the top, doing exactly what is written and nothing else, so `print` shows a result and the order of the lines is part of the meaning.
- Values and types: Every value has a type, such as `int`, `float`, `str` or `bool`, and the type decides what an operation means, so `2 + 3` is `5` but `"2" + "3"` is `"23"`.
- Variables and assignment: A variable is a name attached to a value, and an assignment works out the right side first and then points the name on the left at the result, so `x = x + 1` is a step and not an equation.
- Expressions and operators: Python works out an expression by precedence, and division comes in three kinds, `/` always giving a float, `//` rounding down and `%` leaving the remainder, which together split a number into whole groups and what is left.
- Strings, indexes and slices: A string is a row of characters numbered from `0`, so `s[i]` takes one, `s[a:b]` takes from `a` up to but not including `b`, and a string can't be changed in place, only used to build a new one.
- Input and output: The `input` function always gives back a string, so a number typed in has to be converted with `int` or `float` before it is added up, and an f-string builds the sentence that `print` shows.
- Booleans and comparisons: A comparison such as `x > 3` gives `True` or `False`, `and`, `or` and `not` combine such answers, and `==` asks whether two values are equal where `=` stores one.
- If and else: An `if` runs its indented block only when its condition is `True`, an `else` runs when it isn't, and the indentation, not the line's look, says which lines belong to which branch.
- Chains of decisions: An `if`, `elif`, `else` chain runs only the first branch whose condition is true, so the order of the tests matters, while separate `if` statements each get their own turn.
- While loops: A `while` loop tests its condition before every pass and stops when it is `False`, so something in the body has to move the condition towards `False`, or the loop never ends.
- For loops and range: A `for` loop runs its body once for each item of a sequence, and `range(a, b)` counts from `a` up to but not including `b`, which is why `range(n)` runs exactly `n` times.
- The accumulator pattern: To total, count or find the biggest of many values, set a variable before the loop and update it on every pass, so that when the loop ends the variable holds the answer.
- Loops inside loops: An inner loop runs completely for every single pass of the outer loop, so a loop of $3$ inside a loop of $4$ runs its body $12$ times, which is how a program visits every cell of a grid.
- Stopping early: The word `break` leaves a loop at once and `continue` skips to the next pass, which lets a search stop the moment it finds what it wants, and a loop's `else` shows that nothing was found.
- Defining and calling functions: A `def` gives a block of code a name without running it, and each call runs the block with the arguments handed to its parameters, so one definition can be reused with different values.
- Return versus print: The `print` function only shows text on the screen, while `return` hands a value back to the caller to store and use, and a function that never returns gives back `None`.
- Parameters and arguments: Arguments are matched to parameters by position or by name, a default value fills in a parameter the caller leaves out, and a function that changes its own parameter name never changes the caller's variable.
- Scope and the call stack: Each call gets a frame of its own for its local variables, which is gone when the call returns, so two functions can use the same name for different things and a local can't be read from outside.
- Breaking a problem into functions: A big task becomes small ones when each function does one job and has a name that says which, so the main program reads like a plan, and each piece can be written and tried on its own.
- Reading an error message: A traceback names the kind of error, says what went wrong and points at the line, and reading it from the last line up, kind first, tells you what to look for before you change anything.
- Finding a bug: A bug is found by comparing what you think each line did with what it did, by printing or tracing the values at the point where they first differ, then changing one thing and running again.
- Testing your code: A test is a call with an answer worked out beforehand, and a few tests chosen to include the empty, the smallest and the edge cases catch the mistakes that a single typical example hides.
- Lists: A list holds values in order, numbered from `0`, and unlike a string it can be changed in place with `append`, `pop` and assignment to an index, so a loop can build one up as it goes.
- Two names, one list: A variable holds an arrow to a list and not the list itself, so `b = a` makes a second name for the same list and a change made through one name shows through the other, unless the list is copied.
- Tuples and unpacking: A tuple is a short fixed row of values that can't be changed, which suits a pair like a point, lets a function give back several values at once, and can be unpacked into separate names.
- Dictionaries: A dictionary pairs each key with a value and finds a value from its key directly, which is what counting how often each word appears needs, with a missing key giving a `KeyError` unless `get` is used.
- Sets: A set keeps each value once, in no particular order, and answers "is it in there?" fast, which makes removing duplicates and comparing two groups with `&`, `|` and `-` short.
- Lists of lists and records: Lists and dictionaries can hold other lists and dictionaries, so a grid is a list of rows read as `grid[row][col]` and a table of records is a list of dictionaries, each reached by indexing one level at a time.
- Reading and writing files: The `open` function connects a program to a file, a `for` loop reads it one line at a time with the newline still on the end, and a `with` block closes it afterwards, which is how data outlives a run of the program.
- A first look at recursion: A function can call itself on a smaller version of its problem, as long as a base case stops the chain, and the answer is built as the calls return one by one from the deepest.
- Classes and objects: A class is a plan for a kind of thing, each object made from it has its own attributes, and a method is a function that works on the object it is called on, whose own name is `self` inside.