print("This is a code cell.")
print("")
print("Any Python code you type in this cell will be run when you press the 'Run' button")
print("up there, or when you press any of the keyboard shortcuts you just learned.")
print("")
print("If the code evaluates to something, or if it produces output, that output will be")
print("shown beneath the cell after you run it.")
print("")
print("Let's keep on going. Press Shift-Enter to see what this cell produces and keep going")
print("with our exercise.")
Intro to Google Colab (and some other tips and tricks)
Google Colab is a cloud-based notebook-style platform for programming in Python (among other languages), which allows you to intersperse executable code with chunks of text like this. It lets you (mostly) avoid the command line, and results in a file that is easy to read and easy to share with others.
We’ll be using Colab for in-class exercises and for many of the homework assignments.
Let’s get started!
Colab makes it easy for me to share notebooks with you, and for all of us to install any required libraries on a single platform. (This is a big reason why we’re using Colab in this class). One caveat about working with notebooks on Colab is that they are shared with you in a read-only format.
To get started, your very first step should always be to choose File > Save a copy in Drive
from the menu at the top of the page, and make all future edits/modifications on that copy.
In general, I recommend naming the file something with your name in it so as to tell it apart from the original.
NB: If you are an advanced Python user and you’d prefer to use git/GitHub to keep track of your notebooks, I will also maintain a repsitory of class notebooks here.
And off we go!
A notebook consists of a number of “cells,” stacked on the page from top to bottom. Cells can have text or code in them.
You can add a new text cell or a code cell by using the + Code
or + Text
button at the top of the page.
When you click one or the other of those buttons, it will add a cell right below the cell you have currently selected. If your cell ends up in the wrong place, you can click the up or down arrow over there on the far right of the cell to move it up or down, until you get it to the spot you intended.
Your first cell
Let’s make a text cell!
To make a new text cell below this one, do this: * Click on this cell to select it. * Click the + Text
button at the top of the page. * Type some stuff and press Shift-Return
(or Shift-Enter
on some keyboards).
Colab will “render” the text and display it on the page in rendered format. You can hit Return
or Enter
, or double-click the cell, to edit its contents again.
In Colab, you can just use the formatting options at the top of the cell to format the text.
NB: If you are curious as to why the formatting options insert some special characers into the text, it is because Colab formats text using a language called Markdown. If you want to learn more about Markdown, here is a tutorial, although I prefer to just consult a cheat sheet like this one.
Exercise: Make a text cell with some formatting using Markdown
Here is your first exericse: Insert a new cell just below this one, and us the formattinng palate to make some text bold, some text italics, and some:
- text
- in
- a
- list
Three helpful shortcuts
Instead of pressing Shift-Enter
, you can press Alt-Enter
(or Option-Return
on a Mac) to render the current cell and create a new cell just below. New cells will by default be Code
cells.
To change a code cell to a text cell, you can press Control-M M
.
To change a text cell to a code cell, you can press Control-M Y
.
Code cells
Code cells– which are actually the default type of cell in Colab– use the same set of commands as text cells, but instead of rendering the text, they run chunks of code.
Let’s not beat around the bush! Press Shift-Enter
again to run your first chunk of code.
Sidenote: You just learned how the print function works in Python 3!
And, therefore, an obligatory meme (via @cszhu on Twitter):
A bit more on printing things
Here are a few more examples of how to print things.
Here is more about print()
than you likely ever wanted to know.
Errors
If your code generates an error, it will be displayed in addition to any output already produced.
IMPORTANT: These error messages are incredibly helpful when debugging. If you get an error, read it and see if it helps point you to where the problem is in your code.
So let’s make ourselves an error. We’ll commit the cardinal sin of dividing by zero.
Run the cell below.
print("Here is some printing.")
print("And now here is an error:")
1 / 0
Variables
The major difference between Python and R– at least in terms of getting started– is that in Python, you can only use =
to assign variables.
Let’s assign some variables:
= 0
x = .5
y = True # note another difference b/t R and Python: Boolean (T/F) values are not all caps z
Exercise: Write some code to print out the variables we’ve just assigned
# your code here
Another neat thing about notebooks:
Any variables you define or modules you import in one code cell will be available in subsequent code cells.
So for instance, if you run the cell below:
import random # a useful module that we'll come back to later
= ["cheddar", "daguerrotype", "elephant", "flea market"]
stuff
print(random.choice(stuff)) # choice is a function that-- you guessed it-- makes a random choice
… then in subsequent cells you can do this:
print(random.choice(stuff)) # choice is a function that-- you guessed it-- makes a random choice
Exercise: Write some code and then run it
Using the previous two code cells as a guide… - Reassign the “stuff” variable with four different words - Use the “choice” function, as above, to randomly print one of those four words
# your code here
FYI: “stuff” is a list, which is a type of value in Python which represents a sequence of values. It’s a very common and versatile data structure and is often used to represent tabular data (among other information).
More on lists in tonight’s homework. But to conclude for the day:
Keyboard shortcuts
In Colab, most keyboard shortcuts start with Control-M
. After that,
Z
undoes the previous action (inside a cell)H
is find and replaceA
inserts a code cell aboveB
inserts a code cell belowD
deletes a cell
Saving / submitting your work
In theory, Colab will save your work as you type. If you want to make double sure that your work is saved, Cmd-S
at any time will save your notebook. (You can also select File->Save
from the menu up there.
When it comes time to submit a notebook for evaluation, select File > Download as > Download .ipynb
. This is the file that you should submit.
NB: Please do not just submit links to Colab notebooks as the grader will need to ensure that you’ve stopped working and submitted your notebook by a particular date.
Viewing / editing notebooks outside of Colab
You may have already noticed that just double-clicking on an .ipynb
file that you’ve saved to your computer doesn’t open it. The technical explanation for this is that Colab runs as a cloud-based server, and every time you do something to / in a notebook file, it invovles a call to that server to figure out what to actually do.
Sometimes, however, you just want to easily view or share an .ipynb
file without a server. In many (but not all) cases, .ipynb
files hosted on GitHub will render very nicely. To wit, click here to see how this notebook holds up. But in cases where GitHub fails, or when the file is hosted elsewhere, nbviewer is good to know about. Note that the notebook needs to already exist online for nbviewer to work.
For times that you don’t have internet access, or if you ever want to wean yourself off of Google products, you can also open/edit .ipynb
files on your computer. To this, I recommend installing Anaconda Navigator, which is free and open source. Once you install that and run it, you will find that a bunch of other software/packages have been installed, which just require that you click to run then. Click on the option for Jupyter Notebook and navigate to your .ipynb
file from there.
This notebook was created by Lauren Klein in Fall 2019, incorporating materials from Alison Parish and Jinho Choi. It was updated in Fall 2021, Spring 2021, and Fall 2022.