Programming Bootcamp 2016

Lesson 1 Exercises -- ANSWER KEY



Notes on using this notebook

  • Cells with In [] next to them are code cells. Run code using Ctrl+Enter (or Shift+Enter)
  • In places where it says "Your guess" or "Your answer", double click to edit the cell with your answer.
  • I will often provide you with expected output for a given problem. Use this to check that your code is correct.
  • If the directions for a question don't specify a particular way of doing things, this means you can do it however you want (within reason). For example, if I don't specifically say "print using one line of code", then you can print using multiple print statements if you want.

1. Guess the output: print statement practice (1pt)

For the following blocks of code, first try to guess what the output will be, and then run the code yourself. These examples may introduce some ideas and common pitfalls that were not explicitly covered in the lecture, so be sure to complete this section. Points will be given for filling in the guesses; guessing wrong won't be penalized.

I will add some comments on the ones that might have been the most confusing...


In [1]:
print "what's", "up"


what's up

In [2]:
print "what's" + "up"


what'sup

In [3]:
print "I have", 5, "cats"


I have 5 cats

In [4]:
print "I have" + 5 + "cats"


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-54b359d3a0fc> in <module>()
----> 1 print "I have" + 5 + "cats"

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

In [5]:
print 9 - 6 * 2


-3

In [6]:
print (9 - 6) * 2


6

In [7]:
print 24 % 6


0

In [8]:
print 24 % 7


3

In [9]:
print -3 ** 2


-9

To make this work properly, you need to do: (-3) ** 2


In [10]:
print 9 / 2


4

Your guess:


In [11]:
print 9.0 / 2


4.5

Your guess:


In [12]:
print 9 / float(2)


4.5

Your guess:


2. Guess the output: variables practice (1pt)

For the following blocks of code, first try to guess what the output will be, and then run the code yourself.


In [13]:
x = 5
print x * 3


15

In [14]:
x = "5"
print x * 3


555

Yes, this works! It's a weird shortcut that Python provides for duplicating strings.


In [15]:
x = "5"
print int(x) * 3


15

In [16]:
x = "cat"
y = x
print y


cat

In [17]:
x = "cat"
y = "dog"
x = y
y = x
print y


dog

In [18]:
x = "cat"
y = "dog"
print x + y


catdog

In [19]:
x = 5
x = 1
print x


1

In [20]:
x = 5
x + 1
print x


5

Remember that to actually change a variable, you need to use the assignment operator (=). Saying "x+1" doesn't overwrite the value of x. We would need to say "x = x+1".


In [21]:
x = 2
y = 4
print (x * y) ** x


64

In [22]:
x = 16
print x ** 0.5


4.0

Raising something to the power of 0.5 is the same as taking the square root. ~MATH~


3. On your own: printing (1pt)

Write a single line of code that prints your name:


In [23]:
print "Sarah"


Sarah

Add a single line of code to what's already below to print the variables color and number:


In [24]:
color = "magenta"
number = 2715

print color, number


magenta 2715

4. Fix the code (1pt)

The following code blocks have bugs. Fix each one so that it runs without error. There may be multiple errors!


In [26]:
print "I bought", 10, "pizzas"


I bought 10 pizzas

Bug: tried to add together strings and ints.

There's more than one right way to fix this. Above is one option. You could also convert 10 to a string by putting it in quotes or using str(10)


In [27]:
firstPerson = "Joe"
print firstPerson


Joe

Bug: illegal variable name (starts with a number)

Fix: change the variable name


In [28]:
fruit = "Banana"
print "I bought a", fruit


I bought a Banana

Bug: typo in variable name ("friut")

Fix: fix typo


In [30]:
age = "25"
name = "Wilfred"
introduction = "Hello, my name is " + name + " and I am " + age + " years old."
print introduction


Hello, my name is Wilfred and I am 25 years old.

Bug 1: Wilfred is not enclosed in quotes. Python thinks it is a variable instead of a string.

Fix 1: Put Wilfred in quotes


Bug 2: Missing a + between age and " years old."

Fix 2: Add the +


Bug 3: print misspelled on last line

Fix 3: fix typo


5. Math practice I (1pt)

The equation for a line is

y = mx + b

Write code to solve for y for a given m, x, and b. Print the value of y at the end. Use the code below as a starting point, and fill in the rest of the needed code.

[ Check your answer ] For the given values of m, x, and b below (0.5, 10, 3), you should get the answer 8.0.


In [31]:
m = 0.5
x = 10
b = 3

y = m * x + b
print y


8.0

6. Math practice II (2pt)

The quadratic formula is defined as:

$$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$

Write code to calculate the quadratic formula for a given a, b, and c. Your code should print both possible values for x (that is, the values produced by doing + or - for the $\pm$).

I haven't told you yet how to find the square root in Python because I'd like you to look this up for yourself! There are actually several different ways -- try googling it.

[ Check your answer ] For the given values of a, b, and c (-2, 2, 1), you should get the answers -0.366 and 1.366.


In [32]:
a = -2
b = 2
c = 1

# raising to the 0.5 power is the same as taking the square root.
# alternatively, you can use the sqrt() function from the math module.
x1 = ( (-b) + (b**2 - 4*a*c) ** 0.5 ) / float(2*a)
x2 = ( (-b) - (b**2 - 4*a*c) ** 0.5 ) / float(2*a)

print "x =", x1, "or", x2


x = -0.366025403784 or 1.36602540378

After you verify that your code works, try a few different values of these variables. Note, you will get an error message if $b^2 - 4ac$ is negative, since you can't take the square root of a negative number. This is fine for now -- later we'll go over ways to prevent errors like that from occurring.


7. Reading user input (1pt)

We'll go over this next time, but here's a head start. Run the following code:


In [ ]:
print "Enter your first name"
firstName = raw_input()
print "Enter your last name"
lastName = raw_input()
print "Welcome,", firstName, lastName

What happens? What does raw_input() do?

https://docs.python.org/2/library/functions.html#raw_input

raw_input() allows you to get user input. Execution pauses until the user enters some text and hits "enter". The input is then converted to a string and can be saved in a variable.

Google it to see if you're right.

Here's another way you can use the raw_input() function:


In [ ]:
firstName = raw_input("Enter your first name:")
lastName = raw_input("Enter your last name:")
print "Welcome,", firstName, lastName

Run this. What is different about the output?

Now there's a prompt on the same line instead of the line before. (This is not necessarily better, it's just another way of doing it.)

Oftentimes we can change the behavior of a function by putting different things within the () braces. The values we put in these braces are called arguments. They're sort of like options that you send along with the function that make it do slightly different things. In this case, raw_input() only takes one argument, which is a string that it uses as a "prompt". Different function take different types/numbers of arguments. We're going to see this a lot in the future, so just keep it in the back of your mind.


8. Interactive quadratic formula (2pt)

Edit your quadratic formula code from problem 6 so that it takes the values of a, b, and c interactively using raw_input().

Hint: you may have noticed when you looked up raw_input() that it reads in everything as a string. So if you input 3.5, what actually gets read is "3.5" (a string). This will cause an error when you try to do math using these values. To use them as decimal numbers, we must convert them from strings to floats using the float() function.

Here's an example of how to do this:

age = raw_input("Your age:")
age = float(age)

Or:

age = float(raw_input("Your age:"))

Now, apply this to your quadratic formula code to read in the values of a, b, and c. Check that you still get the correct answer!


In [34]:
a = float(raw_input("a = "))
b = float(raw_input("b = "))
c = float(raw_input("c = "))

x1 = ( (-b) + (b**2 - 4*a*c) ** 0.5 ) / float(2*a)
x2 = ( (-b) - (b**2 - 4*a*c) ** 0.5 ) / float(2*a)
print "x =", x1, "or", x2


a = -2
b = 2
c = 1
x = -0.366025403784 or 1.36602540378