Topic 2: Basic arithmetic, operators, simple I/O
Arithmetic and operators
Once a numeric variable has been assigned then it is then possible to use that variable in various arithmetic and other operations. This is done via operators which act on one or more operands. Binary operators act on two operands and unary operators act on one operand. The standard arithmetic actions "add", "subtract", "multiply" and "divide" are represented by the characters +, -, ** * ** and / respectively. Arithmetic can actually be done as part of the assignment statement, a simple example of which is given below
Operator precedence and associativity
As expressions get more complicated, such as in the example above, the order in which the operators in the expression will be processed needs to be understood. This is known as operator precedence. Consider, for example, the variable assignment
Here there are 3 possibilities:
If + has precedence over ** * ** then
x_vector
will be initialised to a value of 48.If ** * ** has precedence over + then
x_vector
will be initialised to a value of 19.If both ** * ** and + have equal precedence then
x_vector
will be initialised to a value of 28.
In Python
the ** * ** and / operators have precedence over + and -.
Operators with equal precedence are evaluated according to their associativity. In general, operators with equal precedence will have left-right associativity which means that all the ** * ** and / operators in an assignment statement are treated reading the statement from left to right. This is also true for the + and - operators. However, in general, it is good practise to use parentheses in complicated arithmetic assignments, this avoids errors and makes the code much more readable for anyone who reads it.
Commonly used operators
The table below lists commonly used operators, some of which are binary (require 2 inputs), some of which are unary (require 1 input).
Operator | Meaning | Usage |
---|
|Addition of both operands |y=a+b
|Subtract 2nd operand from 1st |y = a-b
|Multiplication of both operands |y=ab / |Floating point division of 1st operand by 2nd |y=a/b // |Integer division of 1st operand by 2nd (returns an integer) |y=a//b % |Integer modulo (remainder) of 1st operand w.r.t. 2nd (returns an integer) |y = a%b |Raise the 1st operand to the power of the second 2nd |y = ab += |Assign left operand to left plus right operands |x+=y
same as
x=x+y -= | As above for subtraction | x-=y
same as
x=x-y *= |As above for multiplication | x*=y
same as
x=xy /= |As above for floating point division |x/=y
same as
x=x/y //= |As above for integer division |x//=y
same as
x=x//y %= |As above for modulus (remainder) |x%=y
same as
x=x%y
Note that in integer division the non-integer part of the result is thrown away (i.e. the number is always rounded down). The usage of the /, // and % operators is illustrated in the short example below
Data types
Python
supports a number of different variable types including integer, float (real number), (character) string as well as more advanced data types such as complex numbers and Boolean (variables which can take the value of True or False only) . Unlike many programming languages it is not necessary, when assigning a variable, to tell Python
what type of variable it is, indeed Python
decides this for itself and can even change the type of variable as the result of a particular operation. To find out what data type a particular variable is stored as then use the type
command.
Adding the type command to a similar example to that above demonstrates something interesting. Compare the output from the following two Python code snippets
This demonstrates that Python
is capable of changing the type of variable that div according to how it is used.
Up until now the examples have used simple, single variables. A very useful data type is the list which is a collection of comma separated variables enclosed in square brackets. Importantly lists can contain objects of different types. Lists are mutable (as opposed to immutable) which means that they can be dynamically modified, even extended and truncated, this will be discussed later in the course. The simple example below shows a list being defined and referenced.
A tuple is very similar to a list except that round brackets are used to define a tuple and that tuples are immutable.
The import
command
The next section considers some of the most commonly used mathematical functions which will be used to perform common operations such as trigonometry, etc. However, before doing that it is necessary to introduce the import
command.
When using a function such as sin
then what is happening is a pre-existing function that someone else has written is being used (in general this is a good thing since it saves us the trouble of having to write the function ourselves!). Functions are collected together in files known as modules or libraries which are collections of functions of a common theme. Mathematical functions or routines such as those discussed in the next section are grouped together in a library known as math
. In order to use functions from the math library it is necessary to include the command
at the start of the Python
program or script. Replacing math
in the command line above with another library name makes all of the routines in that particular library available to the Python
script. Subsequently using a function within the library requires a construction of the type
variable = library_name.function_name(variable)
and so the mathematical functions described in the following section would be called as follows
The math
module
A full description of all of the functions in the math
module (or library) is available at the mathematical functions page at python.org. A following is a list of the most commonly used functions that will be used in this course.
Name | Meaning | Usage |
---|---|---|
math.sqrt() | square root | y=math.sqrt(x) |
math.sin() | sine | y=math.sin(x) (x in radians) |
math.cos() | cosine | y=math.cos(x) (x in radians) |
math.tan() | tangent | y=math.tan(x) (x in radians) |
math.asin() | arcsine | y=math.asin(x) (y in radians) |
math.acos() | arccosine | y=math.acos(x) (y in radians) |
math.atan() | arctangent (tan-1(x)) | y=math.atan(x) (-π/2 < y < π/2) |
math.atan2() | arctangent (tan-1(x1/x2)) | y=math.atan2(x1,x2) (-π < y < π) |
math,fabs() | absolute value | y=math.fabs(x) |
math.pow() | xy | z = math.pow(x,y) |
math.exp() | ex | y=math.exp(x) |
The math
module also provides access to the variables π (math.pi) and e (math.e)
Simple input and output
Being able to communicate with a Python
script is essential. The process of interacting with a Python
script is known as input/output or I/O for short. This section presents very simple I/O, namely entering data from the keyboard and writing it to the computer screen. More sophisticated I/O such as reading data from and writing data to external files will be covered later in the course.
Output: the print
command
The Hello World!
example earlier was a very simple example of the print
command in use. This is a powerful and much used command. The print
command has the following general form:
print (some_string,value1,...)
What goes inside the print
command (known as the arguments to the command) can be a mixture of variable names and text, written inside single or double quotes, along with variable names. Strings of text and variable names must be separated using commas.
An example of how the print
statement can be used is given below
Note that Python
, conveniently, adds spaces around the variables and text strings without explicitly being told to do so to improve readability.
Input: the input
command
The input
command is used in order to read information in from the keyboard. The syntax of the input
command is
variable = eval(input('prompt'))
and is demonstrated in the following code fragment
Notes
in this case the trailing space in the prompt is included in the
input
command.without the use of the
eval
command thenc
would be of type string (see the comparison in the cell below)
If a variable of a particular type is to be input then it is good practise to explicitly state its type (a process known as explicit type casting), i.e
myInt=int(input('Enter an integer'))