Lecture 2 - Input, conditionals and branching

Today:

  • Conditional control flow:
    • If statements
    • Else
    • Elif
    • Pass

Warm up

Raise the first element of the list below to the power of the fifth element

Is this number greater than 8 to the power of 10?

Append the answer to the end of the list

In [95]:
warm_up_list = [4,2,9,4,5,1]
In [96]:
# your code here
answer = warm_up_list[0] ** warm_up_list[4]
print(answer)
1024

You can extract multiple parts of a list using a colon in your bracket [:]

For example, to extract the 1st through 3rd element of a list:

my_list[0:2]

In [61]:
# extract elements 2 through 4 of warm_up_list
print(warm_up_list[1:3])
[254, 324]

In python, strings are just a list of characters so this works on strings as well!

In [66]:
my_big_string = 'heresabigstringwithnospaces'
print(my_big_string[5:15])
abigstring
In [108]:
states = [ 'AK', 'AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE', 'FL', 'GA','HI', 'IA', 'ID', 'IL', 'IN', 'KS', 'KY', 'LA', 'MA', 'MD', 'ME','MI', 'MN', 'MO', 'MS', 'MT', 'NC', 'ND', 'NE', 'NH', 'NJ', 'NM','NV', 'NY', 'OH', 'OK', 'OR', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX','UT', 'VA', 'VT', 'WA', 'WI', 'WV', 'WY']
# your code here
In [109]:
print(states[1:9])
['AL', 'AR', 'AZ', 'CA', 'CO', 'CT', 'DC', 'DE']

len() gives you the length of a list or string

In [50]:
my_list = [1,33,2,23,2,32,42]
print(len(my_list))
7

How long are the variables below?

In [110]:
my_list = ['s','c','i','e','n','c','e']
my_string = 'helpiforgottoputwhitespaceinthissentence'
# your code here 
In [111]:
print(len(my_list))
print(len(my_string))
7
40

How can we talk to our python script?

input() is a function that takes a text prompt and stores it as a string

The only argument for input() is a string that you want the prompt to be

to save what the user inputs, just save input to a variable

In [2]:
your_name = input("what is your name? ")

output_statement = 'python remembered your name is: ' + your_name

print(output_statement)
what is your name? vikas
python remembered your name is: vikas

Try writing a program that takes a numerical input and prints the square of it

In [112]:
input_number = float(input("whats your number? "))
answer = input_number ** 2
print(answer)
whats your number? 23
529.0

What is the most basic way to teach someone to do something?

Only give them two choices: Do this or do that

What are some examples of this?

  • If they don't have bananas at the grocery store, buy apples

Python thinks similarly: if the condition is true, do this thing

If statement structure

Python is sensitive to "whitespace"

Whitespace is a tab, or a space

if <yourcondition>: 
    dothis()

where yourcondition is anything that returns a boolean (True/False)

In [3]:
if 2 > 1: 
    print('Math works')
# there is an invisible tab character on the second line
Math works

Debugging practice

what happened here?

In [6]:
if 2 > 1
    print('Math works')
  Input In [6]
    if 2 > 1
            ^
SyntaxError: invalid syntax
In [7]:
if 2 > 1: 
print('Math works')
  Input In [7]
    print('Math works')
    ^
IndentationError: expected an indented block
In [11]:
if 2 > 1: 
    print('Math works')
   print('But python doesnt sometimes')
  File <tokenize>:3
    print('But python doesnt sometimes')
    ^
IndentationError: unindent does not match any outer indentation level

Does python think dogs are better than cats? whats going on??

In [2]:
if "dogs" > "cats":
    print("Dogs really are the best") 
Dogs really are the best

strings are sorted lexicographically (aka: alphabetically) in python

d comes after c, which means d > c according to python

Write an if statement that checks if a is greater than b

If it is true, print "a is greater than b"

In [86]:
a = 100 ** 2
b = 7 ** 4

# your code here
if a > b: 
    print('a is greater than b')
a is greater than b

Else

Else is like saying 'otherwise' after if: "if this is true, do this. Otherwise, do that"

The general structure of an if/else statement is:

if <your condition>:
  dothis()
else:
  dothat()

Else does not take a conditional! it assumes the opposite of the if conditional

Lets try an else statement

In [22]:
if 'unix' < 'gui': 
    print('This sounds wrong')
else: 
    print('Roman told you so')
Roman told you so

in this case, "u" is lexicographically (alphabetically) after "g"

to python, this means "unix" is less than "gui" is False

Debugging practice

What went wrong here?

In [25]:
if 1 < 5: 
    print('5 is greater than 1')
else 1 > 5: 
    print('1 is greater than 5?? ')
  Input In [25]
    else 1 > 5:
         ^
SyntaxError: invalid syntax
In [32]:
if 1 < 5: 
    print('5 is greater than 1')
 else: 
    print('1 is greater than 5?? ')
  File <tokenize>:3
    else:
    ^
IndentationError: unindent does not match any outer indentation level

Write an if statement that checks if a is greater than b

if it is true, print a is greater than b

if it is false, print b is greater than a

In [97]:
a = 500 * 20
b = 7 ** 9
In [99]:
# your code here
if a > b: 
    print('a is greater than b')
else:
    print('b is greater than a')
b is greater than a

Else and elif

Elif is the partner of if and else:

In [87]:
# If, else and elif

x = float(input("What's your favorite number? : "))

if x == 7:
  print("We have the same favorite number!")
elif x < 2:
  print("Your favorite number is way less than mine")
elif x < 7:
  print("Your favorite number is less than mine")
else:
  print("Your favorite number is greater than mine")
What's your favorite number? : 10
Your favorite number is greater than mine

Write a program that take a number as an input and checks if it is between 28 and 30.

If it is less than 28, print "your number less than 28".

If it is greater than 30, print "your number is greater than 30".

If the number is 29, print "thats a nice number"

In [94]:
# your code here
x = float(input("What's your favorite number? : "))
if x < 28: 
    print('your number is less than 28')
elif x > 30: 
    print('your number is greater than 30')
elif x == 29:
    print('thats a nice number')
What's your favorite number? : 100
your number is greater than 30

for loops are similar between bash and python

Recall what a for loop is:

for this thing in my list of stuff, do this

for i in 1 2 3 4
do
   echo loop iteration $i 
done

for loop structure in python

for <variable> in <list>: 
    <run_command>

note that there is no do/done/semicolon!

In [101]:
teachers = ['Roman','Vikas','Sarah','Daniel']
for person in teachers: 
    print(person + " is a great teacher!")
Roman is a great teacher!
Vikas is a great teacher!
Sarah is a great teacher!
Daniel is a great teacher!

Write a for loop to print each letter in the first five letters of the alphabet

In [26]:
# your code here
alphabet = ['a','b','c','d','e']
for letter in alphabet: 
    print(letter)
a
b
c
d
e

Challenge:

What would the last line of the following code return?

my_list = [1,2,3,4,5]
i = 1
for number in my_list: 
    i = i + number
    print(i)
In [31]:
my_list = [1,2,3,4,5]
i = 1
for number in my_list: 
    i = i + number
    print(i)
2
4
7
11
16

Making lists quickly

Python has a function range() that will give you the numbers between the two arguments, excluding the last number

range(1,5) will return a sequence containing all numbers between 1 and 5

In [57]:
for num in range(1,5):
    print(num)
1
2
3
4

Write a function that sums all of the numbers between 1 and 100

In [31]:
# your code here
x = 0
for num in range(1,101):
    x = x + num
print(x)
5050

Can we write a function that prints the sums of all cominations of the following lists?

In [115]:
x = [1,2,3]
y = [4,5,6]
In [116]:
for outer in x: 
    for inner in y:
        print(outer + inner)
5
6
7
6
7
8
7
8
9

Modify the for loop we just wrote to only print the sum of numbers if it is greater than 7

In [103]:
# your code here:
In [104]:
for outer in x: 
    for inner in y:
        number_sum = outer + inner
        if number_sum > 7: 
            print(number_sum)
8
8
9

Biology review about codons:

codons are three consecutive nucleotides that code for an amino acid

codon_table.png

There are four special codons: one start, and three stop. Can you point out the start and stop codons?

Where do codons go in an RNA molecule?

transcript_structure.png

Can we write a program to find the start codon in an RNA sequence?

What are the parts of the program we would need?

- Variable to store the RNA sequence

- A way to extract codons

- Variable to remember the position of the codon

- A way to check if the codon is a start codon

Try to write a program that will print the start codon position in this example sequence

hints: you'll need a for loop, len(), and 'range()

In [105]:
rna_sequence = 'AUGUUUUUGAUACUUUUAAUUUCCUUACCAACGGCUUUUGCUGUUAUAGGAGAUUUAAAGUGUACUACAGUUUCCAUUAAUGAUGUUGACACUGGUGUUCCUUCUAUUAGCACUGAUACUGUCGAUGUUACUAAUGGUUUAGGUACUUAUUAUGUUUUAGAUCGUGUGUAUUUAAAUACUACGUUGUUGCUUAAUGGUUAUUACCCUACUUCAGGUUCUACAUAUCGUAAUAUGGCACUGAAGGGAACUUUACUAUUGAGCACACUGUGGUUUAAACCACCUUUUCUUUCUGAUUUUACUAAUGG'
#your code here
In [106]:
rna_length = len(rna_sequence)
last_codon_start = rna_length - 3
for codon_start in range(0,last_codon_start):
    codon_end = codon_start + 3
    current_codon = rna_sequence[codon_start:codon_end]
    if current_codon == 'AUG':
        print(codon_start)
0
79
82
124
133
151
193
231
301

Try to write a program that will find all stop codons in the same sequence

In [77]:
rna_sequence = 'AUGUUUUUGAUACUUUUAAUUUCCUUACCAACGGCUUUUGCUGUUAUAGGAGAUUUAAAGUGUACUACAGUUUCCAUUAAUGAUGUUGACACUGGUGUUCCUUCUAUUAGCACUGAUACUGUCGAUGUUACUAAUGGUUUAGGUACUUAUUAUGUUUUAGAUCGUGUGUAUUUAAAUACUACGUUGUUGCUUAAUGGUUAUUACCCUACUUCAGGUUCUACAUAUCGUAAUAUGGCACUGAAGGGAACUUUACUAUUGAGCACACUGUGGUUUAAACCACCUUUUCUUUCUGAUUUUACUAAUGG'
stop_codons = ['UGA','UAA','UAG']
#your code here
rna_length = len(rna_sequence)
last_codon_start = rna_length - 3
for codon_start in range(0,last_codon_start):
    codon_end = codon_start + 3
    current_codon = rna_sequence[codon_start:codon_end]
    if current_codon ==  stop_codons[0]:
        print(codon_start)
    elif current_codon ==  stop_codons[1]:
        print(codon_start)
    elif current_codon ==  stop_codons[2]:
        print(codon_start)
7
16
46
55
77
80
86
107
113
131
139
157
172
191
227
238
256
272
290
299

Challenge: Write a program that stores all start codon positions in the list found_start_codons

Also store all stop codons in the list found_stop_codons

In [107]:
# your code here
found_start_codons = []
found_stop_codons = []
rna_length = len(rna_sequence)
last_codon_start = rna_length - 3
for codon_start in range(0,last_codon_start):
    codon_end = codon_start + 3
    current_codon = rna_sequence[codon_start:codon_end]
    if current_codon ==  stop_codons[0]:
        found_stop_codons.append(codon_start)
    elif current_codon ==  stop_codons[1]:
        found_stop_codons.append(codon_start)
    elif current_codon ==  stop_codons[2]:
        found_stop_codons.append(codon_start)
    elif current_codon == 'AUG':
        found_start_codons.append(codon_start)

print(found_start_codons)
print(found_stop_codons)
[0, 79, 82, 124, 133, 151, 193, 231, 301]
[7, 16, 46, 55, 77, 80, 86, 107, 113, 131, 139, 157, 172, 191, 227, 238, 256, 272, 290, 299]