2 + 2
4
3 - 2
1
4 * 6
24
5/2
2.5
Exponents in Python use the double asterisk symbol **
not the carrot symbol ^
.
9**2
81
16**(1/2)
4.0
The order of arithmetic operations in Python is the same as the order of operations in mathematics. Parenthesis ( )
can be used to control the order of opperations.
3*(2+1)
9
3-1/(4+8)
2.9166666666666665
The modulus or remainder operator in Python is %
. The remainder after division of the first number by the second number is returned when %
is used.
5%2
1
3.04%1
0.040000000000000036
3.0%1
0.0
note: in Python the pound symbol #
is used to denote comments. Comments are lines of text that can be read by people but are not run as code.
sin(30)
-------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-13-d1dd6e003e86> in <module>() ----> 1 sin(30) NameError: name 'sin' is not defined
import math
math.sin(30) # sine of angle in radians (not degrees)
-0.9880316240928618
math.sin(6) # once the module is imported, it can be used in the rest of the notebook or .py file
-0.27941549819892586
from math import sin
sin(30)
-0.9880316240928618
from math import sin, cos
print(sin(30)) # only the output of the last line in a code cell is shown
cos(30)
-0.9880316240928618
0.15425144988758405
from math import log, e, log10
log(10) # natural logarithm
2.302585092994046
log(e)
1.0
log10(3*10**8) # base 10 log
8.477121254719663
Variables are defined in Python using the equals sign =
also called the assignment operator.
# Calculate the volumne of a sphere with radius 8.1
import math
r = 8.1
V = (4/3)*math.pi*r**3
print(V)
2226.094855221884