You are a guest. Restricted access. Read more


In Python you have the following arithmetic operators:

Symbol Name
Floor division

Now, let's try to use Python as a calculator. We will calculate $3*8/6$:

print 3*8/6

Here are a few more examples:

a=10; b=3;
print a/b
print a*b
print a**b # power
print a%b  # find the reminder of the division

The rules of arithmetic precedence are the same as with calculators; Python evaluates expressions from left to right, but things enclosed in brackets are evaluated first:

a=10; b=3;
print a+(a+b)*3
print ((a+a)+b)*3

Elementary functions

You can also do some calculations using built-in elementary functions. For this we will need to import a module (i.e. peace of code) which contains such functions. For elementary functions, we will need to import the module math which has elementary functions. Let calculate $\sqrt{100}$:

import math
print math.sqrt(100)

Note we call “math.sqrt”, not simply “sqrt”.

Alternatively, you simply import all functions (in this case you do not need to type “math.” on front of each statement

from math import *
print sqrt(100)

Let us consider a logarithmic function:

from math import *
print log(100)

Exercise: Change 100 to some other number and check the output

The math module provides access to mathematical constants and functions.

import math
print math.pi            #Pi, 3.14...
print math.e             #Euler's number, 2.71...
print math.sin(2)        #Sine of 2 radians
print math.cos(0.5)      #Cosine of 0.5 radians
print math.tan(0.23)     #Tangent of 0.23 radians
print math.sqrt(49)      #Square root of 49 = 7

How do we know which functions can be used? There is a special command “dir()” which prints all implemented Python functions in the module “math”:

import math
print dir(math)

Run this commands and you will see familiar math functions of Python

Largest numbers

Let us find out max and value for integer numbers:

import sys
print sys.maxint, sys.minint
print dir(sys)


from  math import abs
print math.abs(-100)

Exercise: This code has as a mistake. Correct this code and calculate the absolute value of 100

python/arithmetic.txt · Last modified: 2015/05/10 17:18 (external edit)
Back to top
CC Attribution-Share Alike 3.0 Unported = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0