An intro to Python for biology

Variables and printing


In [ ]:
# this is a comment, use these to tell people what your code does

In [ ]:
mystring = "Homo sapiens" # a string, letters, words, sentences, anything in quotes
myinteger = 4 # an integer
myfloat = 4.0 # a float (a number with a decimal point)

print "This is a string:", mystring, "this is a float:", myfloat, "and this is an integer: ", myinteger

Basic Math

You can do calculations:


In [ ]:
myfloat = 2.0
yourfloat = 3.0
print myfloat/yourfloat

But be careful, when you calculate with only integers, you can only get an integer back, so Python rounds your answer down!


In [ ]:
myint = 2
yourint = 3
print myint/yourint

In [ ]:
myint = 2
yourint = 3

# Which of these work and why?

In [ ]:
print float(myint)/yourint # 1

In [ ]:
print myint/float(yourint) # 2

In [ ]:
print (myint+0.0)/yourint # 3

In [ ]:
print myint/yourint*1.0 # 4

In [ ]:
print myint*1.0/yourint # 5

In [ ]:
print float(myint/yourint) # 6

Lists


In [ ]:
mylist = [6,3,6,7,2,6,2,9,7,0]
print mylist

You can get each item of the list using the brackets. Try to replace 0 with other numbers and see what you get:


In [ ]:
print mylist[0]

Here the number inside the brackets is called an index, it represents the location of an item in the list.

You can also get more than one item at a time by providing a range of indices:


In [ ]:
print mylist[0:3]

Strings can be words, sentences, and anything else you can write as a sequence of characters. They act a lot like lists.

You can make a string using quotes


In [ ]:
mystring = "ACGT"
print mystring

What happens if you remove the quotes? What about using single quotes like 'this'?


In [ ]:
mystring = ACGT
print mystring

You can get the length of the string using the len() function:


In [ ]:
mystring = "ACGT"
print len(mystring)

You can get each letter of the string using the brackets. Try to replace 0 with other numbers and see what you get:


In [ ]:
print mystring[0]

Here is an example with DNA:


In [ ]:
DNA = "CAACGGGCAATATGTCTCTGTGTG"
print "Your DNA is", len(DNA), "bases long"

print DNA[7]