Workshop: First steps with Python

About this workshop
This workshop is put together with students in mind that are familiar with some creative coding (e.g. Processing or p5.js), but have never touched Python before. If that’s you, it will hopefully explain how basic programming concepts translate into this language and familiarize you with a workflow that allows you to do ALL THE COOL THINGS that can be done with Python!
I set out to teach this in 1.5h and won’t go much into depth. If that’s what you are looking for, I highly recommend Allison Parrish’s “Reading and Writing Electronic Text” class; the latest syllabus seems to be unfolding on GitHub (using Jupyter Notebook), but you will learn much from the old one, too, which is basis to everything I will be talking about here, too. Thanks to Allison for that and for all the inspiring work she does!

When to use Python

If you got first introduced to programming in an Art or Design School, chances are that frameworks like Processing or p18.js are familiar to you - you might have created interactive sketches using those, along this pattern:

image here

Programs like this are interactive: they most likely run until you stop them or even react to a person’s input. The loop structure makes this very convenient; in every iteration we can check whether there is any input to react to, calculate stuff and display things.

Python program, in contrast to that, are usually more linear and not interactive. The take some form of input, run a computation using that input and return output along the way. Then they stop.

image here

This makes Python a great language to process data of any kind into new forms.

Add some examples usages here.

Command Line: 2 commands and how to get out of trouble

To use Python, you will need to use your computer’s Command Line application (named “Terminal” on OSX). It’s great if this is the first time you will be using this program because you will be getting used to it in no time :-) If you have experience with it already it’s also great!
Since this workshop is about Python, we will only talk about the Command Line very briefly. Most things we do on our computer are done using keyboard and mouse to interact with the graphical user interface (GUI). Maybe this makes some sense:

In the GUI:
- run programs by clicking the icon
- create/use/navigate files/folders by clicking around in finder

On the Command Line:
- run programs by using commands
- create/use/navigate files/folders by using commands

Open your Command Line, it will look a little bit like this:

The Terminal

You will see very similar text to this. The most import bit here is the ~ symbol because it shows us where we are.

The ~ symbol signifies that we are in the User's root folder.

When using the Command Line, at any moment, you are somewhere in you file system, much like when you are navigating through your browser. The ~ stands for the user root, in MAC’s finder that folder looks usually like this:

The equivalent location as seen in the Finder.

The ls command - “What is here where I am?”:
In the finder, when we click on a folder, we see the files that are inside. On the Command Line we only see what is inside the current directory (by the way directory means the same as folder, I use them both interchangeably) when we tell it to do so using the ls (stands for list as far as I know) command. Go ahead and type

ls

then hit enter.

The list command.

Again, this is equivalent to this view in the Finder:

The list command.

The cd command - “Change location!”:
To navigate to a different location, use the cd command. It stands for change directory. Often you will find your self typing ls first to see what’s in the current folder, then you see the next folder you want to go in and do so with the cd command, then you use ls again to see the files inside the directory you have changed to. A bit like this - note also that the ~ changed to Desktop when we changed location:

The change-directory (cd) command.

In your Computer’s memory system, any file or directory is really not just its name, but the whole path from the computer’s root, if you type pwd (present working directory) you will see such a path, in my case it looks like this:

I am mentioning this for one because it is interesting to know :-) but also because many many commands act on file system in some way, like ls and cd we just learned and usually all those commands can also be used with longer file paths. You can, for example list the contents of a directory even if you are not in it like this:

leoneckerts-MacBook-Pro:~ leoneckert$ ls Documents/leon/nyu

and equally not only change directories with cd one step at a time, but jump up (or down?) many directories at once. By the way, to change directory backwards (or up? or down? oh this is confusing) you use .. like this:

Hey Command Line, whatever you are doing, stop it!
Here are two more commands that will be useful. Sometime you run programs on the command line that take a while to run, but then you want to close them. Anytime you don’t see your cursor right after that default line as we see it it the windows above, a program is running. For example, here is no programming running, which means you can enter a new command:

Something is fishy here, this is not how the Command Line normally looks!

To close running programs, most of the times, you can use one of the folling key combinations.
Try this first:CTRL+C
…and if this doesn’t work, try thisCTRL+D

this should get you out of trouble most of the times :-)

A simple Python working environment

Okay, now let’s get to Python already! Python programs are written into text files with a .py extension and executed from the Command Line (this workshop explains things using a UNIX command line as you will find on Apple or Linux computers); you might know the Command Line under the name ‘Terminal’.
A good woring environment constists of a python file open in a text editor (e.g. Atom) next to a Terminal window with the project’s directory open. You can do this manually using the command learned above or use this shortcut:
Make a project folder or navigate to one that you want to work in in the Finder, then drag it into the Terminal icon and also onto the Atom (or any other text editor) icon:

Drag your project folder onto the icons to open it in the two applications.

I like to do it this way because it opens the Command Line already in the right folder (the project folder) and opens the text editor with my folder showing in the sidebar.

The two applications we need to do things with Python.

From then on, I recommned creating new files this way to make sure they are saved in the same directory:

Creating new files in our project directory.

For now, let’s create a file with a name of you choice and Python’s .py extension.

Ready to write some Python code!

Coding in Python

On your command line, type

python

and hit enter. You should see this as the beginning of the line now >>> which means you have python on your device and you are currently in a interactive python interpreter, you can code python in here, try it:

In the interactive Python interpreter

To get out of here you hit…? Do you remember? It’s CTRL+D.

If that worked, great, briefly run

python --version

to check what version you are running, for this workshop any version 2 is fine - version 3 of python is newer but slightly different, people still use both versions.

how to run Python code

We write python code into the file, save it and then run it with

python [filename]

on the Command line. Let’s try it, let’s write a line of python to the file we created before:

print"this is me coding in python!"

python-script.py

Then we save the file and run with the python command followed by the filename:

python python-script.py

Running a python script.

You just ran a python script!

syntax

If you are coming from a JavaScript background you are used to seeing many kinds of brackets and punctuations like })); or something similiar. In JavaScript, whitespace doesn’t matter (in fact your whole program might as well be on line 1) and a lot of punctuation makes up for that. In python it’s the opposite, you are forced to format you code properly, but in turn it will look much cleaner - not only because it’s formatted (indentation etc.), but also because as a result of that it doesn’t need much punctuation and brackets.

Precise formatting is something to get used to however. You have to always indent code blocks and always indent them in the same way. If one line is indented one tab and the next one (in the same block of code) is only indented 2 spaces, the program will not run.
Here is a wrong program:

Important, if you are used to using the tab key for indentation, be aware that every text editor uses its own instruction on how to handle the tab key. In the settings you can define if it should interpret the key as “a tab” or as any number of spaces (“soft tabs”) like “4 spaces”. I personally like my tab key to translate into 4 spaces, other people use 2. I’d never use tabs, that will break your code if others want to modify it. Tabs are not popular because they look like spaces, but are interpreted as “tabs” - who wants that? Nobody. If you look it up on stackome’, ‘favorite_digits’]verflow, this is the solution (PEP-8 seems to be the official Python style guide):

Tabs or Spaces?

In the Atom text editor you change the tabs like this, tick the “soft tabs” box and enter the amount of spaces you want to use:

Setting soft tabs in Atom

In other text editors it will work very similarly.

variables

Variables in python are of the usual types: integers, floating point numbers, strings, booleans. Did I forget any?
What’s different in python (different to anything else I’ve seen at least) is that you don’t have to declare a variable by using some magic words like “var num = 2” or even the type like “int num = 5”, no - In python you just name it by whatever name you give it.

# an integer variablenumber=10# an float variableother_number=7.3# an string variablemy_name="leon"# an boolean variableits_late=true

As you can see this all reads quite nicely without any extra words or symbols! You might have also noticed that before, in our first program, when we simply wrote

print"blablblabla"

to print something to the Command Line. Also, as you guessed the pound sign is what lets us add comments to our code

# this line doesn't get executed, butthis_one_does=true

Here are a few methods on different variable types - you might be familiar with simmilar operations from other languages like JavaScript:

# NUMBERSa=7b=float(a)printa# prints: 7printb# prints: 7.0c=a+bprintc# prints: 14.0d=c/aprintd# prints: 2.0e=int(d)printe# prints: 2printe==2# prints: True# remainder! (modulo, did someone say modelo?)print20%7# prints: 6a=20/7# prints: 2a=20.0/7.0# prints: 2.857142857142857a=round(20.0/7.0)# prints: 3.0print7*4# prints: 28# power of....printpow(2,4)# prints: 16# STRINGSs="banana pizza"a=s[2]printa# prints: n# slicing:b=s[1:6]printb# prints: anana c=s[1:]printc# prints: anana pizzad=s[:6]# prints: banana prints[-1]# prints: aprints[-4:-1]# prints: izz# --> everytime a : is involved it will # try to return a range of characters# where the start of the range is on the # left of the colon, the end on the right# default for start is the first letter, # default for end the last letter# if there is no colon, like in s[2] or s[-1] # we can expect a single character to be returned# we learn lists in the next section! lists are similar to arrays# here is how we turn a sentence into a list of words:k=s.split()printk# prints: ['banana', 'pizza']prints.split()[1]# prints: pizza# we can split by other characters, tookk=s.split("n")# prints: ['ba', 'a', 'a pizza']s="giraffe haengematte "prints+"!"# prints: giraffe haengematte ! # strip away whitespace or new line characters:prints.strip()+"!"# prints: giraffe haengematte!s="Hello Dear Humans!"prints.lower()# prints: hello dear humans

lists & dictionaries

These are two data structures in python, lists are the equivalent to arrays, dicionairies are very much alike JavaScript objects: key-value pairs under one variable name. There is another structure called set and probably even more I don’t even know about, but for a start lists and dictionairies is enough to know. Guess how you make a list? Just like you create any other variable, except in this case we will need some brackets: square for lists, curly for dictionaries:

my_first_list=[1,3,5,3,-2,0.2]a_dictionairy={"name":"leon","value":53}#an alternative way to declare them is:my_first_list=list([1,3,5,3,-2,0.2])a_dictionairy=dict({"name":"leon","value":0})# this might seem unecessary typing and in fact# I am not sure if there is ever a real reason to do it# that way...# I like doing it when I instatiate an empty list or dictionairy# like:total=list()# will be filled with values later

for-loops & if-statements

For loops and if statements are much like in other languages, just without brackets (unless you want them). Instead, a colon after the line that starts the loop or statement and the following block of code correctly indented. You will often loop over lists like this:

a=["lemon","lennon","lenin","leon"]forwordina:printword#prints:#lemon#lennon#lenin#leon#--> the word "word" here is just a variable name# conventionally you are using one that makes# sense for a human# alternatives works just the same:forelementina:printelement# orforsjkdfahsjkdsahina:printsjkdfahsjkdsah

even if you don’t loop over a specific list, but just want to do something x number of times, you will practically be looping of a list anyway, remember the range(x, y) function we learned above? It returns an array with numbers within a range you define. In a loop this looks like this:

foriinrange(0,10):print"this is loop number",i# prints:#this is loop number 0#this is loop number 1#this is loop number 2#this is loop number 3#this is loop number 4#this is loop number 5#this is loop number 6#this is loop number 7#this is loop number 8#this is loop number 9

Similar to this is how if statents work in python:

divisable_by_eleven=list()#is "divisable the right way to say this?foriinrange(0,80):ifi%11==0:divisable_by_eleven.append(i)printdivisable_by_eleven# prints: [0, 11, 22, 33, 44, 55, 66, 77]# orprint"some numbers i like are"," and ".join(divisable_by_eleven)# Ops! that throws an error!# prints: TypeError: sequence item 0: expected string, int found# --> that is because the join function looks for strings, but the list contains ints# there is several ways to solve this# we could have expected that aleady in the for loop for example and done this:foriinrange(0,80):string_i=str(i)ifi%11==0:divisable_by_eleven.append(string_i)print"some numbers i like are"," and ".join(divisable_by_eleven)# prints: some numbers i like are 0 and 11 and 22 and 33 and 44 and 55 and 66 and 77 and 0 and 11 and 22 and 33 and 44 and 55 and 66 and 77# great!

we just solved an error instead of REALLY covering if-statements, but there is not more to it really. Here is one more:

names=["Juan Jose","Mathura","Chino","Jenjenjen","Yuli","Aaron","Jason"]fornameinnames:# remember, "name" here is just a variable name that I am choosingifname.startswith("J"):# hey! another string method: string.startswith('...')# alternatively string.endswith('...') also exists, # these are real great!print"One of my friends whose name starts with a J:",name# prints:#One of my friends whose name starts with a J: Juan Jose#One of my friends whose name starts with a J: Jenjenjen#One of my friends whose name starts with a J: Jason

modules (and pip)

You will often see (and write) python script starting with lines like this:

importsys,osimportImagefromPILimportrandom

These are so called modules. It’s like “libraries”, it’s code someone else has written that we can import into our program and make use of. Python by itself comes with a lot of functionalities, but not all of them can just be used - but can simply be important (without even installing them). That is to keep programs light, “only take what you need”, I guess.

If we want to generate (pseudo-)random numbers for example, we need to import the “random” library.

importrandomprintrandom.random()# prints: 0.703032205798 # generates a number between 0 and 1# the random library also has very useful methods like# random.choice(list)# to pick a random value from a list# or # random.sample(list, k)# to pick a random sample of size k from a list

I am not going to explain modules in much more detail, but for now I’d say the three most important modules to play with are
random to do stuff with randomnesssys to pass in arguments to our program as we run it (explained below in the input & output section)os to have programe interact with the operating system (e.g. list the contents of directories or create files)

3rd party modules:
There is also maaaaaany third party modules that first have to be installed. You install them with a program called pip fro your command line.
This workshop will not cover pip, but please feel free to ask me about it anytime!

input and output

This section introduces a procedure that can be the foundation of a lot of programs you will be writing in python. As I said in the beginning, python programs tend to be linear like:

input ----> program ----> output

The input data can be of any kind, today we will use text. Let’s get some text to work with, maybe some music lyrics? Here is how you could download some from your command line into the project folder:

curl files.leoneckert.com/waww.txt > waww.txt

This put’s the lyrics of “What a Wonderful World” by Louis Armstrong into a file named waww.txt and saves it in the current directory.

Reading a file in python:

forlineinopen("waww.txt","r"):printline

inputoutput.py

This outputs this:

I see trees of green, red roses too
I see them bloom for me and you
And I think to myself what a wonderful world.
I see skies of blue and clouds of white
The bright blessed day, the dark sacred night
And I think to myself what a wonderful world.
The colors of the rainbow so pretty in the sky
Are also on the faces of people going by
I see friends shaking hands saying how do you do
They're really saying I love you.
I hear babies crying, I watch them grow
They'll learn much more than I'll never know
And I think to myself what a wonderful world
Yes I think to myself what a wonderful world.

Note the white lines? That’s because of a new line character in the file (you’ll always get this with text files) - the solution to correcting this is to use the strip() command:

forlineinopen("waww.txt","r"):line=line.strip()printline

inputoutput.py

output:

I see trees of green, red roses too
I see them bloom for me and you
And I think to myself what a wonderful world.
I see skies of blue and clouds of white
[...]

That looks better. This is a great base to do all sort of thing with this text: