- bool:
yes = True, no = False
- int:
year = 2001
- float:
g = 9.81, G = 6.67e-11
- str:
name = "Welcome to 'P53'"
- list:
vec = [ 1.23, -0.5, 2 ]
- tuple:
date = (1999, 12, 31)
1 + 1
= 2, -1 - 1
= -2
"hi" + "world"
= "hiworld"
2 * 3
= 6, 3 / -2
= -1.5
"hi" * 3
= "hihihi"
- power:
2 ** 3
= 8
- modulus:
7 % 3
= 1
- floor div:
7 // 3
= 2
- equality:
1 + 1 == 2
is True
- inequality:
1 + 1 != 2
is False
2 >= 1
is True
, 2 > 2
is False
2 <= 1
is False
, 2 < 3
is True
True and False
is False
True or False
is True
not True
is False
2 >= 1 or 2 > 2
is True
now = ['Apr',13,[9,15,'am']]
now[0]
is 'Apr'
now[1]
and now[-2]
are 13
now[2]
is [9,15,'am']
now[2][-1]
is 'am'
digits=[0,1,2,3,4,5,6,7,8,9]
digits[:4]
is [0,1,2,3]
digits[6:]
is [6,7,8,9]
digits[4:6]
is [4,5]
digits[2:8:2]
is [2,4,6]
len(digits[2:3])
is 1
[2*n+1 for n in range(5)]
[n-1 for n in range(5) if n%2==1]
- can be indexed and sliced like lists
- cannot be modifed after creation
tuple(1, 2, 3)
tuple([1, 2, 3])
(1, 2, 3)
1, 2, 3
(1,)
has length 1
(,)
has length 0
a = 1
b = 3
print(f'a={a}, b={b}, a/b={a/b:.2f}')
if ?:
pass
elif ?:
pass
else:
pass
for value in values:
pass
for i, value in enumerate(values):
pass
break
: break out of enclosing loop
continue
: jump to next iteration
- utility:
print,help
- numeric:
abs,min,max,pow,round
- types:
bool,int,float,str,list,tuple
- iterable:
len,enumerate,range
import math
math.sin(math.pi / 2)
is 1.0
def myfunc(x, y):
return x + y, x - y
assert myfunc(1, 2) == (3, -1)
def combine(x1, x2, c1=1, c2=1):
return c1 * x1 + c2 * x2
assert combine(2, 3) == 5
assert combine(2, 3, c1=0.5) == 4
assert combine(2, 3, c2=2) == 8
x = np.array([0.0,0.2,0.4,0.8,1.0])
x = np.linspace(0, 1, 5)
np.zeros((2, 3))
is 2x3 array of zeros
np.ones((3, 2, 3))
is 3x2x3 array of ones
x.shape
is tuple of dimensions
x.dtype
is type of each element value
x.size
is total number of elements
- trig:
sin,cos,tan,asin,acos,atan,atan2
- angles:
deg2rad,rad2deg
- constants:
pi,e,inf,nan
rng = np.random.default_rng(seed=123)
rng.uniform(lo, hi, size=(3, 2, 3))
rng.normal(loc=mu, scale=stddev, size=9)
import matplotlib.pyplot as plt
plt.plot(x, y, 'r-')
plt.hist(z, bins=50, range=(-5,5))
- colors: r(ed),g(reen),b(lue),(blac)k
- line styles:
- -- :
- symbols:
. o + x