logo

Math operations

Python has support for both mathematical operations and functions.

Mathematical operations
An overview of operations:



Operation Result
x + y sum of x and y.
x * y multiplication of x and y.
x - y difference of x and y.
x / y division of x by y.
x % y remainder of x/y
x ** y x to the power of y
abs(x) absolute value of x
sqrt(x) square root of x

Mathematical functions
Python supports a wide variety of mathematical functions.



Function Returns Example
abs(x) Returns the absolute value of x. {% codeblock lang:python line_number:false %} x = -35 x = abs(x) print(x) {% endcodeblock %}
cmp(x,y) Returns -1 if x < y
Returns 0 if x equals to y
Returns 1 if x > y.
{% codeblock lang:python line_number:false %} x = 6 y = 4 print( cmp(x,y) ) {% endcodeblock %}
exp(x) Returns the exponential of x {% codeblock lang:python line_number:false %} import math x = 6 print( math.exp(x) ) {% endcodeblock %}
log(x) The natural logarithm of x {% codeblock lang:python line_number:false %} import math x = 6 print( math.log(x) ) {% endcodeblock %}
log10(x) The base-10 logarithm of x {% codeblock lang:python line_number:false %} import math x = 6 print( math.log10(x) ) {% endcodeblock %}
pow(x,y) The result of x**y {% codeblock lang:python line_number:false %} import math x = 6 print( math.pow(x,2) ) {% endcodeblock %}
sqrt(x) The square root of x {% codeblock lang:python line_number:false %} import math x = 6 print( math.sqrt(x) ) {% endcodeblock %}

Tip
You can use the Python interpreter as calculator. To do so you simply start Python without an IDE and filename. Example:


Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> 18*17
306
>>> 2**4
16
>>>


BackNext

Leave a Reply

Login disabled