Programming Bootcamp 2016

Lesson 2 Exercises -- ANSWERS



1. Guess the output: conditionals practice (1pt)

For the following blocks of code, first try to guess what the output will be, and then run the code yourself. Points will be given for filling in the guesses; guessing wrong won't be penalized.

NOTE: The first cell below holds the variables that will be used in the problems. Since variables are shared across cells in Jupyter notebooks, you just need to run this cell once and then those variables can be used in any other code cell.

(However, remember that closing the notebook or restarting the kernel clears all the variables, so you will need to re-run the cell to re-populate those variables after doing that.)


In [1]:
# RUN THIS BLOCK FIRST TO SET UP VARIABLES!
a = True
b = False
x = 2
y = -2
cat = "Mittens"

(^^ you might find it helpful to copy these variables somewhere you can easily see them when doing the problems. e.g. a piece of paper or a text file.)


In [2]:
print a


True

In [3]:
print (not a)


False

In [4]:
print (a == b)


False

In [5]:
print (a != b)


True

In [6]:
print (x == y)


False

In [7]:
print (x > y)


True

In [8]:
print (x = 2)


  File "<ipython-input-8-6fbc2415a06a>", line 1
    print (x = 2)
             ^
SyntaxError: invalid syntax

A single = means assignment, and you can't do assignment within a print statement (assignments are always done on their own line). What we want here is: print (x == 2)


In [9]:
print (a and b)


False

In [10]:
print (a and not b)


True

In [11]:
print (a or b)


True

In [12]:
print (not b or a)


True

In [13]:
print not (b or a)


False

In [14]:
print (not b and a)


True

In [15]:
print not (b and a)


True

In [16]:
print (x == abs(y))


True

In [17]:
print len(cat)


7

In [18]:
print cat + x


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-36807e9f20b2> in <module>()
----> 1 print cat + x

TypeError: cannot concatenate 'str' and 'int' objects

In [19]:
print cat + str(x)


Mittens2

In [20]:
print float(x)


2.0

In [21]:
print ("i" in cat)


True

In [22]:
print ("g" in cat)


False

In [23]:
print ("Mit" in cat)


True

What is "in"? This is just another Python operator that you can use in your conditionals. As you may have guessed, (x in y) evaluates to True if x is found in y. This can be used to check if a string is contained in another string (e.g. "Mit" in "Mittens").


2. Guess the output: if statement practice (1pt)

Same directions as above.


In [24]:
# RUN THIS BLOCK FIRST TO SET UP VARIABLES!
x = 2
y = -2
cat = "Mittens"

In [25]:
if (x % 2) == 0:
    print "x is even"
else:
    print "x is odd"


x is even

In [26]:
if (y - 4*x) < 0:
    print "Invalid!"
else:
    print "Banana"


Invalid!

In [27]:
if "Mit" in cat:
    print "Hey Mits!"
else:
    print "Where's Mits?"


Hey Mits!

In [28]:
x = "C"
if x == "A" or "B":
    print "yes"
else:
    print "no"


yes

See below for explanation!


In [29]:
x = "C"
if (x == "A") or (x == "B"):
    print "yes"
else:
    print "no"


no

Surprised by the last two? It's important to note that when you want compare a variable against multiple things, you can only compare it to one thing at a time. Although it makes sense in English to say "is x equal to A or B?", in Python you must write: ((x == "A") or (x == "B")) to accomplish this. The same goes for e.g. ((x > 5) and (x < 10)) and anything along those lines.

So why does the first version give the answer "yes"? Basically, anything that isn't False or the literal number 0 is considered to be True in Python. When you say 'x == "A" or "B"', Python reads it as '(x == "A") or (B)', which evaluates to '(False) or (True)', which is True!


3. On your own (2pts)

Write code to accomplish the following tasks using the concepts we went over in the lecture.

Use the following variables in your code. You must actually use the variables; pretend you don't know their values.


In [31]:
# RUN THIS BLOCK FIRST!
num1 = 3.14159
num2 = 6
num3 = 100
num4 = 6 * -5 - 4 * 2 + -7 * -8 + 3
motif = "GTAAGTCGGTAACGTAAGTCGGTAAC"

(A) Check if num3 is greater than num4. Print "yes" if it is, and "no" if it isn't.


In [32]:
if num3 > num4:
    print "Yes"
else:
    print "No"


Yes

(B) Print a random integer between num2 and num3.


In [33]:
import random

random.randint(num2, num3)


Out[33]:
82

(C) Check if the length of the string stored in motif is less than or equal to 25. Print "yes" if it is, and "no" if it isn't.


In [34]:
if len(motif) <= 25:
    print "Yes"
else:
    print "No"


No

(D) Round num1 to the nearest hundredth.


In [35]:
round(num1, 2)


Out[35]:
3.14

(E) Check if num4 is positive or negative.


In [38]:
if num4 >= 0:
    print "It's positive"
else:
    print "It's negative"


It's positive

4. Quadratic formula: checking for negative roots (1pt)

Recall that when calculating the quadratic formula, you will get an error if $b^2 - 4ac$ is negative, since you can't take the square root of a negative number.

Edit the code below so that it checks for this potential error before it occurs:

  • If the error is going to occur, print a message saying "non-real answer" and do not calculate the values of x.
  • If the error is not going to occur, calculate and print the values of x.

In [41]:
a = float(raw_input("Enter value for a: "))
b = float(raw_input("Enter value for b: "))
c = float(raw_input("Enter value for c: "))

underRoot = (b**2 - 4*a*c)

if underRoot >= 0:
    x1 = ( (-b) + underRoot ** 0.5 ) / float(2*a)
    x2 = ( (-b) - underRoot ** 0.5 ) / float(2*a)
    print "x =", x1, "or", x2
else:
    print "non-real answer"


Enter value for a: 2
Enter value for b: 2
Enter value for c: 2
non-real answer

[ Check your answer ]

  • If a=1, b=4, and c=1, expected output is:
    x = -0.267949192431 or -3.73205080757
  • If a=2, b=2, and c=2, expected output is:
    non-real answer

5. Motif checker (2pts)

Using raw_input(), prompt the user for a DNA sequence and a motif to search for (the sequence and motif can be any string of A/T/G/C's; see below for examples).

(A) Find the length of the motif and length of the DNA sequence and check if the motif is longer than the sequence. If it is, print "Motif is too long".


In [44]:
dnaSeq = raw_input("Enter a DNA sequence: ")
motif = raw_input("Enter a motif to search for: ")

if len(motif) > len(dnaSeq):
    print "Motif is too long."


Enter a DNA sequence: ATTGCGCGA
Enter a motif to search for: TTGAGCTGCGGATGCGAT
Motif is too long.

(B) Adding to your code from part (A): If and only if the motif is shorter than the sequence, go on to check if the motif can be found somewhere within the sequence (hint: use "in"). If it is found, print "Motif found". If it is not found, print "Motif not found".


In [45]:
dnaSeq = raw_input("Enter a DNA sequence: ")
motif = raw_input("Enter a motif to search for: ")

if len(motif) > len(dnaSeq):
    print "Motif is too long."
else:
    if motif in dnaSeq:
        print "Motif found."
    else:
        print "Motif not found."


Enter a DNA sequence: AGCTAGCCTGCTAGAAATCGATTGGCTAGCAATCTTATTGTGTTCTACG
Enter a motif to search for: ATG
Motif not found.

[ Check your answer ] Try running your code above using the following input and make sure your results match the expected output.

Sequence: AGCTAGCCTGCTAGAAATCGATTGGCTAGCAATCTTATTGTGTTCTACG
Motif: ATG
Expected output:

Motif not found

Sequence: AGCTAGCCTGCTAGAAATCGATTGGCTAGCAATCTTATTGTGTTCTACG
Motif: ATCGA
Expected output:

Motif found

Sequence: CTAGCC
Motif: ATGGCTAGCTA
Expected output:

Motif is too long

6. Password protection (3pts)

Write code that prompts the user to guess a password and checks whether the password is correct.

  • First create a variable called password and set it equal to whatever you want the password to be (any string).
  • Then prompt the user to guess the password, and read their input from the terminal.
  • Check if what they entered matches your password, and print a message saying whether or not the guess was correct.

(A) Do this giving the user only one chance to guess.


In [46]:
password = "Mittens123"
guess = raw_input("Enter the password: ")

if guess == password:
    print "Correct!"
else:
    print "Incorrect password. Access denied."


Enter the password: Mottens456
Incorrect password. Access denied.

(B) Do this giving the user 3 chances to guess. Only prompt for another guess if the previous guess was incorrect. When they guess correctly, print a confirmation message and end the program. If they don't guess correctly in 3 tries, print "Access denied!" and end the program.


In [48]:
password = "Mittens123"
guess = raw_input("Enter the password: ")

if guess == password:
    print "Correct!"
else:
    guess = raw_input("Incorrect password. Try again: ")
    if guess == password:
        print "Correct!"
    else:
        guess = raw_input("Incorrect password. Try again: ")
        if guess == password:
            print "Correct!"
        else:
            print "Incorrect password. Access denied."


Enter the password: Muttens777
Incorrect password. Try again: Mottens123
Incorrect password. Try again: Muppins321
Incorrect password. Access denied.

7. Coin flip simulation (2pts)

For this problem, we will simulate a coin flip using the random number generator in the random module.

Try running the following code several times:


In [ ]:
import random

randNum = random.randint(0,1)
print randNum

You should see that you always get either 0 or 1. We will pretend that each time we run random.randint(0,1) we are flipping a coin, where 1 represents heads and 0 represents tails.

Write code that "flips a coin" 10 times and counts how many times it comes up heads. At the end, print how many of the flips were heads.


In [50]:
import random

headsCount = 0

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

if random.randint(0,1) == 1:
    headsCount = headsCount + 1

print headsCount, "of 10 flips were heads"


4 of 10 flips were heads


Extra problems (0pt)

The following problems are for people who would like more practice. They will not be counted for points.

(A) Following from the coin flip problem above:

Change your code so that the coin is now "unfair" (i.e. the chance of heads is not equal to the chance of tails). See if you can make it so the probability of heads is 75%.

Hint: There are several ways to do this, but one simple way involves using a larger range of random ints and assigning heads/tails differently.


In [51]:
import random

headsCount = 0

# random.randint(0,3) gives a 0, 1, 2, or 3
# if it's 0, 1, or 2, call it heads
if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

if random.randint(0,3) < 3:
    headsCount = headsCount + 1

print headsCount, "of 10 flips were heads"


7 of 10 flips were heads

(B) Using raw_input(), prompt the user for a number. Check if that number is between 50 and 100, and print different messages depending on the outcome.


In [52]:
num = int(raw_input("Enter a number: "))
if (num >= 50) and (num <= 100):
    print "Your number is between 50 and 100"
else:
    print "Your number is not between 50 and 100"


Enter a number: 55
Your number is between 50 and 100

(C) Using raw_input(), prompt the user for an integer. Check if the integer is a multiple of 7, and print different messages depending on the outcome.


In [53]:
num = int(raw_input("Enter a number: "))
if (num % 7) == 0:
    print "Your number is a multiple of 7"
else:
    print "Your number is not a multiple of 7"


Enter a number: 42
Your number is a multiple of 7