=
. x = 42
instructor = 'Dr. Henderson'
pi = 3.14
yeti = False
list
class. x = [42]; y = x; x.append('Jackie Robinson')
print(y)
y.append('Mariano Rivera')
print(x)
is
. .copy()
method to copy its
values to a new location. print(x is y)
x = [42]
y = x.copy()
print(x is y)
x.append('Jackie Robinson')
print(y)
int
, float
, str
, bool
, None
, bytes
. x = 5e-1
print(float(x))
print(str(x))
print(bool(x))
print(bool(int(x)))
isinstance()
. x = 5e100
print(isinstance(x, float))
print(isinstance(x, int))
int
can hold arbitrarily large integers.float
type is a double-precision (64-bit) floating point number.+
, -
, *
, /
, //
, %
, **
. print(13 / 2) # thanks Python 3
print(13 // 2) # integer divsion
print(13 % 2) # mod
x = 2 ** 0.5
print(x ** 2 - 2)
bool
type holds logical values.True
and False
. bool
.bool
.eps1 = 1e-8
eps2 = 1e-16
z = (2 ** 0.5) ** 2 - 2
b1 = z < eps1
b2 = z > eps2
b1 and b2
print((eps1 > z) and (z > eps2))
eps2 < z < eps1
.format()
.x = 42; n = 100
phat = x / n
se = (phat * (1 - phat) / n) ** 0.5
lwr, upr = phat - 1.96 * se, phat + 1.96 * se
ci_str = "{0:.1f}% (95% CI: {1:.0f}-{2:.0f}%)"
pretty = ci_str.format(100 * phat, 100 * lwr, 100 * upr)
pretty
f
for a "glue" like syntax. from IPython.display import Markdown
Markdown(f'''
> Life is {pretty} towels.
>
> --Unknown.
''')
try:
5 + 'phi'
except:
print('Error')
float
and int
types play nicely.n = 5; phi = (1 + 5 ** 5e-1) / 2
print(isinstance(n, int))
print(isinstance(phi, float))
print(n * phi)
... unlike many other languages, e.g. R, C++, which use braces `{}`.
In Python, indentation is functional, not just good style.
... but also potentially harder to debug (in the beginning).
Avoid tabs, `\t`, but use the tab key when your editor is enabled to translate.
:
is used to denote the start of an indented block.k = 0
for i in range(10):
k += i
print(k)
()
after the function name. print(round(3.141592653589793))
print(round(3.141592653589793, ndigits = 1))
print(round(3.141592653589793, ndigits=2))
print(round(3.141592653589793, 3))
# error
# round(digits = 2, 3.141592653589793)
... are one of the most useful programming contructions.
... allow you to name and reuse blocks of code.
... help you to break complex problems into simpler parts.
... make your code more readable.
Rule of thumb: if you copy-and-paste the same code more than once, it's probably better to encapsulate that code into a function.
def
keyword to define a new function.def n_vowels(s):
n = 0
for v in ['a', 'e', 'i', 'o', 'u']:
n += s.count(v)
return(n)
def s(x, y = 0):
"""
Describe your function's purpose concisely.
Parameters
----------
x : TYPE
DESCRIPTION.
y : TYPE, optional
DESCRIPTION. The default is 0.
Returns
-------
None.
"""
Methods are functions that belong to objects and have access to associated data.
object.method()
.book
of class str
...title()
method.book = "the hitchhiker's guide to the galaxy"
print(book.title())
:
denoting
the start of an indented block.