3 + 5
4 * 2.1
8 / 3
2 - 15.3
3**7
Variables
We saw in the last exercise that Python can do simple calculations, such as
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:
- Starts with a letter, and
- Contains only the alphanumeric characters (a-z, A-Z, 0-9) and (if you wish) the underscore character, ‘_’. Note that variable names are case-sensitive, so
variablename
,variableName
andVariableName
are all treated as being distinct!
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:
= 17.3
azqg = 12.5
bppe = azqg * (1 + bppe/100) cdoq
= 17.3
cost_before_tax = 12.5
tax_rate = cost_before_tax * (1 + tax_rate / 100) cost_after_tax
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,
= 3
x = 2
y 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.
= 3
x = 2
y = x*y - y z
Now, z
contains the value 4. We can also reassign the value of a variable,
= 3
x = 2
y = x + y x
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\).
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!).
- Join them using underscores (e.g.
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
orix
), it is usual to choose the first letter appropriately. In particular, a barei
,j
,k
,m
orn
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
andgamma
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
orsum
). 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:
= 4.003
mass_of_helium = 20.180
neon_mass = 39.948
massArgon = 83.798
mKrypton = 131.293 mXe
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,
= 3
a type(a)
will print int
(shorthand for ‘integer’), while
= 3.0
a type(a)
will print float
(i.e., floating-point). We will encounter other types in due course.
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.
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’:
= <variablename>.<attributename>
a = <variablename>.<functionname>() b
For example, if we create a complex number \(z = 1+3i\) (where \(i = \sqrt{-1}\))
= 1 + 3j z
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.