Py4Bio Chapter 3: The for loop

This is the Chapter 3 of Py4Bio.

For loop lets you do something to each element in a list.

>>> for name in ["Andrew", "Arafat", "Arnob", "Alif"]:
...     print("Hello,", name)
... 
Hello, Andrew
Hello, Arafat
Hello, Arnob
Hello, Alif
>>> 

Rules of writing a for loop:

All lines in the same code block must have the same indentation.

>>> for name in ["Andrew", "Arafat", "Arnob", "Alif"]:
...     print "Hello,", name
...     print "Your name is", len(name), "letters long"

When indentation does not match…

>>> a = 1
>>>   a = 1
  File "<stdin>", line 1
    a = 1
    ^
SyntaxError: invalid syntax


>>> for name in ["Andrew", "Arafat", "Arnob", "Alif"]:
...     print("Hello,", name)
...        print("Your name is", len(name), "letters long")
  File "<stdin>", line 3
    print("Your name is", len(name), "letters long")
    ^
SyntaxError: invalid syntax


IndentationError: unindent does not match any outer indentation level

‘for’ also works on strings.

A string is similar to a list of letters.

>>> seq = "ATGCATGTCGC"
>>> for letter in seq:
...   print("Base:", letter)
... 
Base: A
Base: T
Base: G
Base: C
Base: A
Base: T
Base: G
Base: T
Base: C
Base: G
Base: C

Numbering bases

>>> seq = "ATGCATGTCGC"
>>> n = 0
>>> for letter in seq:
...     print "base", n, "is", letter
...     n = n + 1

The range function

>>> range(5)
[0, 1, 2, 3, 4]
>>> range(8)
[0, 1, 2, 3, 4, 5, 6, 7]
>>> range(2, 8)
[2, 3, 4, 5, 6, 7]
>>> range(0, 8, 1)
[0, 1, 2, 3, 4, 5, 6, 7]
>>> range(0, 8, 2)
[0, 2, 4, 6]
>>> range(0, 8, 3)
[0, 3, 6]
>>> range(0, 8, 4)
[0, 4]
>>> range(0, 8, -1)
[]
>>> range(8, 0, -1)
[8, 7, 6, 5, 4, 3, 2, 1]

Do something ‘N’ times

>>> for i in range(3):
...     print("If I tell you three times it must be true.")
... 
If I tell you three times it must be true.
If I tell you three times it must be true.
If I tell you three times it must be true.


>>> for i in range(4):
...     print(i, "squared is", i*i, "and cubed is", i*i*i)
... 
0 squared is 0 and cubed is 0
1 squared is 1 and cubed is 1
2 squared is 4 and cubed is 8
3 squared is 9 and cubed is 27

Exercise 1: Write a program that asks for a sequence (use the input function) then prints it 10 times. Include the loop count in the output

Enter a sequence: TACG
0 TACG
1 TACG
2 TACG
3 TACG
4 TACG
5 TACG
6 TACG
7 TACG
8 TACG
9 TACG

Exercise 2: Write a program that asks for a sequence then numbers each base, one base per line.

Enter a sequence: GTTCAG
base 0 is G
base 1 is T
base 2 is T
base 3 is C
base 4 is A
base 5 is G

Can you modify your program to start with base 1 instead of 0?

Exercise 3: Here is a Python list of restriction site patterns. Write a program that prints each pattern.

>>> restriction_sites = [
  "GAATTC",    # EcoRI
  "GGATCC",    # BamHI
  "AAGCTT",    # HindIII
]

Output:

GAATTC is a restriction site
GGATCC is a restriction site
AAGCTT is a restriction site