The Basics PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

7/6/2019 The Basics

The Basics
In this section we introduce how we can use Python for basic calculations. From this you might think that
programming is similar to using an advanced calculator. It is certainly true that you can use Python in this way.
However, we will see later on that computer programming allows us to do much more than simple numerical
calculations. From now on, whenever you reach for a calculator (or a spreadsheet program), you should
immediately thing of using Python instead.

Numbers

Integers (int)
Whole numbers or integers can be entered directly. You can use a minus sign for negative numbers.

0
1
-1
314159
-200

In mathematics or finance we sometimes use commas or spaces in large numbers such as 10 000 000. This is
not allowed in Python. Putting a space in a number will result in a syntax error (try this). Digits separated by
commas will be interpreted as separate numbers.

If you make a script containing the numbers and execute this script, you will see no output other than the last
number. You have to use the print command to print (display) the output.

In [1]: # script to print some integers


print(0)
print(1)
print(-1)
print(314159)
print(-200)

0
1
-1
314159
-200

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 1/9
7/6/2019 The Basics

Floating point numbers (float)


Python can also work with numbers with a decimal point.

1.2
-3.4
0.0005
33.98

These are called floating point numbers in Python.

Scientific/engineering notation
Very big or very small floating point numbers can be entered using scientific notation.
The number 5.6 × 10 is typed as 5.6e17 (the letter e stands for exponent).
17

We can output several values at once by separating them with a comma. The values are separated by a single
space in the output.

In [2]: print(2e6, 1e-3, 5.6e17, 1.618e-20)

2000000.0 0.001 5.6e+17 1.618e-20

Arithmetic
The following examples show how to do addition, subtraction, multiplication, division and exponentiation. The
comments starting with # are for your information only and are ignored by the Python interpreter.

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 2/9
7/6/2019 The Basics

In [3]: # python arithmetic


print(9+16) # addition
print(25-9) # subtraction
print(4*5) # multiplication
print(9/4) # division
print(9//4) # integer division
print(2**5) # exponentiation (power)
print(4.4+2.5)
print(8.7*1.2)
print(1.0/7.0)
print(1.0//7.0)

25
16
20
2.25
2
32
6.9
10.44
0.14285714285714285
0.0

Note that multiplication symbol * is always necessary. This is especially important once we start using variables
and parentheses. In mathematics we often write: 5x = 5 × x and 5(3 + 4) = 5 × (3 + 4).

In [4]: # The following will give an error:

print(5(3 + 4)) # use: 5 * (3 + 4)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-7ab2cf2256ab> in <module>()
1 # The following will give an error:
2
----> 3 print(5(3 + 4)) # use: 5 * (3 + 4)

TypeError: 'int' object is not callable

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 3/9
7/6/2019 The Basics

When combining several arithmetic operations in one expression, the order in which the calculations are carried
out is the standard BODMAS rule:

1. Brackets (parantheses),
2. Orders (roots and powers/exponentiation),
3. Multiplication
4. Division / Multiplication,
5. Addition / Subtraction.

Combinations of addition and subtraction are carried out from left to right.
This means that 1 - 2 + 3 is equivalent to (1 - 2) + 3 and not 1 - (2 + 3). calculations.
The same holds for combinations of multiplication and division.
For example, 6/2*3 is equivalent to (6/2)*3 and not 6/(2*3). Note that the use of spaces
does not influence the order of calculations, e.g. 6 / 2*3 is equal to (6/2)*3.

The order of operations can be changed by using parentheses (()). Only parentheses (round brackets) can be
used. Square brackets ([]) and braces (curly brackets) ({}) have a special meaning in Python and cannot be
used to change the order of operations.

In [5]: # some arithmetic operations


print(2+3*5)
print((2+3)*5)
print(-(9+4))

17
25
-13

Note that it is not a good idea to use expressions like 3**2*2.


You should use parentheses to make it clear that you mean (3**2)*2 and not 3**(2*2). (Try
these examples.)
In certain cases you should use parentheses even though they are not strictly necessary.
For example an expressions like 2*3*4/7*8 would be clearer when written as (2*3*4/7)*8
Spaces around mathematical operations are allowed and it is recommended to use extra spaces to
make mathematical expressions clearer. Beware that the extra spaces do not have any special
meaning for Python.

In [6]: # use of spaces


print(2 + 3*5) # GOOD
print(2+3 * 5) # BAD, this is equal to 2+(3*5) and NOT (2+3)*5

17
17

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 4/9
7/6/2019 The Basics

Arithmetic Involving Integers


When adding, subtracting or multiplying integers, the result will always be an integer. The same is true for
exponentiation if the exponent is positive. For negative exponents the result will be a floating point number.

In [7]: 10**(-2)

Out[7]: 0.01

The parentheses are not strictly necessary in this case, but it is a good habit to use them.

Mixing integers and floating point numbers in the same expression is allowed. Whenever integers and floating
point numbers are combined in the same expression, the result will be a floating point number.

In [8]: (1 + 0.4) * 5

Out[8]: 7.0

A division involving two integers will always result in a float in Python 3 (this has changed from Python 2).

In [9]: 11/5

Out[9]: 2.2

If you want the integer result, use the int() function (also see the // operator).

In [10]: print(11/5)
print(int(11.0/5.0))
print(11//5)

2.2
2
2

The remainder after integer division can be found using the operation %

In [11]: print(11 % 5)

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 5/9
7/6/2019 The Basics

Converting the type of number


Integers and floating point numbers are different types of values in Python, and behave differently when doing
mathematical calculations (see later).

Special in-built functions int() and float() can be used to convert between types.

A function is a key-word followed by round brackets (parentheses).


the input (called the "argument") to the function goes into the brackets.
the function gives (or "returns") an output:

In [12]: print(int(3.14))
print(float(5))

3
5.0

Other useful functions


Some other functions come with basic Python that can be used on numbers.

The round() function takes a number and rounds it up or down, depending on certain rules
(https://docs.python.org/release/3.1.5/library/functions.html#round) (but the behaviour might not be as you
expect from maths):

In [13]: print(round(4.49))
print(round(4.50))
print(round(4.51))

4
4
5

The abs() function for absolute values

In [14]: abs(-10)

Out[14]: 10

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 6/9
7/6/2019 The Basics

Using "libraries" to add new functionality to Python


Some features come with Python but are not available straight away, we need to add them at the top of a script.

Importing a whole library into Python


For example to use constants such as π or e we can import a library called math, using an import statement:

In [15]: # how to import a library


import math

pi_approximation = 355.0/113.0
e_approximation1 = (1.0 + 1e-6)**(1e6)
e_approximation2 = 1 + 1 + 1.0/2 + 1.0/2/3 + 1.0/2/3/4 + 1.0/2/3/4/5

print(math.pi, pi_approximation - math.pi)


print(math.e, e_approximation1 - math.e, e_approximation2 - math.e)

3.141592653589793 2.667641894049666e-07
2.718281828459045 -1.359363291708604e-06 -0.0016151617923787498

Notice how the values of the constants pi and e are called from within the math library using the "dot"
syntax. That is, the name of the loaded library, followed by a "." and then the thing we want from
within the library (with no spaces).

This "dot" method is used a lot in Python to access functions or variables within other so called "objects".

Importing particular objects from inside a library


Some functions such sine, cosine or square root also need importing from libraries. In this case we can only load
the bits we need from math, instead of using the dot method (which also works).

In [16]: from math import sin, cos, sqrt, pi

print(sqrt(2), sin(pi/2), cos(0))

1.4142135623730951 1.0 1.0

degs
Note: angles are in radians so you need to convert using rads = × π
180

there is also a "convenience function" deg2rad, which lives in another library called numpy
(Numerical Python), which also has its own versions of mathematical constants and functions:

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 7/9
7/6/2019 The Basics

In [17]: import numpy

print(numpy.sin(90*math.pi/180), numpy.sin(numpy.deg2rad(90)))

1.0 1.0

Notice how we can also put a function in the argument (input) to another function.

Importing libraries with a pseudonym


To make typing easier we can import a library and give it a nickname, using import as:

In [18]: import numpy as np


from numpy import deg2rad as d2r

print(np.sin(d2r(90)))

1.0

If you want to know what functions are available you can either:
1. search the internet (google: "python numpy functions")
2. start typing in Spyder and wait for the pop-up to appear

#type the following in Spyder and pause...


import numpy
numpy.

3. use the in-built dir function:

import math
dir(math)

4. Use the in-built help fuunction:

import math
help(math)

Appendix: A note on floating point precision


The floating point numbers in Python have a precision of approximately 16 significant digits and this can cause
rounding errors.

Mathematically, the result of the calculation (1 + a) − 1 is a, no matter what the value of a is.

With finite precision the result can be less accurate for smaller the values of a:

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 8/9
7/6/2019 The Basics

In [19]: (1.0 + 1.23456789e-10) - 1.0

Out[19]: 1.234568003383174e-10

In the next example the first and third line give a result that is correct to 1 significant digit.
For the first and third line the truncation due to finite precision leads to the loss of all significant digits.

In [20]: print((1.0 + 2e-16) - 1.0)


print((1.0 + 1e-16) - 1.0)
print((100.0 + 1e-14) - 100.0)
print((100.0 + 7e-15) - 100.0)

2.220446049250313e-16
0.0
1.4210854715202004e-14
0.0

The strange values that remain are a result of the numbers being stored in binary in the computer's memory then
converted back to decimal.

https://people.bath.ac.uk/nm268/progpy.bho/The+Basics.html 9/9

You might also like