Introduction to Python and Google Colab
Introduction to Python and Google Colab
What a Colab notebook actually is
Google Colab is a hosted Jupyter notebook: a document made of cells, attached to a Python process running on a Google machine. There are two kinds of cell - code cells, which execute Python, and text cells, which hold formatted notes. You run a code cell with Shift+Enter.
The Python process behind the notebook is called the runtime (or kernel), and understanding it prevents most beginner confusion. The runtime holds the current name bindings created by code that has actually executed.
A name can be rebound or deleted, and its binding disappears when the runtime ends; creation order does not determine name lookup. The runtime has no knowledge of where cells sit on the page.
The single most important fact: cells run in the order you run them
A notebook looks like a script, and it is not one. Nothing runs until you run it, and you can run cells in any order, repeatedly, and after editing them.
The small number in brackets to the left of a code cell - [1], [2], [3] - is the execution counter: each counter shows that cell's most recent execution number.
If a cell runs again, its displayed counter advances and does not retain its earlier number. Out-of-order counters can reveal that the latest execution order differs from page order, but they do not reconstruct every earlier run.
Worked example. Suppose one cell contains count = 4 and a second contains count = count * 3. Run the first, then the second, then the second again.
The runtime evaluates the right-hand side each time using the current value, so count becomes 4, then 12, then 36. Nothing about the notebook's layout prevents you from running a cell twice, and the runtime simply does what you asked, twice.
The habit that makes a notebook trustworthy is Runtime, then Restart runtime and run all. That clears every variable and executes the cells strictly from top to bottom. If the notebook still produces the results you expect, the visible code really does generate them.
If it fails, the earlier results depended on something no longer in the notebook - a deleted cell, an edited value, or a variable typed into a cell that was later changed.
A related trap: a saved notebook can preserve output representations, including text, structured data and images, but those saved outputs are records of past runs, not live runtime state.
Saved code and output do not recreate variable bindings. A NameError means the referenced name is not bound in the current runtime; it does not by itself prove that the runtime is new or entirely empty.
Colab runtimes also disconnect after idleness and are recycled, discarding variables and any files written to the temporary local disk. Anything you need to keep should be saved to Drive or downloaded.
Displaying results: two different behaviours
Colab normally displays an unsuppressed final expression, which is why typing 2 + 3 alone in a cell shows 5; a trailing semicolon can suppress that display. print() is different: it writes output wherever it is called, including inside loops, and returns None.
A cell ending in x normally shows the value of x as a result; print() or display() can show additional values in a cell.
A line beginning with ! is sent to the shell rather than to Python, which is how packages are installed: !pip install followed by a package name.
Variables, names and types
Assignment binds a name to an object: n_trials = 25. Three points follow.
- The name has no type; the object does. Python is dynamically typed, so a name can be rebound to a value of any type. type(n_trials) reports the type of the value currently bound.
- Assignment is not comparison. A single = assigns; a double == tests for equality and produces True or False. Using the wrong one is a common early error.
- Names are case-sensitive, cannot begin with a digit, and should not shadow built-in functions. Writing sum = 10 shadows the bare name in the current namespace: sum now refers to the integer, so sum(values) raises a TypeError because an integer is not callable. The built-in function itself remains accessible as builtins.sum after import builtins; deleting the shadowing name or restarting the runtime restores bare-name lookup.
The core types for early work are int (whole numbers), float (decimals), str (text in quotes) and bool (True or False).
Arithmetic, and the two division operators
With x = 7 and y = 2:
Expression | Value | Type | Meaning |
|---|---|---|---|
x + y | 9 | int | Addition |
x - y | 5 | int | Subtraction |
x * y | 14 | int | Multiplication |
x / y | 3.5 | float | True division - this successful operation returns a float |
x // y | 3 | int | Floor division - discards the remainder |
x % y | 1 | int | Remainder |
x ** y | 49 | int | Exponentiation |
For built-in int and float operands, a successful / operation with a nonzero divisor and a representable result returns a float, even when the quotient is exact: 8 / 4 gives 2.0 rather than 2.
Division by zero raises ZeroDivisionError, and a quotient outside the float range can raise OverflowError. Use // when you genuinely want a whole number of whole groups.
Types do not convert themselves
For mixed string-and-number arithmetic, Python does not implicitly turn a numeric-looking string into a number. "3" + "4" gives "34", because + means concatenation for two strings, while 3 + 4 gives 7.
Mixing them - 3 + "4" - raises a TypeError rather than guessing which arithmetic you meant. If the text should be a number, parse it with int("3") or float("3.5").
Conversion in the other direction can happen through formatting: f"{3}" produces the text "3". input() and ordinary unparsed text-file reads yield strings, while binary reads yield bytes and parsers such as JSON can produce numbers or other types.
A first taste of data
A list holds several values in order: readings = [12, 19, 7, 23]. Indexing starts at zero, so readings[0] is 12. Built-in functions cover the basics: len(readings) gives 4, sum(readings) gives 61, min and max give 7 and 23.
A mean is then sum(readings) / len(readings), which is 15.25. The wider catalogue of commands and functions belongs to the sibling concept; what belongs here is knowing that these pieces combine in one line and that the result is a float because / was used.
Error messages are instructions
- NameError - a name is not defined in the runtime. Usually the defining cell has not been run in this session, or the name is misspelled or differently capitalized.
- TypeError - an operation was applied to incompatible types, most often text where a number was expected.
- SyntaxError - Python could not parse the line. Look at the line above the one reported as well, since an unclosed bracket reports on the following line.
- IndentationError - indentation is part of Python's syntax, not decoration, and must be consistent.
- ZeroDivisionError - division by zero, frequently from an empty list whose length is 0.
Read the last line of the traceback first: it names the error type and the problem, and that is usually all you need.
A code cell in Colab contains the single expression 9 / 4.
What value is displayed, and what is its type?
Mark Yourself Question
- Grab a piece of paper and try this problem yourself.
- When you're done, check the "I have answered this question" box below.
- View the solution and report whether you got it right or wrong.
In a Colab code cell, using only built-in Python and no imported libraries, compute the mean of the six values 4, 8, 15, 16, 23 and 42.
Give the code you would write, state exactly what is displayed, explain why the result has the type it does, and name one variable name you should avoid here and why.