Author: A. Sean Pue
A lesson for AL340 Digital Humanities Seminar (Spring 2015)
--> Double Click here to start<--
This is an IPython Notebook. It contains numerous cells that can be of different types (Markdown, Code, Headings).
Select the cell above this one by double clicking it with your mouse.
You can see that it contains text in a format called Markdown. To execute the cell,
press shift+enter.
To complete this tutorial (which is meant for a classroom), execute the cells and follow the instructions.
In [699]:
I am really *Markdown* but I am set as Code. Fix me!
This will be a very quick introduction to Python.
We will focus on:
In [704]:
X = 1
Y=2
In [705]:
# Here is an example
X = 1
X=1 # This line is considered less readable than the above.
One of the features of Python that makes it so readable is that it cares very deeply about the space at the beginning of lines (indentation), so make sure you don't have a space at the beginning of the line. Otherwise, you will get an error.
In [706]:
X = 1 #This is okay
# An IndentationError here due to the space
X = 2
In [707]:
# Here, nothing is displayed because there is just a variable set.
X=1
In [708]:
# Here X is the last declaration in the cell, so X is displayed.
X=1
X
Out[708]:
In [709]:
# Here we have a declaration without a variable.
1
Out[709]:
You can also use the command print
followed by a variable or declaration.
In [710]:
X=1
print 1
print X
You can print
multiple variables or declarations together by using a comma.
In [711]:
print 1,1,X,X
There are also ways to output to files and so forth. You can also produce HTML within the notebook.
In [712]:
# 1. In this cell, write the code to output the number 3. Do not use print
#YOURCODEHERE
In [713]:
# 2. In this cell, do the same using print.
#YOURCODEHERE
In [714]:
# 3. Do the following
# print the number 4 on its own line.
#YOURCODEHERE
# next, set X to 5
#YOURCODEHERE
# print X followed by 3
In [715]:
1+1
Out[715]:
In [716]:
4/2
Out[716]:
In [717]:
5*2
Out[717]:
You can also use parentheses, e.g. ( )
, to specify the order of operations.
In [718]:
(4-1)*3
Out[718]:
You can use +=
to add on to a number, too.
In [719]:
X=1
X+=1
X
Out[719]:
In [720]:
# The answer you should get is 518517481480
#YOURCODEHERE
Now, subtract 666666 from 777777 and multiply by the result by two.
In [721]:
# The answer you should get is 222222.
# HINT: To do this on one line, you will need to use parentheses.
#YOURCODEHERE
A function is code that when called with a particular input gives a particular output. In math, this takes the form:
f(X) = 2 + X
f(2) = 4
Python uses a similar format.
Here let's use the built-in function abs()
which gives the absolute value of a number (e.g. |-1|=1)
In [722]:
abs(-1)
Out[722]:
In [723]:
abs(2-1)
Out[723]:
You can specify multiple inputs. Let's try another built-in function called min
, which gives the minimum value of the numbers based to it.
In [724]:
min(4,2,1)
Out[724]:
In [725]:
X=0
min(4,3,2,X)
Out[725]:
Note that you can also add to an existing number (or texts, as we will see) by using +=
.
In [726]:
X = 1
X += 1
X
Out[726]:
You can find out the type
of a variable or declaration using the function type
. Let's try it.
In [727]:
type(1)
Out[727]:
There are a number of basic numeric types, including int
and float.
int
is a whole number, positive or negative. To set it, you can do the following: x=1
or int(1)
.
float
(for floating-point number) is a more precise number and includes a decimal. To set one, you can include a decimal point in your number, e.g. x=1.0
, or use the function float(1)
.
In [728]:
type(1)
Out[728]:
In [729]:
type(1.0)
Out[729]:
In [730]:
type(2*3)
Out[730]:
In [731]:
type(2.0*3)
Out[731]:
The distinction between int
and float
can be a bit of gotcha, as Python will provide an int
answer if one of the variables is not set as a float
(by adding a decimal
to the declaration).
In [732]:
# Fix below to return .5 (not 0).
X = 1/2
print X
In [733]:
x = True
type(x)
Out[733]:
You can test whether or not something equals something else using the
operator ==
, and to see if they are not equal using !=
.
In [734]:
x = 1
x == 1
Out[734]:
In [735]:
x = 2
x != 1
Out[735]:
In [736]:
type(True)
Out[736]:
You can check to make sure your expectations are correct using the command assert, which will through an error if your assertion is not correct.
In [737]:
x = 1
assert x == 1 # no problem here
assert x == 1.0 # no problem here, either
assert type(x)==float # it's an int not a float!
In [693]:
s = 'Hello'
t = "there"
type(s)
Out[693]:
Strings can be combined using +
:
In [694]:
s + ' ' + t+ ' what\'s your name?' # you can use \' to put a ' inside ''s
Out[694]:
To get the length of a string, use the function len
.
In [695]:
len('Hello')
Out[695]:
Strings also have numerous functions available to them. To use them, type a string variable followed by a period and then the function.
In [696]:
s = 'Hello'
print s.capitalize() # capitalizes the first letter
print s.upper() # capitalizes all letters
print s.lower() # lowercases all letters
In [697]:
a = 'X'.lower() # makes the string 'X' lowercase
b = 'x'.upper() # makes the strin g'x' uppercase
print (a + b).upper() # joins a and b and turns them uppercase
print (a + b).lower().upper() # does the above but then turns it uppercase
You can turn a number into a string, and a string into a number as follows.
In [698]:
s='1'
i=int(s)
f=float(s)
print s,i,f
Python has a number of other data structures besides the ones we have learned (int
,float
,str
,bool
)
Python is not "strongly typed" which means the type
of your variable
can changes, as in the following:
In [643]:
x = 1
print x,type(x)
x = 1.0
print x,type(x)
x = '1'
print x,type(x)
x = False
print x,type(x)
In [644]:
my_list = ['A',1,2,3,'B']
print my_list
print 'the first item is',my_list[0]
print 'length of my_list is',len(my_list)
You can also select from the end of a list using a negative number, e.g. l[-1]
, and you can select a range of items using a colon, e.g. l[0:2]
In [645]:
l = ['0',1,2,3,'5']
print 'the first two items are',l[0:2] # l[start_at,end_before]
print 'The last item is',l[-1] # use negative numbers to read from end
print 'The first to next-to-last items are',l[0:-1]
In [646]:
l = ['A','B','C','D','E','F']
# YOURCODEHERE
To append to a list use the .append
command or +=
In [647]:
l=['A','B','C','D','E','F']
l+='G'
print l
l.append('H')
print l
In [648]:
l = ['A','A','A','B']
print l,type(l)
s = set(l)
print s,set(s)
In [649]:
langs = {}
print langs, type(langs)
langs['hi'] = 'Hindi'
print langs, len(langs) # you can get the length, too
# Here is a way to set it all at once
langs = {'hi': 'Hindi', 'en': 'English', 'myfavnumber': 7}
print len(langs),langs['myfavnumber']
To get the keys of a dictionary, use the funciton .keys
, e.g. langs.keys()
In [650]:
print langs.keys()
In [651]:
colors = ['red','white','blue','green']
for x in colors:
print x
In [652]:
colors = ['red','white','blue','green']
# YOURCODEHERE
Whenever you have a task that you need to repeat, it is usually worthwhile to make a function. As mentioned above, a function is code that takes an input and returns an output.
In Python, you define a Python using the following pattern:
def my_function(): # put your input inside the ()s
# your code here
return # your output here output
Here is an example:
def add_one(x)
x = x + 1
return x
You can have multiple inputs, and the output can be whatever form you want, too. Spacing is important, as you need a standard indentation (usually 4 or 2 spaces) after the definition. That makes it easier to read.
Below is an example.
In [653]:
def add_two(x):
return x+2
def add_three(x):
o = x+2
return o
def add_five(x):
assert x
return add_two(add_three(x))
y = 0
y = add_two(y)
print y
y = add_three(y)
print y
y = add_five(y)
print y
In [654]:
# So quote_me('Hello') should output: Hello!
def quote_me(s):
# YOURCODEHERE
return #YOURCODEHERETOO
In [655]:
import sys
print sys.version # this shows your version of Python, etc.
Above, you see you can access a variable or a function by prefacing it my the name of the module. If you want to import the variable or version into the 'name space' your code so that you can access it directly, use the command from
...import
...
In [656]:
from sys import version
print version # we no longer need the sys
You can also import a module and give its own name using the command import
...as
...
In [657]:
import sys as my_own_system
print my_own_system.version
In [ ]: