Lesson 2. Names

2023-01-23

There are only two hard things in Computer Science: cache invalidation and naming things. Phil Karlton

Objectives

The aim of this lesson is to understand the use of variables and functions.
How to write your own functions is the topic of another lesson; for now, our concern is just with using functions available from existing Python modules.
In earlier lessons, our examples made informal use of variables and functions, but we now take a more precise approach.

After the lesson, you should know


Variable Names

A variable name is a sequence of upper or lower case letters (A-Z, a-z), digits (0-9) and underscores (_). In addition, a valid name must not begin with a digit. At the IPython prompt, try typing

3Jane = 1.5

In this case, Python raises a SyntaxError. A name is allowed to begin with an underscore, but by convention this practice is recommended only in special circumstances that are beyond the scope of this lesson. Underscores are useful mainly in longer names that require more than one word, e.g.,

escape_velocity = 11.2

Also, IPython assigns the value of the most recent result to _, which can be useful for interactive calculation. Try the following.

exp(-2)+sin(4)
_ + 1

Python reserves certain keywords such as ‘if’, ‘for’, ‘and’, ‘return’ and ‘except’ that have a special meaning and cannot be used as names for variables. To see a complete list of reserved words, type the command

help('keywords')

Python names are case sensitive so, e.g., in a vote-counting program you could use variables ‘For’ and ‘Against’ even though ‘for’ is reserved. Probably ‘Yes’ and ‘No’ (or ‘Yea’ and ‘Nay’) would be better choices to avoid confusion.

Assigning Values

The equal sign = is used to assign a value to a variable. The value can be a literal constant, as in the escape_velocity example above, or it can be an expression. Consider the following statements.

x = 4
x = x + 1/x

The first statement assigns the value 4 to x, after which the second statement evaluates the expression x + 1/x, obtaining the result \(4 + 1/4=4.25\), and assigns this value to x. Note that the second statement is not asserting that x equals x+1/x; in fact, the mathematical equation \(x=x+1/x\) is not satisfied by any number \(x\). You should therefore read the second statement as ‘x is assigned the value x + 1/x’ or ‘update x to the value x + 1/x’ or, more succinctly, ‘x gets x + 1/x’.

In any assignment statement, all variables appearing on the right-hand side must have previously been assigned a value. For example, if you have not already defined z then the statement

x = z**2 + 3

will raise NameError: 'z' is not defined.

Exercise. Solve the quadratic equation \(x^2-x-2=0\) using the standard formula \[ x_\pm=\frac{-b\pm\sqrt{b^2-4ac}}{2a}. \] Assign the appropriate values to variables called a, b, c, sqrt_dscr (square root of discriminant), x_plus and x_minus.

Constants

You will often want to use special constant values. Rather than defining them yourself, say pi = 3.14159, it is easier (and typically more accurate and less error-prone) to rely on a value provided from a module. In particular, NumPy defines the constants in the table below.

Name Symbol Value
e \(e\) 2.718281828459045
euler_gamma \(\gamma\) 0.5772156649015329
pi \(\pi\) 3.141592653589793

Also useful are the machine epsilon, the largest (finite) floating-point number and the smallest (positive normalised) floating-point number.

eps = finfo(float).eps
huge = finfo(float).max
tiny = finfo(float).tiny

Combining Assignment with Arithmetic

Python defines +=, -=, *=, /= for updating a variable. For example, the statement

x += 5

is a shorthand for

x = x + 5

Similarly, x *= 2 is a shorthand for x = x * 2, and so on for the others.


Modules and Names

Python has a large standard library organised into modules. For example, suppose that we would like to see the calendar for June, 2022. There is a calendar module with a function prmonth that is just what we need. An import statement is needed before we can run the function.

from calendar import prmonth
prmonth(2022, 6)

Alternatively, we can import the module and call the function using its qualified name.

import calendar
calendar.prmonth(2022, 6)

The first approach saves typing if you will use the function name several times, but the second is sometimes more convenient. A third option, convenient for interactive use, is

from calendar import *

which imports everything from the calendar module. In Lesson 0, we saw how to configure Spyder so that the IPython shell does this automatically for the numpy module.

Any sufficiently large codebase needs a way to resolve name clashes. This problem arises when different parts of the code, typically written by different people, use the same name for different objects.

For example, consider two modules garden and kitchen. The first might define a function prune for pruning a tree, and the second a function prune for adding prunes to a recipe. In the (perhaps unlikely) event that we want to write a program that uses both objects, we need a way to distinguish between them. One option is to import the modules

import garden
import kitchen

and use garden.prune() and kitchen.prune(). Alternatively, we can import the functions but assign a distinct alias to each. After

from garden import prune as g_prune
from kitchen import prune as k_prune

we can use g_prune() and k_prune().

Note that variable names as well as functions have to be imported before they can be used. For example, if you needed the value of \(\pi\) in a Python program, then you would use the statement

from numpy import pi

Summary

We have seen

Further Reading

The Style Guide for Python Code sets out the standard conventions for formatting Python programs). In particular, the section on Naming Conventions provides detailed advise about choosing names for variables and functions.

Back to All Lessons