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:
name = "World"
print("Hello",name)
Now we can change the value stored in the variable name, and execute the same code:
name = "James"
print("Hello",name)
We can change the value stored in the variable and still use the same print statement to get different output.
But we can use variables to store numerical values as well as strings. Let's create a variable to hold James' age:
age = 25
print(name,"is",age,"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.
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:
mass_in_kgs = 70.0
print(name,"has a mass of",mass_in_kgs,"kg")
mass_in_lbs = 2.2 * mass_in_kgs
print(mass_in_kgs,"kg is equivalent to",mass_in_lbs,"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
.