Feb 4, 2018
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!
This is the plan
- When to use Python
- Command Line: 2 commands and how to get out of trouble
- A simple Python working environment
- Coding in Python
- … how to run Python code
- … syntax
- … variables
- … lists & dictionaries
- … for-loops & if-statements
- … functions
- … modules (and pip)
- … input and output
- Python 2 or Python 3??
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:
leoneckerts-MacBook-Pro:Desktop leoneckert$ pwd
/Users/leoneckert/Desktop
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:
no program running, the command line is ready for my commands.
Here on the other hand, something seems different, that doesn’t look normal to us, what’s going on!?
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 this
CTRL+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!"
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:
number = 10
if number > 5:
print "it's bigger than 5!"
print "the precise value is", number
When I try to run it, I get an error:
Running a python script.
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 variable
number = 10
# an float variable
other_number = 7.3
# an string variable
my_name = "leon"
# an boolean variable
its_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, but
this_one_does = true
Here are a few methods on different variable types - you might be familiar with simmilar operations from other languages like JavaScript:
# NUMBERS
a = 7
b = float(a)
print a
# prints: 7
print b
# prints: 7.0
c = a + b
print c
# prints: 14.0
d = c / a
print d
# prints: 2.0
e = int(d)
print e
# prints: 2
print e == 2
# prints: True
# remainder! (modulo, did someone say modelo?)
print 20 % 7
# prints: 6
a = 20 / 7
# prints: 2
a = 20.0 / 7.0
# prints: 2.857142857142857
a = round( 20.0 / 7.0 )
# prints: 3.0
print 7*4
# prints: 28
# power of....
print pow(2, 4)
# prints: 16
# STRINGS
s = "banana pizza"
a = s[2]
print a
# prints: n
# slicing:
b = s[1:6]
print b
# prints: anana
c = s[1:]
print c
# prints: anana pizza
d = s[:6]
# prints: banana
print s[-1]
# prints: a
print s[-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()
print k
# prints: ['banana', 'pizza']
print s.split()[1]
# prints: pizza
# we can split by other characters, too
kk = s.split("n")
# prints: ['ba', 'a', 'a pizza']
s = "giraffe haengematte "
print s + "!"
# prints: giraffe haengematte !
# strip away whitespace or new line characters:
print s.strip() + "!"
# prints: giraffe haengematte!
s = "Hello Dear Humans!"
print s.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
Here are some methods that you can use with lists:
a = list()
a.append(7)
a.appent(1)
print a
# prints: [7, 1]
print a[0]
# prints: 7
# to get the length:
print len(a)
# prints: 2
b = [8]
print a + b
# prints: [7, 1, 8]
c = a + b
c.append(3)
print c
# prints: [7, 1, 8, 3]
# slicing:
print c[1:]
# prints: [1, 8, 3]
print c[1:3]
# prints: [1, 8]
print c[-1]
# prints: 3
print c[:-1]
# prints: [7, 1, 8]
print c[-2]
# prints: 8
# ---> these are all super useful!
c.sort()
print c
# prints: [1, 3, 7, 8]
last_element = c.pop()
print last_element
# prints: 8
print c
# prints: [1, 3, 7]
second_element = c.pop(1)
print "the second element was", second_element, "the remaining list is", c
# prints: the second element was 3 the remaining list is [1, 7]
print 7 in c
# prints: True
print 12 in c
# prints: False
# Oh, and range is a cool thing
r = range(0, 8)
print r
# prints: [0, 1, 2, 3, 4, 5, 6, 7]
rr = range(0, 8, 2)
print rr
# prints: [0, 2, 4, 6]
print range(10, 5, -1)
# prints: [10, 9, 8, 7, 6]
# Oh, and the join method! (as you see there is plenty of such methods,
# if you search for solutions online,
# stackoverflow.com will always be be heloful)
p = ["bread", "elephants", "muffins"]
print " & ".join(p)
# prints: bread & elephants & muffins
# --> the join function looks odd at first,
# it starts with what you want to glue
# each element of the list together with
# and is then followed by the list in brackets.
This should be enough to get you playing, but there is more, discover as you go! Here is something to do with dictionairies:
my_dict = dict()
my_dict["name"] = "leon"
my_dict["favorite_digits"] = list()
my_dict["favorite_digits"].append(13242)
my_dict["favorite_digits"].append(4)
print my_dict
# prints: {'name': 'leon', 'favorite_digits': [13242, 4]}
print my_dict["favorite_digits"][1]
# prints: 4
just_keys = my_dict.keys()
print just_keys
# prints: ['name', 'favorite_digits']
print "name" in my_dict
# prints: True
Enough of lists and dictionaires for now!
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"]
for word in a:
print word
#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:
for element in a:
print element
# or
for sjkdfahsjkdsah in a:
print sjkdfahsjkdsah
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:
for i in range(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?
for i in range(0, 80):
if i%11 == 0:
divisable_by_eleven.append(i)
print divisable_by_eleven
# prints: [0, 11, 22, 33, 44, 55, 66, 77]
# or
print "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:
for i in range(0, 80):
string_i = str(i)
if i%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"]
for name in names:
# remember, "name" here is just a variable name that I am choosing
if name.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
functions
Almost forgot about function! You define them like this:
def replace_character(string, char, replace):
out = ""
for letter in string:
if letter == char:
out += replace
else:
out += letter
return out
print replace_character("hello leon", "e", "yolo")
# prints: hyolollo lyoloon
modules (and pip)
You will often see (and write) python script starting with lines like this:
import sys, os
import Image from PIL
import random
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.
import random
print random.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 randomness
sys
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:
for line in open("waww.txt", "r"):
print line
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:
for line in open("waww.txt", "r"):
line = line.strip()
print line
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:
all_words = list()
for line in open("waww.txt", "r"):
line = line.strip()
words = line.split()
all_words += words
print all_words
# prints: ['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.']
all_words.sort()
print all_words
# prints out the list of words, but sorted in alphabetical order
counter = 0
for line in open("waww.txt", "r"):
line = line.strip()
words = line.split()
line = list()
for word in words:
line.append(all_words[counter])
counter += 1
print " ".join(line)
# now what does that print?!
# it prints:
#And And And Are I I I I
#I I I I I I I I'll
#The The They'll They're Yes a a a a
#
#also and and babies blessed bloom blue bright by
#clouds colors crying, dark day, do do faces
#for friends going green, grow hands hear how in
#
#know learn love me more much myself myself myself myself
#never night of of of of of on people
#pretty rainbow really red roses sacred saying saying see see
#see see shaking skies sky so
#
#than the the the the them them think
#think think think to to to to too
#trees watch what what what what white wonderful wonderful
#wonderful wonderful world world. world. world. you you you.
Okay, what happened here?