Variables#

How do I use the Exercises?#

  1. Go to the course website: [http://janclemenslab.org/neu715/intro]

  2. In the table of content on the left, go to “Basics - exercises/Variables”

  3. Then, in the top bar do one of the following:

    • If you have a working python installation: Click on the arrow to download the notebook with the exercises and open it in jupyter.

    • If you do not have a running python yet (let us know - we can help): Click on the rocket icon and run the notebook in google colab (more reliable but requires a google account) or in binder (less reliable but does not require any account).

Exercise 1: Variables and arithmetic#

Compute the density of a whale using variables#

Mabel and Jolanda, our friends from the department of marine biology, ask us to help them with automating a computation for them. They have measured the weight and volume of Keiko, a whale they are tracking:

  • mass 41928 kg

  • volume 77.05 \(m^3\)

They want to know Keiko’s density. Knowing only basic python, they compute the whale’s density as the ratio of its mass and volume:

41928 / 77.05
544.1661258922777

This code has several disadvantages:

  • It is inflexible: Data values and computation are mixed.

  • It is not readable: It’s unclear from the code alone what the two values are and what the code does!

Improve the code using variables#

  • Make it flexible: Separate data and computation by creating two variables for mass and volume and by computing the density as the ratio of the two.

  • Make it readable: Give your variables meaningful names that indicate their content - do not use a and b. Add comments to indicate the variables’ units.

# your code here

Compute the whales’ combined mass and volume, their individual densities, and the average of their densities.#

Mabel and Jolanda, our friends from the department of marine biology, need to ship Keiko and her mate, Moby, to the pacific. To know whether the capacity of our container is sufficient, they need to know their combined mass, their combined volume, and their average density. They need our help again!!

Execute below cell once to create the variables for the whales’ individual volumes and masses. Then perform the computations on these variables in the cell “COMPUTATION!” below that.

mass_keiko = 41928  # kg
vol_keiko = 77.05  # m^3

mass_moby = 38653  # kg
vol_moby = 67.23  # m^3
# COMPUTATION!
# your solution here
combined_mass = ...
combined_volume = ...

density_keiko = ...
density_moby = ...

average_density = ...

Exercise 2: Calculate the area and the volume of a cube.#

Here are the formulas for the area and volume of a cube:

  • \(A = W * D\), \(A\) is the area of the base of the cube, and \(W\) and \(D\) are the width and depth.

  • \(V = W * D * H = A * H\), \(H\) is the cube’s height

Make your code efficient by re-using already calculated results.

# use these variables
width = 10
depth = 2
height = 100

# your solution here
area = ...
volume = ...

Exercise 3: Calculate the circumference and area of a circle and the volume of a sphere#

  • circumference of a circle: \(2*\pi*r\)

  • area of a circle: \(\pi * r^2\)

  • volume of a sphere: \(4/3 * \pi * r^3\)

\(\pi\) is approximately 3.14. Make your code efficient by re-using already calculated results.

Bonus: Use google to find out how to get the actual value of pi in python.

pi = 3.14
radius = 85

# your solution here

Exercise 4: variable types and type casting#

Adding two numbers, two strings, and a string and a number#

We know what happens when we add two variables that are numbers:

x = 1
y = 58
x + y  # 59

Try and see what happens if you add two variables that are strings?

x = "George"
y = "Michael"
x + y  #?

Can you explain what is happening here? Why does the “+” sign do different things for numbers and strings?

Try and see what happens if you add a variable that is a string to one that is a number?

x = 10
y = '20'
x + y  # ?

Why does this fail?

# your try-and-see-what-happens code here

Fix the last error above using type casting#

In the previous exercise, you observed that adding variables of different types - for instance a string and a number does not work.

You can fix this by converting the types of variables so that they match - a procedure called type casting.

A variable can be converted:

  • to text via the str (string) function,

  • to an integer number via the int function,

  • to a floating point number via the float function.

print('"str" turns a variable into a string', str(10.0))
print('"int" turns a variable into an integer number', int('10'))
print('"float" turns a variable into an floating point number', float('10.0'))
"str" turns a variable into a string 10.0
"int" turns a variable into an integer number 10
"float" turns a variable into an floating point number 10.0

Fix below code by casting the variables

  1. to text using str() and

  2. to numbers using float() or int()

Remember, functions are used via their name, followed by the input argument in parentheses: output = function(input)

# FIXME!
x = 10
y = '20'
x + y
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[9], line 4
      2 x = 10
      3 y = '20'
----> 4 x + y

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Exercise 4: Keeping track of and re-using variables#

Since all cells in your notebook share the same namespace, you can re-use variables that you have created in another cell. This allows you to split your computation into multiple cells.

Caution: This re-use can have unexpected consequences if you run the same cell multiple times while coding or if you run your cells out of order.

Let’s do some exercises about that:

What’s the value of x at end of the program below?#

Go through the program line-by-line without running it and explain the value of x.

w = 100
x = 2
x = w

And what is the value of x after running this line? Why?

x = x + 10

What’s the value of c if we run the code below? What is the value of c if we run below code a second time?#

Try to predict what will happen before you run the code. Was your prediction you correct?

c = 1  # create a new variable `c` and give it a particular value (aka assign a value to `c`)
d = c + 5   #  create a new variable `d` and assign to it the outcome of `c + 5`
c = c + 8  # you can also re-assign values to existing variables - this allows you to update a variable during computation
c
9

Again: What’s the value of c if we run the code below once? What is the value of c if we run the code a second time?#

Predict what will happen without running the code (you need to have run the cell above before). Explain why.

d = c + 5   #  create a new variable `d` and assign to it the outcome of `c + 5`
c = c + 8  # you can also re-assign values to existing variables - this allows you to update a variable during computation
c
25

What’s the value of c in the below code?#

Why is it not 16 + 4 = 20?

c = 16
d = c + 2
c + 4
c
16