1 of 21

Python 2: Logic, Loops, iterators

Guest Lecture by Sawyer Masonjones

2 of 21

2.1: Logic

  • Used for
    • Decision making
    • Controlling program flow
  • Centered around boolean if:then statements
    • IF X is true, THEN do this.

if foo==bar:

doThis(foo)

else:

doThat(bar)

3 of 21

2.1 Syntax of If / Loop statements

Python determines structure of if/else statements looking for the “:” and the code that follows needs to be indented

If counter > 10:� print(counter, “ is a big number”)�else:� print(counter, “ is smaller or equal to 10”)

This can be a tab or 4 spaces. But don’t mix tabs and spaces!

4 of 21

2.1 Logical Expressions

  • ==
    • foo == bar will return true if the values are the same
  • !=
    • foo != bar will return true if values are different
  • > or <
    • foo < bar will return true if foo is less than bar
  • <= or >=
    • foo <= bar will return true if foo is less than or equal to bar

5 of 21

2.1 Logic Operators

  • not
    • not foo will return true if foo is false
  • and
    • foo and bar will return true iff both foo and bar are true
  • or
    • foo or bar will return true if either foo and bar (or both) are true

���������

foo

Not foo

T

F

F

T

foo

bar

foo or bar

T

T

T

T

F

T

F

T

T

F

F

F

foo

bar

foo and bar

T

T

T

T

F

F

F

T

F

F

F

F

6 of 21

7 of 21

8 of 21

2.1 Logic in Python

If statements start the conditional statement, executing the indented code. Elif statements extend this with new conditions, doing the same. Else is used to execute everything else ie the false case. You don’t need to finish with an else statement.

if foo == bar:

doThis()

elif foo > bar:

doThat()

else:

doThisAndThat()

9 of 21

2.2 Loops

  • Used to repeat actions
  • Two main types: for loops, and while loops
  • For loops iterate over a range or some structure
    • For every number in range 1 to 10, do this
    • For every element in structure, do this
  • While loops repeat until some condition is met
    • While x remains true, do this

10 of 21

2.2 For Loops

  • The range function is used iterate over a range of integers.

for i in range(1,11): #count forwards

print i

for i in range(10,-1,-1): #count backwards

print i

for i in range(1,11,2): #count by 2s

print i

11 of 21

2.2 For Loops and lists

  • Can iterate over a list by index

for i in range(len(list)):

print list[i]

  • Or directly

for item in list:

print item

12 of 21

2.2 While Loops

Iterate until a condition is false

Count = 100

while count > 0:

print count

count -= 1

13 of 21

2.2 Break and Continue

for item in list:

for i in item:

if i == ‘A’:

break #breaks inner most loop

for item in list:

for i in item:

if i == ‘A’:

continue #continues to next iteration

14 of 21

2.4 Iterators

  • Already have covered iterable objects, like lists or strings
  • And used for loops to iterate over them
  • Turning a iterable object to a iterator is another way to interact with them

Iterator = iter(list) #turn iterable object to iterator

next(iterator) #get next object

  • Commonly used in file i/o nextLine(), readLine()
  • BioPython has iterators for various sequence data e.g. fasta

15 of 21

2.4 Iterator example

list = [0,1,2,3]

iterator = iter(list)

next(iterator) #0

next(iterator) #1

next(iterator) #2

next(iterator) #3

next(iterator) #Throws error StopIteration

16 of 21

2.4 Iterators and loops

for item in iterator:

print( item)

while True:

try:

next(iter)

except StopIteration:

break

17 of 21

Putting it together

Problem: You have a DNA sequence and you need to calculate GC content.

Write a script that iterates over a sequence to calculate GC content across the entire sequence.

Write a script that iterates over a sliding window across the sequence.

18 of 21

2.2 Sequences

  • Sequences are ordered linear collections of variables, objects, etc.
  • Useful in storing and accessing data for processing.
  • Several types
    • Lists, formed by brackets: list = [1,4,2,5,6,1,4,8]
      • Each element is accessible by index and mutable
    • Tuples, formed by parentheses: tuple = (4,5,1,6,7,1,1)
      • Each element can be accessed by index, but cannot be changed
    • Strings are special sequences of characters, can be accessed like lists, but are immutable

19 of 21

2.2 List methods

list = [] #Creates empty list

list = [1,3,2,5,21,5] #Creates list with values

list[i] #access ith element of list

list[-j] #access jth element starting from end of list

list[i:j] #slices list from position i to j. Leaving i or j blank slices from begining (i) or end (j)

list.insert(i,value) #inserts value at ith position

list.append(value) #Adds value to end of list

20 of 21

2.2 Lists Methods Continued

list.pop() #removes item from end of list and returns it

list.pop(i) #removes item from the ith position and returns it

list.extend(list2) #adds items from list2 onto list 1

list.remove(value) #removes first item with value

list.count(value) #returns count of items with that value in list

list.index(value) #returns index of first item with value.

list.index(value,start,end) #returns index of first item in range [i:j]

list.copy() #return copy of list

list.clear() #empties list

21 of 21

2.2 Stacks and Queues

  • Stacks are “first in, last out” data structures
  • Queues are “first in, first out”
  • Both are used in some algorithms
  • In python, lists can be used as either with the append and pop methods

stack = [1,2,3,4,5]

stack.append(6) #stack is now [1,2,3,4,5,6]

stack.pop() #stack is now [1,2,3,4,5]

Queue uses pop(0) to take from front of list.