Variables and Assignment

Overview:

  • Teaching: 10 min
  • Exercises: 5 min

Questions

  • How can we store and access data?
  • How does this allow us to write more general code?
  • What happens when we assign one variable to another?

Objectives

  • Understand that using variables allows us to generalise the behaviour of our code.
  • Write programs that assign values to variables and perform calucations with them.
  • Understand that values persist within the Ipython3 session
  • Correctly trace value changes in programs.

Strings in variables

It would be good if instead of having to explicitly type out the values that we wish to print or calculate we could store and access them so that we could re-use programs. We do this with variables and we'll start by considering our Hello World! program from the previous episode. Let's generalise the original code:

In [1]:
name = "World"
print("Hello",name)
Hello World

What have we done?

We have created a variable called name and assigned it the value "World", which means that the variable contains a string. When we want to access the value stored in name, e.g. by printing it to the screen, we can do so by referencing the variable name. Note that:

  • We can print a list of items by separating them with commas, when the code is executed Python puts a space between them.
  • When we reference the variable name we do not put it in quotes.
  • The variable name points to some space in the computers memory that allows us to access the contents, we can think of it like an address.
  • The equals sign = is subtly different to the mathematical symbol which means one thing is equal to another. When we use = in Python it means put the value on the right, into the variable on the left. This is what we mean when we assign a value to a variable.

Strings and Variables

What would happen if we ran the following code?

print("Hello","name")

Solution

Now we can change the value stored in the variable name, and execute the same code:

In [3]:
name = "James"
print("Hello",name)
Hello James

We can change the value stored in the variable and still use the same print statement to get different output.

Numerical Variables

But we can use variables to store numerical values as well as strings. Let's create a variable to hold James' age:

In [4]:
age = 25
print(name,"is",age,"years old.")
James is 25 years old.

As before we have used print to print a list of items, the two variables name and age, interspersed with some text (strings) to give the sentence meaning. It is often good to do this so that we can make sense of the output. Similarly note that we have used meaningful names for the variables, in that name is being used to store name and age, an age. The variable name set to "James" persists as long as we are in the same session, meaning it keeps the same value and we can continue to access it.

Calculating with variables

Again though rather than just storing numbers we really want to be able to perform calculations to make our research easier. Let's consider the following:

In [5]:
mass_in_kgs = 70.0
print(name,"has a mass of",mass_in_kgs,"kg")
James has a mass of 70.0 kg
In [6]:
mass_in_lbs = 2.2 * mass_in_kgs
print(mass_in_kgs,"kg is equivalent to",mass_in_lbs,"lbs")
70.0 kg is equivalent to 154.0 lbs

Once again we emphasise that the = takes the value of the right, which in this case involves performing the calculation 2.2*70 and assigns the result to the variable mass_in_lbs. Also since we haven't changed the value stored in mass_in_kgs we can continue to access it and use it for calculations, as we have in using it to assign a value to mass_in_lbs.

What happens if we change mass_in_kg?

If we change the value of mass_in_kg e.g. by setting the value to 75.0, what will happen to mass_in_lbs? Once you've decided what you think will happen try it.

Solution

What variable names should I use?

Variable names must begin with a character from the alphabet, and contain only alphanumeric characters and the underscore _, which we used in place of spaces in mass_in_kg. Why didn't we call the four variables used above flibble, x1_33,sqwark and woof?

Solution

Using a new variable?

What happens if I try running the following code, without having assigned a value to the variable my_new_variable

print(my_new_variable)

Solution

Python is case sensitive

Python is case senstive. This means that variables and functions when we get to them must be referenced with the correct case. Typically we might choose only to use lower case letters to avoind issues. Try the following:

In [10]:
kitten = "Bert"
print(Kitten)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-5237b6d04162> in <module>
      1 kitten = "Bert"
----> 2 print(Kitten)
NameError: name 'Kitten' is not defined

Key Points:

  • Variables are used to store and access values in our programs.
  • print(variable) displays the value stored in the variable.
  • We use = to assign a value to a variable in order to record it in memory.
  • When one variable is used to assign a value to a second when we change the first, the second does not change.
  • Using informative variable names makes you code more readable.
  • Variables must be assigned values, before they can be used.
  • Python is case sensitve!