Python Cheat-Sheet PDF
Python Cheat-Sheet PDF
>>> print 7
7
>>>
To run a program, be sure you have a normal terminal prompt (will
vary by system), will usually end with a '$' or a single '>' character:
>>> python myprog.py arg1 arg2
(program output)
When you write your program (in a text editor), be sure to save it
before trying out the new version! Python reads the saved file to
run your program.
Each argument is a string object and they are accessed using sys.argv[0],
sys.argv[1], etc., where the program file name is the zeroth argument.
Write your program with a text editor and be sure to save it in the present
working directory before running it.
10 or 2.71828
hello
[1, 17, 44] or [pickle, apple, scallop]
(4, 5) or (homework, exam)
{food : something you eat, lobster : an edible arthropod}
more later
>>> pi = 3.14159
>>> print pi
3.14159
When we write out the object directly, it is a literal,
as opposed to when we refer to it by its variable
name.
first
argument
second
argument
zeroth
argument
first
argument
Assigning variables
In order to retain program access to a value,
you have to assign it to a variable name.
this says give me access to all
the stuff in the sys module
import sys
sys.argv[0]
import sys
print sys.argv[0]
import sys
s = sys.argv[0]
Numbers
Python defines various types of numbers:
Integer (1234)
Floating point number (12.34)
Octal and hexadecimal number (0177, 0x9gff)
Complex number (3.0+4.1j)
Conversions
>>> 6/2
3
>>> 3/4
0
>>> 3.0/4.0
0.75
>>> 3/4.0
0.75
>>> 3*4
12
>>> 3*4.0
12.0
Formatting numbers
The % operator formats a number.
The syntax is <format> % <number>
>>> %f % 3
3.000000
>>> %.2f % 3
3.00
>>> %5.2f % 3
3.00
Formatting codes
%d = integer (d as in digit)
%f = float value - decimal (floating point) number
%e = scientific notation
%g = easily readable notation (i.e., use decimal
notation unless there are too many zeroes, then
switch to scientific notation)
Number of
digits after
decimal
d, f, e, g
Examples
>>> x = 7718
>>> %d % x
7718
>>> %-6d % x
7718
>>> %06d % x
007718
>>> x = 1.23456789
>>> %d % x
1
>>> %f % x
1.234568
>>> %e % x
1.234568e+00
>>> %g % x
1.23457
>>> %g % (x * 10000000)
1.23457e+07
string basics
Basic string operations:
S = "AATTGG"
S1 + S2
S*3
S[i]
S[x:y]
len(S)
int(S)
float(S)
len(S[x:y])
Methods:
S.upper()
# convert S to all upper case, return the new string
S.lower()
# convert S to all lower case, return the new string
S.count(substring)
# return number of times substring appears in S
S.replace(old,new)
# replace all appearances of old with new, return the new string
S.find(substring)
# return index of first appearance of substring in S
S.find(substring, index)
# same as previous but starts search at index in S
S.startswith(substring)
# return True or False
S.endswith(substring)
# return True of False
Printing:
print var1,var2,var3
print "text",var1,"text"
list basics
Basic list operations:
L = ['dna','rna','protein']
# list assignment
L2 = [1,2,'dogma',L]
# list can hold different object types
L2[2] = 'central'
# change an element (mutable)
L2[0:2] = 'ACGT'
# replace a slice
del L[0:1] = 'nucs'
# delete a slice
L2 + L
# concatenate
L2*3
# repeat list
L[x:y]
# get a slice of a list
len(L)
# length of list
''.join(L)
# convert a list to a string (a string function that acts on lists)
S.split(x)
# convert string to list- x delimited
list(S)
# convert string to list - explode
list(T)
# converts a tuple to list
Methods:
L.append(x)
L.extend(x)
L.count(x)
L.index(x)
L.insert(i,x)
L.remove(x)
L.pop(i)
L.reverse()
L.sort()
dict basics
D = {'dna':'T','rna':'U'}
D = {}
D.keys()
D.values()
D['dna']
D['dna'] = 'T'
del D['dna']
D.pop('dna')
'dna' in D
'r' = read
'w' = write
'a' = append
if elif - else
if <test1>:
<block1>
elif <test2>:
<block2>
elif <test3>:
<block3>
else:
<block4>
Only one of the blocks is ever executed.
A block is all code with the same indentation.
Comparison operators
Boolean: and, or, not
Numeric: < , > , ==, !=, >=, <=
String: in, not in
<
>
==
!=
<=
>=
is
is
is
is
is
is
less than
greater than
equal to
NOT equal to
less than or equal to
greater than or equal to
for loops
for <target> in <object>
continue
skip the rest of the loop and start at the top again
break
As usual, all the commands with the same indentation are run as a code block.
for integer in range(12)
while loops
Similar to a for loop
while (conditional test):
<statement1>
<statement2>
. . .
<last statement>
While something is True keep running the loop, exit as
soon as the test is False.
Any expression that evaluates True/False can be used
for the conditional test.
Time efficiency
Rough order of speed for common operations:
reading/writing files - very slow
going through a list serially for matching elements - slow
accessing a list (or string) element by index - fast
accessing a dictionary value by key - fast
File reading - sometimes you only need to look through a file until you find
something. In this case, read lines until you have what you need then close
the file.
Dictionaries can be used in various clever ways to save time.
Do simple profiling to see what part of your code is slowest (for example,
invoke time.time() twice, once before and once after a code block).
Future - beginning Python is kept simple by hiding a lot of complex things
from you - dig in deeper to understand what takes more time (and memory).
Memory efficiency
File reading - often you don't need to save the entire contents of a file into
memory. Consider whether you can discard some of the information.
If your program generates many copies of a long string, consider making a
dictionary entry with the string as the value (you only need to store it once).
If you are working with a long string and you want to access many segments
of it, do NOT save each segment as a string - use string indexing to get
each segment as you need it.
Future - instead of using Python lists, consider using classes in the Python
array module to store long sequences, etc.