Skip to main content

Section 1.4 Python recap

Python as a calculator. Python, at the lowest possible level, can be used as a calculator. The symbols for the four operations are the ones one writes on paper except for multiplication, whose symbol is *. Be careful: writing 3a for \(3\times a\) amounts to a syntax error, you must rather use 3*a.

Priorities. The priority among the four operations is the same as in any calculator: first the multiplications/divisions, then sums/differences. When one wants to enforce a different order of operations, parentheses must be used.

Square roots and other mathematical functions. Python by default has no mathematical functions defined besides the four operations mentioned above and a few others. In order to use square roots, sine and cosine functions and so on, it is needed to load an external module. The most general and powerful currently available is NumPy. A standard way to load numpy is using the syntax import numpy as np. After running this line, you can call mathematical functions as, for instance, np.sqrt (square root), np.sin (sine function) and so on.

BEWARE: the python web plugin used in this book (SageMathCell) loads and uses by default SymPy. Hence, if you set, within the book, a = sqrt(2), the variable a will be a symbolic variable, as opposed to a numerical one. It will be stored as 'the number whose square is 2'. Hence, the value of a*a is exactly 2! But no operation is performed to evaluate that square, simply SymPy knows that the square of the square root of a number is equal to the number itself.

The type of a variable. To know the type of a variable, say a, use print(type(a)).

The = symbol. Notice that the symbol = is used for assignments rather than for comparing quantities: the instruction a=2 assigns the value 2 to the variable named a.

Printing. In order to print the value of a numerical variable, say a, just use the code print(a). If you need to control the number of digits after the dot, use the slightly more spfisticated syntax print("a = %.17f" % a). This example will print 17 digits of a after the dot. If you want to display the result in scientific notation, then use print("a = %.17e" % a).

Example: