We'll get started today talking about some of the most basic building blocks of working with code. Many bootcamps and online coding platforms hide these details to make getting started easier for you. But today we're going to start by covering these topics because they are the foundational ideas of all digital machines and will lay a solid groundwork to start with this semester.
Table of contents for the topics today: (Click each to jump down to the corresponding section.)
The command line is a type of user interface. Usually when we think about user interfaces we think about interactive motion graphics, which we usually call GUIs for graphical user interfaces. The command line is a user interface too, but it is an interface primarily operated through text.
There are many reasons why we are saddled with this text-based mode and metaphor for interacting with computer programs. If you would like to learn about some history of the command line and how it came to be, you can watch this video where I walk through part of that story (25 min). I made this for my "Radical Software" class last semester, so please ignore that on the title slide. I also refer to a twitter project, which we won't be doing in this class.
Suffice it to say, the command line (sometimes called the terminal, or a shell) is a computer program in which you type the names of other programs (called commands) which the shell then executes. These commands can be common operating system utilities, like listing the contents of a folder, and they can also be computer programs that you write, which is what we'll get started with today.
As I explain in the above video, a big part of the persistent usefullness of the command line today is that it is often much easier to write computer programs with text-based user interfaces than with more user friendly GUIs. Often times a GUI will require dozens of extra lines just to get started, whereas a command line program can get right to algorithms or data processing without the extra code to make it more visually appealing or user friendly.
Find the command line on your computer.
On Mac you can access the command line with a program called Terminal. Open up Finder, go into the "Applications" folder, look for a folder called "Utilities", and within that, find and double-click on "Terminal". Or you can use a Spotlight search (⌘-SPACE) and search for "Terminal".
On Windows, the easiest way is probably to download and install the Bash shell provided by Git.
When you open that, it should look something like this, but probably with different colors:
Conveniently, the VS Code text editor (which we get to below) comes bundled with its own integrated Terminal-style command prompt, and this is probably the most convenient way for you to invoke commands in the Terminal this semester. The integrated command line in VS Code makes it easier to run Python programs in this way as we'll see later.
Throughout the semester, whenever I am including command line instructions, I will display them in a white, fixed-width font on a black background with rounded gray corners like this:
$ echo "Hello, world" Hello, worldOr for shorter commands, I'll use a single line of white, fixed-width text on a black background:
like this
.
(I try to make this formatting easily visible for everyone, even those who might have different seeing abilities. If I can help make this more legible for you, please let me know!)
The dollar sign $
is a
commonly-used symbol to signify the prompt where you can
type commands. Your prompt may look different — this
is also a customizable setting. Some shells use a hash
symbol #
for this purpose. Any
text that I include after this symbol will be valid syntax
that you can copy/paste into your command line.
You should not type the dollar sign. Any lines that I include after (lines not beginning with a dollar sign) are meant to indicate what the command line may display back to you in response to your command. Sometimes you are meant to see the exact same text as me, other times you may be expecting different but similar text. I will try to always explain clearly to you what you should expect to see.
Try typing the command above. In this case, you should get the same result as me.
We won't be using too many command line instructions. I will explain them as we need them. For now, here are a few useful ones:
pwd
:
print working directory,
displays the name of the current directory that you are
in. In the command line
context, folders are
called directories.
cd
:
change directory,
changes the directory (folder) that you are currently in.
ls
:
list, lists the contents
of the current directory. That is a lower-case "L", not
the number "1".
If a command is running and you want to stop it, you can
type CONTROL-C. If you want to exit your shell program, you
can type exit
or press CONTROL-D,
then you can close the window.
It is absolustely essential this semester that you create a simple scheme for organizing your work into folders and subfolders by week, exercise, and project. Many students seem to resist this organization technique. I do wish to respect everyone's different work patterns and the ways we all prefer to organize our thinking. But when working on coding projects, folders and subfolders are a key organizational technique. Computer programs will often reference other digital objects like images, multimedia, data files, or other programs, and folders are the default way of grouping these resources together. And when it comes time to bundle up your work to share with others, folders of code will typically be used to distribute collections of functionality as a library, app, or full application. Simply putting all your work into one large folder and searching for things may work for you, but it will not work for the tools we'll be using.
Start by creating a folder for our class for the
semester. (I recommend you put it in your
Documents
folder or a similar
location on your computer, but that is up to you. Within
that, I also recommend that you create a folder for coding,
and a folder for the other work you'll be doing this
semester, but that is also up to you.) What is essential is
that within your class folder, you create subfolders for
each technical tutorial, and for your three unit projects.
So your folder structure my look like this so far:
Most terminal programs now offer some nice and convenient
interaction between your GUI and the command line. So in
your Terminal window, you may type
cd
(note the space) and then
actually drag the "Unit 1 tutorial 1" folder into the
Terminal and press enter.
Now type pwd
, and you should see something similar to this:
$ pwd /Users/rory/Documents/Code as a Liberal Art/Coding/Unit 1 Tutorial 1What you see will be slightly different depending on where you've put your folder. What you see here is called a path: a textual representation of a string of folders and subfolders. Paths are extremeley important and a way to locate resources on a computer.
A path is a key part of the URL for any webpage you may visit. Look at the URL for this webpage for example:
https://classes.codeatlang.com/code-as-a-liberal-art/2023-spring/unit1-tutorial1-lesson.html
Notice the path (the part that comes after the server name) and think about what you know now about how this indicates a folder structure on our webserver.
Every digital object on your computer (e.g. every image, file, or program) will have a path indicating where it is located, and the path is the way that you would tell a computer program how to access that digital object. We will talk about paths more throughout the semetser.
Look at Terminal and Finder or Explorer side-by-side and notice the similarities. They are both two different views of the same arrangement of data: files organized into folders with paths. Note folder names, folder contents, and path (in Finder, this is shown in the status bar at the bottom of the window).
Next let's introduce Python in the command line context.
From the command line, you should simply be able to
type python3
to invoke the
Python shell:
$ python3 Python 3.8.3 (v3.8.3:6f8c8320e9, May 13 2020, 16:29:34) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>You may not see precisely the same output, but it should be similar. If you see
Python 2.7.x
let
me know.
Noteworthy here is that the prompt has changed
to >>>
. This is to indicate
that you are not in the operating
system shell, but rather in the
Python shell. At this point, you can no
longer type the regular shell commands. For
example, cd
and pwd
will give you an error
message. Instead, you can type Python commands. Let's
experiment with a few. Try this:
>>> print("Hello!") Hello
If you get an error message likebash: syntax error near unexpected token ...
, it means you are not in the Python shell. Typepython
, and make sure that you see the Python command prompt:>>>
You have just typed and executed a single
line of Python code. This line is comprised of
one command: print()
. The print()
command is simple: it displays a message to the user (i.e.,
it "prints" it to the screen). What does it print? Whatever
you specify in between the parentheses, which is what we
call the arguments to
the command.
In this case, the argument
is "Hello"
: a bit of text
enclosed in quotes (""
),
which, in computer programming, we call
a string. Computers can process numbers and
text (strings), as well as other digital objects like
images, video, etc. Let's look at some other Python
commands.
In the Python shell, if you simply type a number, Python will evaluate that expression and display the result, basically just printing the value:
>>> 10 10 >>> 5 5
Note that strings are different
from numbers, even if they may seem like the
same value to us. Note the difference in output here. Python
uses single quotes ' '
or double-quotes "
"
to indicate string values. Think of
single and double quotes as interchangeable in Python for now
and you can use either, but you must use the same end quote as
you used for the beginning of a string.
>>> "Hello" 'Hello' >>> 10 10 >>> "10" '10'
Note that the number 10
and the
string '10'
are not equal. We can check values for
equality with two equal signs ==
. For example:
>>> 10 == 5 + 5 True >>> 10 == "10" False
You can also create variables, set them to
values, and do various operations on them, such as
arithmetic. In Python, like in most programming languages,
we have addition +
, subtraction -
,
multiplication *
and division /
.
>>> x = 10 >>> y = 5 >>> x + y 15 >>> x / y 2.0 >>> x * y 50
And we can combine commands in various ways, for example
to print()
the result of an operation on a
variable:
>>> print(x-1) 9
We can also use things called control
structures, such as the if
command, to
change the way code instructions are executed:
>>> if x > 5: ... print("Greater") ... else: ... print("Less than") ... Greater
Note that the command prompt changed for a moment to
dots: ...
. This notation indicates that
I am inside a code block, in this case,
an if
statement. This code block
is initiated by the colon :
.
Usually Python ignores
all whitespace. So x = 5
is the
same as x = 5
,
and print("Hello")
is the same
as print( "Hello" )
. You can
add spaces for clarity and readability. However, at the
start of a line, spaces are called indentation
and they are very important in Python: they indicate that you
are in a code block. In the above example,
both print()
statements
are indented because they are in a way part of
the if
statement.
The last line containing only ...
is
created by pressing ENTER with no spaces and no other text. The
empty line ends the if
statement, instructing
Python to evaluate the above four lines.
The if
statement will run differently with
different values:
>>> x = 2
>>> if x > 5:
... print("Greater")
... else:
... print("Less than")
...
Less than
(When working through coding examples, I will indicate any modified code in orange with a thin dashed underline. Again, I hope to accommodate all different types of seeing abilities and if this styling is not super clear, please let me know how I can make it better!)
Typing commands like this into the Python shell can be a good
way to learn, but it is a very limited way to work. Algorithms
are all about automation: writing some
instructions and then running them on different inputs. In other
words, you don't want to have to manually modify the value
of x
each time, you want an if
statement that automatically responds to some data or user
input. To achieve this, we'll have to exit the Python shell and
create and executable Python computer program by typing code
into a file, which we can then run many many
times without re-typing.
To exit the Python shell back to the command line, you can
type CONTROL-D or exit()
.
A file is a collection of data, grouped together into one atomic unit, which exists on a computer and is identified by a name and a path.
Files are managed on computers by something called file systems. The file system is the entire scheme of folders, subfolders, and paths that your computer uses to organize and manage data as atomic files. The file system is one part of your operating system (e.g., Mac, Windows, Linux) along with other system utilities.
Files can be of all types: images, sounds, videos, games. They can be fancy text with lots of formatting like a Microsoft Word file, or they can be simple text with no formatting, which we call plain text, and which are usually opened by a program like Text Edit.
File types are usually specified by filename
extensions: the part at the end that starts
with a "dot" .
. The file extension
tells your operating system
which program to use to
open a given file. For example, if you double-click a
.doc
file, your computer will probably
open it with Microsoft Word; .html
files are opened with your default web
browser; .pdf
files will be opened with
Preview (Mac), QuickLook (Windows) or Acrobat Reader; and image
files like .jpg
or .png
will probably be opened with
Preview or QuickLook.
Please adjust the preferences for Finder (Mac) or Explorer (Windows) so that your operating system will not hide file extensions to you. Understanding file extensions is a key part of digital literacy, and knowing the extensions of files will be crucial for accessing them via computer programs this semester.
Computer programs are just files! They are usually plain text files on your computer, with a file extension telling your operating system that they can be run.
(jump back up to table of contents)To create computer program files, you need a text editor: a program that lets you type and save text as plain text, without any fancy formatting like Microsoft Word offers.
The text editor that we will use this semester is a very useful, open source tool called VS Code. The fact that it is open source means that the computer program files and algorithms of this tool are freely, publicly available, not proprietary or hidden. That means you can view the source code for this tool! In fact, the full source code is posted here on GitHub. Feel free to have a look. This also means that if you wanted to, you could modify VS Code to change its behavior in some way, then rebuild it and run your own customized version. (A very advanced exercise, but possible!)
Open up VS Code (images to come). Start by closing all the tabs and help screens. Then, drag your "Unit 1 tutorial 1" folder into the VS Code window:
If you are prompted with this question about trust you can click 'Yes'. (If you trust me! ;) ) In the future, you should always think carefully before accepting such terms. Who is this code coming from? What does it do? Opening and running arbitrary code on your system potentially gives the authors of that code artibtrary permissions to access all of your files, data, and control of your machine. So be careful.
You should now see this folder in the sidebar. If not, click the "Explorer" icon: two little stacked rectangles.
Click File > New File. Now you can type Python syntax into this file and save it. Try this:
x = 5 if x > 5: print("Greater") else: print("Less than")Throughout the semetser, I will indicate valid Python code in a file with this fixed-width font on a light blue background. Whenever you see this, it should be valid Python code that you can copy/paste into your file. Again, if I can help make this more legible to you, please let me know!
When writing Python code in a file, you
can add comments
with #
. A comment is a note to
any humans who may be reading your code, they are ignored by
Python. Add a comment to the top of this file:
# First Python program of the semester!
x = 5
if x > 5:
print("Greater")
else:
print("Less than")
(When working through coding examples, I will indicate newly
added code in blue with a dotted underline.)
Now that you have Python commands in a file, you can save the file and run it repeatedly from the command line without retyping those instructions.
Click File > Save (or press ⌘-s on Mac or CONTROL-s on
Windows) and name this file
in_class.py
. Note the
underscore _
. Using dashes for filenames in
Python can cause errors, but using underscores is fine.
Now that you have saved the file, click back over to Terminal and type the following and you should see this output:
$ python in_class.py Less than
Possible errors:
syntax error
, you
are probably still in the Python shell. Do you
see >>>
as your
command prompt? If so, type exit()
or
CONTROL-d to exit back into the command line.
No such
file or directory
, you are not "in" the folder
containing your file. To check, you can
type pwd
to see which directory
you are in, or ls
to see what
other files are in that directory. To fix the problem,
type cd
and change to the
directory
containing in_class.py
. Scroll
up to the discussion of cd
to
remember how to do this.
Great! Now we can get started coding in Python.
Hopefully this gives you some building blocks in algorithmic thinking that you can play with. The homework for this week has some opportunities for you to experiment with these ideas. Have fun!