Python supports most common maths operations. The table below lists maths operators supported.
| Syntax | Math | Operation Name |
|---|---|---|
a+b |
a+b | addition |
a-b |
a-b | subtraction |
| a*b | a * b | multiplication |
| a/b | a\div b | division (see note below) |
| a//b | a//b | floor division (e.g. 5//2=2) |
| a%b | a%b | modulo |
| -a | -a | negation |
| < | a < b | less- than |
| > | a > b | greater- than |
| <= | a <= b | less- than- equal |
| >= | a >= b | greater- than- equal |
| abs(a) | | a | |
absolute value |
| a**b | a**b | exponent |
| math.sqrt(a) | sqrt a | square root |
Note: In order to use
math.sqrt()function, you must explicitly load the math module by addingimport mathat the top of your file, where all the other modules import is defined.
In [8]:
# Sample Code
# Say Cheese
x = 34 - 23
y = "!!! Say"
z = 3.45
print(id(x), id(y), id(z))
In [9]:
print(x, y, z)
x = x + 1
y = y + " Cheese !!!"
print("x = " + str(x))
print(y, id(y))
print("Is x > z", x > z ,"and y is", y, "and x =", x)
print("x - z =", x - z)
In [15]:
print("~^" * 30)
print(30 * "~_")
print(id(x), id(y), id(z))
In [19]:
print((30 * "~_") * 2)
In [21]:
print(30 * "~_" * 2)
In [25]:
print(30 * "~_" * "#")
In [26]:
print(30 * "~_" + "#")
In [27]:
t = x > z
print("x = " + str(x) + " and z = " + str(z) + " : " + str(t))
print("x =", x, "and z =", z, ":", t)
print(x, z)
print("x % z =", x % z )
print("x >= z", x <= z)
In [28]:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 1.1 / 7
print("You weigh", mass_stone, "stone.")
Python uses the standard order of operations as taught in Algebra and Geometry classes. That, mathematical expressions are evaluated in the following order (memorized by many as PEMDAS or BODMAS {Brackets, Orders or pOwers, Division, Multiplication, Addition, Subtraction}) .
(Note that operations which share a table row are performed from left to right. That is, a division to the left of a multiplication, with no parentheses between them, is performed before the multiplication simply because it is to the left.)
| Name | Syntax | Description | PEMDAS Mnemonic |
|---|---|---|---|
| Parentheses | ( ... ) | Before operating on anything else, Python must evaluate all parentheticals starting at the innermost level. (This includes functions.) | Please |
| Exponents | ** | As an exponent is simply short multiplication or division, it should be evaluated before them. | Excuse |
| Multiplication and Division | * / // % | Again, multiplication is rapid addition and must, therefore, happen first. | My Dear |
| Addition and Subtraction | + - | They should happen independent to one another and finally operated among eachother | Aunt Sally |
In [1]:
print (round(3.14159265, 2))