Variables

Authors

Andrew Valentine

Louis Moresi

Summary

In this section we will use variables to hold the results of calculations so that we can reuse them. This not only save computing things again and again but allows us to simplify expressions so that we make fewer mistakes. We will learn a number of tricks that make code more easy to read and, consequently, less likely to contain errors.

We saw in the last exercise that Python can do simple calculations, such as

3 + 5
4 * 2.1
8 / 3
2 - 15.3
3**7

On its own, this isn’t terribly useful. However, we can store the results of calculations, by ‘assigning’ them to a ‘variable’. To do this, we just need to type

We can use any name we want, provided it:

Strictly, your variable names can also begin with an underscore. However, there is a convention among Python programmers that this is done to signal to other programmers (and code editors) that the variable is ‘private’ or intended to be hidden in some way.

The computer doesn’t care what name you use. However, humans who have to look at your program will be much happier if you use names that describe what the quantity ‘means’. The computer will treat these two examples identically:

azqg = 17.3
bppe = 12.5
cdoq = azqg * (1 + bppe/100)
cost_before_tax = 17.3
tax_rate = 12.5
cost_after_tax = cost_before_tax * (1 + tax_rate / 100)

Which one do you find easier to understand ?

You may encounter code that looks more like (1) than (2). This is because early programming languages placed strict limits on the length of variable names (see this wikipedia article). However, there is no longer any need for this and (we think) you should avoid it at all costs !

Using variables

As you may have noticed from the above example, once we have set the value of a variable, we can use it in calculations. Thus,

x = 3
y = 2
print(x * y)

will perform the calculation \((3\times 2) = 6\), and display the answer on the screen. If we wish, we can choose to assign the result to another variable, e.g.

x = 3
y = 2
z = x*y - y

Now, z contains the value 4. We can also reassign the value of a variable,

x = 3
y = 2
x = x + y

Notice that x appears on both sides of the equals sign here. This should be read as ‘do the calculation x + y and then store the result in x (over-writing whatever was there before)’. We end up with x containing the value \(3 + 2 = 5\).

Try creating some variables, and using them in simple calculations. Start with the examples above. Be sure to check that the results match what you expect.

Constructs such as x = x + y are so common that Python has a special shorthand notation for this. We can express the same equation by entering x += y. There are similar versions for other operators: -=, *= and /=.

Try out these shorthand operators. Is x += 3 the same as 3 += x? Why / why not ?

There is no particular advantage to using these short forms, except convenience and readibility.

Naming Conventions

You can call your variables anything you like. However, following a few conventions will improve the clarity of your code:

  • If your variable name is made up of multiple words, either:

    • Join them using underscores (e.g. a_long_variable_name = 17), or
    • Capitalize the first letter of each word (e.g. AnotherLongVariableName = 23.6). This is sometimes referred to as ‘camel case’ or ‘CamelCase’(since it is lower case with extra humps!).
  • It is common but not compulsory to use UPPER CASE for constants that should never need to be changed within the program, e.g. GRAVITATIONAL_ACCELERATION = 9.81.

  • Traditionally, variables that contain integers have names beginning with the letters i, j, k, l, m, or n; variables containing real numbers start with any other letter. This comes from early programming languages (especially Fortran) where it was a requirement, and follows a similar convention in mathematics. Nowadays, this convention is often ignored for long variable names. However, if your name only contains one or two characters (e.g. a or ix), it is usual to choose the first letter appropriately. In particular, a bare i, j, k, m or n should only be used for a counting index (more on that later). If you ignore this rule, the program will work fine, but you can expect anyone who has to decipher your code in future to get more than a little bit frustrated with your choices.

Some other tips:

  • If your code is connected to another document (e.g. you are trying to plot some equation from a paper) then use clearly-related names in both. For example, if your paper has the equation \(y = \alpha x +3\gamma\), then use the variable names x, y, alpha and gamma in your code. You can even use unicode.
  • Make your variable names long enough to be clearly understood, but not too long. At most, you probably want it to be based on two or three words.
  • Do not give your variable a name that has a special meaning in Python (e.g. int or sum). Doing so will not always cause problems, but it is a common source of grief.

Above all, try and develop a consistent style, and name similar quantities in similar ways. For example, the following are individually all reasonable choices for variable names:

mass_of_helium = 4.003
neon_mass = 20.180
massArgon = 39.948
mKrypton = 83.798
mXe = 131.293

However, mixing the different styles within one program is guaranteed to cause you confusion and lead to errors. Pick one format that makes sense to you, and stick with it.

Types

Any and every variable has a type. We can ask Python to report on the type of a given variable by using the command type(variable_name). For example,

a = 3
type(a)

will print int (shorthand for ‘integer’), while

a = 3.0
type(a)

will print float (i.e., floating-point). We will encounter other types in due course.

Try creating some variables, and using them in simple calculations. Start with the examples above. Be sure to check that the results match what you expect.

What happens if you mix different types, ?

i = 2
a = 3.0 * i
print(type(i), type(a))
print(a)

print(i / 2)
print(i / 3)

Application: Salary calculations

Let’s try doing a real-world calculation. Suppose your annual salary is $ 164,402, and the annual tax rate is 35%. How much money should be paid into your bank account every two weeks?

What if you happened to be a famous musician in 1960s London, where the tax rates were more progressive. Suppose you earn $1,987,231.20 and the tax rate is just 20% on the first $50,000 that you earn, and 95% on the remainder.

Calculate your fortnightly pay as a non-musical researcher Remember, break the problem down into individual steps, and create variables for each of the quantities involved! You should find the answer is $ 4110.06.

Now repeat the calculation for the higher-income scenario. Wait, isn’t that the same ?

  Let me tell you how it will be
  There’s one for you, nineteen for me
  â€™Cause I’m the taxman
  Yeah, I’m the taxman
  Should five percent appear too small
  Be thankful I don’t take it all
  â€™Cause I’m the taxman
  Yeah, I’m the taxman

  Taxman George Harrison, Revolver

Variables are more than just variables

As we saw earlier, each variable we create has a type. Most variables come with certain functions and attributes ‘attached’ to them, to perform various operations that are commonly-required for that data type. These can be accessed using a ‘dot’:

a = <variablename>.<attributename>
b = <variablename>.<functionname>()

For example, if we create a complex number \(z = 1+3i\) (where \(i = \sqrt{-1}\))

z = 1 + 3j

we can then access two attributes and a function, - z.real - The ‘real part’ of the complex number - z.imag - The ‘imaginary part’ of the complex number - z.conjugate() - Function returning the ‘complex conjugate’ of z

Similarly, any floating-point number, v, comes with a v.as_integer_ratio() function that reports \(a\) and \(b\) such that \(v = a/b\). To see the full list of functions associated with any variable v, type help(v). You can also type v. and then hit the Tab key.

Coding scratch space