Tutorial:Jython/2 Arithmetics

From HandWiki


In Python you have the following arithmetic operators:

Symbol Name
+
Addition
-
Subtraction
*
Multiplication
/
Division
''
Floor division
%
Modulo
'''
Power

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

<jc python edit> print 3*8/6 </jc>

Here are a few more examples:

<jc lang="python"> a=10; b=3; print a/b print a*b print ab # power print a%b # find the reminder of the division </jc>

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:

<jc lang="python"> a=10; b=3; print a+(a+b)*3 print ((a+a)+b)*3 </jc>

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's calculate $\sqrt{100}$:

<jc lang="python"> import math print math.sqrt(100) </jc> 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

<jc lang="python"> from math import * print sqrt(100) </jc>

Let us consider a logarithmic function: <jc python edit> from math import * print log(100) </jc>

The math module provides access to mathematical constants and functions.

<jc lang="python"> 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 </jc>

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":

<jc lang="python"> import math print dir(math) </jc>

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

Largest numbers

Let us find out max and value for integer numbers: <jc lang="python"> import sys print sys.maxint, sys.minint print dir(sys) </jc>

Exercises:

<jc python edit> from math import abs print math.abs(-100) </jc>