.ipynbcan render images, tables, graphs, LateX equations
content is organized into cells
In [1]:
print("Hello world")
The last command's output is displayed
In [2]:
2 + 3
3 + 4
Out[2]:
This can be a tuple of multiple values
In [3]:
2 + 3, 3 + 4, "hello " + "world"
Out[3]:
In [4]:
%%time
for x in range(100000):
pass
In [5]:
%%timeit
x = 2
In [6]:
%%writefile hello.py
print("Hello world from BME")
For a complete list of magic commands:
In [7]:
%lsmagic
Out[7]:
Jupyter notebooks can be converted to slides and rendered with Reveal.js just like this course material.
This slideshow is a single Jupyter notebook which means:
jupyter-nbconvert --to slides 01_Python_introduction.ipynb --reveal-prefix=reveal.js --post serve
More on Jupyter slides:
Kernel -> Restart & Run AllKernel -> Restart & Run All before submitting homework to make sure that your notebook behaves as expected
In [8]:
print("this is run first")
In [9]:
print("this is run afterwords. Note the execution count on the left.")
In [10]:
42
Out[10]:
In [11]:
_
Out[11]:
Next-previous output:
In [12]:
"first"
Out[12]:
In [13]:
"second"
Out[13]:
In [14]:
__
Out[14]:
In [15]:
__
Out[15]:
Next-next previous output:
In [16]:
___
Out[16]:
N-th output can also be accessed as a variable _output_count. This is only defined if the N-th cell had an output.
Here is a way to list all defined outputs (you will understand the code in 3 week):
In [17]:
list(filter(lambda x: x.startswith('_') and x[1:].isdigit(), globals()))
Out[17]:
In [18]:
_i
Out[18]:
N-th input:
In [19]:
_i2
Out[19]:
In [20]:
import antigravity
In [21]:
n = 12
if n % 2 == 0:
print("n is even")
else:
print("n is odd")
In [22]:
n = 2
print(type(n))
n = 2.1
print(type(n))
n = "foo"
print(type(n))
In [23]:
i = 2
print(id(i))
i = 3
print(id(i))
i = "foo"
print(id(i))
s = i
print(id(s) == id(i))
s += "bar"
print(id(s) == id(i))
In [24]:
#n = int(input())
n = 12
if n < 0:
print("N is negative")
elif n > 0:
print("N is positive")
else:
print("N is neither positive nor negative")
In [25]:
n = -2
abs_n = n if n >= 0 else -n
abs_n
Out[25]:
In [26]:
l = [] # empty list
l.append(2)
l.append(2)
l.append("foo")
len(l), l
Out[26]:
In [27]:
l[1] = "bar"
l.extend([-1, True])
len(l), l
Out[27]:
In [28]:
for e in ["foo", "bar"]:
print(e)
In [29]:
for i in range(5):
print(i)
specifying the start of the range:
In [30]:
for i in range(2, 5):
print(i)
specifying the step. Note that in this case we need to specify all three positional arguments.
In [31]:
for i in range(0, 10, 2):
print(i)
In [32]:
i = 0
while i < 5:
print(i)
i += 1
There is no do...while loop in Python.
In [33]:
for i in range(10):
if i % 2 == 0:
continue
print(i)
In [34]:
for i in range(10):
if i > 4:
break
print(i)
In [35]:
def foo():
print("this is a function")
foo()
In [36]:
def foo(arg1, arg2, arg3):
print("arg1 ", arg1)
print("arg2 ", arg2)
print("arg3 ", arg3)
foo(1, 2, 3)
In [37]:
foo(1, arg3=2, arg2=29)
In [38]:
def foo(arg1, arg2, arg3=3):
print("arg1 ", arg1)
print("arg2 ", arg2)
print("arg3 ", arg3)
foo(1, 2)
Default arguments need not be specified when calling the function
In [39]:
foo(1, 2)
In [40]:
foo(arg1=1, arg3=33, arg2=222)
If more than one value has default arguments, either can be skipped:
In [41]:
def foo(arg1, arg2=2, arg3=3):
print("arg1 ", arg1)
print("arg2 ", arg2)
print("arg3 ", arg3)
foo(11, arg3=33)
This mechanism allows having a very large number of arguments. Many libraries have functions with dozens of arguments.
The popular data analysis library pandas has functions with dozens of arguments, for example:
pandas.read_csv(filepath_or_buffer, sep=', ', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression='infer', thousands=None, decimal=b'.', lineterminator=None, quotechar='"', quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=False, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, skip_footer=0, doublequote=True, delim_whitespace=False, as_recarray=False, compact_ints=False, use_unsigned=False, low_memory=True, buffer_lines=None, memory_map=False, float_precision=None)
In [42]:
def foo(n):
if n < 0:
return "negative"
if 0 <= n < 10:
return "positive", n
return
print(foo(-2))
print(foo(3))
print(foo(12))
In [43]:
import this