\u001b[0;34m\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mx\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m-\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32massert\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"This value of x should be positive\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mAssertionError\u001b[0m: This value of x should be positive"
]
}
],
"source": [
"x = -1\n",
"assert (x > 0), \"This value of x should be positive\""
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Functions"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Python functions are defined using the `def` keyword. \n",
"> * the body of the function is indented (always use 4 spaces for one indentation level)\n",
"> * the returned value preceded by the `return` keyword; (functions can have multiple return statements)\n",
"> * arguments can be parsed as positional arguments (`args`), i.e. a list of comma seperated values: func(a, b, c)\n",
"> * arguments can be parsed as keyword arguments (`kwargs`), which have a default value if not explicitely parsed: func(spam=1, eggs=2)\n",
"> * when using args and kwargs, args must always come before kwargs: func(a, spam=1, eggs=2)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### parse positional arguments"
]
},
{
"cell_type": "code",
"execution_count": 419,
"metadata": {},
"outputs": [],
"source": [
"def add(x, y):\n",
" return x + y\n",
"\n",
"def inverse(x):\n",
" if x != 0:\n",
" return 1/x\n",
" else:\n",
" print('warning: cannot return the inverse of 0, returning None')\n",
" return None"
]
},
{
"cell_type": "code",
"execution_count": 420,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 420,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"add(2, 2)"
]
},
{
"cell_type": "code",
"execution_count": 421,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"0.5"
]
},
"execution_count": 421,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"inverse(2)"
]
},
{
"cell_type": "code",
"execution_count": 422,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"warning: cannot return the inverse of 0, returning None\n"
]
}
],
"source": [
"inverse(0)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### parse keyword arguments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Arguments can be parsed as keyword arguments, and default values can be set."
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"def greetings(language='english', name='Jake'):\n",
" if language == 'english':\n",
" print('Hello {}!'.format(name))\n",
" elif language == 'spanish':\n",
" print('Hola {}!'.format(name))\n",
" else:\n",
" print('I dont speak this language.')"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hola Emiliano!\n",
"Hola Jake!\n"
]
}
],
"source": [
"greetings(language='spanish', name='Emiliano')\n",
"greetings(language='spanish') # name not parsed => will take use default value defined in funtion"
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello Jake!\n"
]
}
],
"source": [
"d = dict(language='english')\n",
"greetings(**d) # unpack dictionary keys-values as keywarg arguments"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### set documentation"
]
},
{
"cell_type": "code",
"execution_count": 459,
"metadata": {},
"outputs": [],
"source": [
"def addone(a):\n",
" '''This function is used to add one to the parsed variable.'''\n",
" return a + 1"
]
},
{
"cell_type": "code",
"execution_count": 460,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"'This function is used to add one to the parsed variable.'"
]
},
"execution_count": 460,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"addone.__doc__"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### warning: calls by value or reference"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"**Call by `value`**: for primitive variables (ex: numbers), Python copies the content of the variable into the function. "
]
},
{
"cell_type": "code",
"execution_count": 442,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"def addone(a):\n",
" a = a + 1\n",
"\n",
"n = 3\n",
"addone(n) # => variable 'n' is copied to new variable 'a' inside the function => 'a' is changed 'n' is not\n",
"print(n) "
]
},
{
"cell_type": "code",
"execution_count": 443,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4\n"
]
}
],
"source": [
"# => to change 'n' we need to return the copied variable 'a' which was changed\n",
"def addone(a):\n",
" a = a + 1\n",
" return a\n",
"\n",
"n = 3\n",
"n = addone(n)\n",
"print(n)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"**Call by `reference`**: for complex variables (ex: lists), Python does not copy the variable inside the function, instead it references it. This mean that the parsed variable will suffer the changes, even though the variable is not returned from the function."
]
},
{
"cell_type": "code",
"execution_count": 445,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[1, -10, 3, 4]\n"
]
}
],
"source": [
"mylist = [1, 2, 3, 4]\n",
"\n",
"def func(a):\n",
" a[1] = -10\n",
"\n",
"func(mylist)\n",
"print(mylist) # => the array is modified even though the list was not returned from the function!"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Intermediate Exercises"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" 1. Write a function that takes two values and returns the larger one, and document it\n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"\n",
" 2. Write a function that takes a list of numbers as an argument and returns the mean\n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"\n",
" 3. Write a function that computes the inverse of two values, and prints a warning message when the denominator is 0\n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"\n",
" 4. Build a for loop which iterates through numbers ranging from 0 to 20, and as it iterates it creates a list containing the squared value of the iterated value. Exist the loop when the iterator exceeds 10.\n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"\n",
" 5. Create a dictionnary a with various volcanoes as keys, and their altitude as values. Print the altitude of your favourite volcanoe from the dictionary.\n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
""
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Classes, Methods, Attributes"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Python, everything is an `object`, even functions and attributes. \n",
"`OOP` = Object Oriented Programing"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"* `Classes` are defined with the `class` keyword. \n",
" ‐ class names are usually Capitalized and use CamelCase \n",
" ‐ classes are instantiated with () \n",
" ‐ class attributes are fined in __init__ (not compulsory, but considered good practice) \n",
"* `Methods` are functions inside classes, and are defined with the `def` keyword \n",
" ‐ function names are usually lower case \n",
"* `Attributes` are set like that instance.attribute = value, and are also accessed via instance.attribute"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"class Volcano():\n",
" \n",
" def __init__(self, name):\n",
" self.name = name\n",
" self.type = 'mountain' # public attribute\n",
" self.__imminentexplosion = False # private attribute (starts with double underscore)\n",
" \n",
" def print_name(self):\n",
" print('The volcano name is', self.name)\n",
" \n",
" def set_altitude(self, altitude):\n",
" self.altitude = altitude"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"outputs": [],
"source": [
"# - instantiate class\n",
"volc = Volcano('colima')"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"'mountain'"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# - get class attribute (public):\n",
"volc.type "
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"# - private class attribute unaccesible\n",
"# volc.__imminentexplosion # command returns 'AttributeError'"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"The volcano name is colima\n"
]
}
],
"source": [
"# - call class method:\n",
"volc.print_name() "
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3820\n"
]
}
],
"source": [
"# - set attribute through class method:\n",
"volc.set_altitude(3820)\n",
"print(volc.altitude)"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"{'name': 'colima',\n",
" 'type': 'mountain',\n",
" '_Volcano__imminentexplosion': False,\n",
" 'altitude': 3820}"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# - get class attributes (public + private) as dictionary\n",
"volc.__dict__"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n"
]
},
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# - check class instance\n",
"print(type(volc))\n",
"isinstance(volc, Volcano)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### inheritence"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A class can `inherit` methods and attributes from a parent class.\n",
"> `super().method()` let's you call an instances parent's method from an instance method"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"class ExplosiveVolcano(Volcano):\n",
" def __init__(self, name):\n",
" super().__init__(name)\n",
" \n",
" def set_expected_VEI(self, VEI):\n",
" '''Volcanic Explosivity Index (VEI) is a relative measure of the explosiveness of volcanic eruptions.'''\n",
" self.expected_VEI = VEI"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"# - instantiate class which inherited from class Volcano\n",
"popo = ExplosiveVolcano('Popocatépetl') # needs to parse arguments for parent class Volcano"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"popo.set_expected_VEI(5)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5\n"
]
}
],
"source": [
"print(popo.expected_VEI)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"A class can inherit from multiple classes:"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"class Mountain():\n",
" def __init__(self):\n",
" self.category = 'geology'"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [],
"source": [
"class SuperVolcano(ExplosiveVolcano, Mountain):\n",
" # Note: because ExplosiveVolcano already inherits from Volcano, should not inherit both\n",
" \n",
" def __init__(self, name):\n",
" super().__init__(name)\n",
" self.info = 'stay away'\n",
" \n",
" def breathe(self):\n",
" print(\"breathing\")"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"yellowstone = SuperVolcano('Yellow Stone')"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"stay away\n"
]
}
],
"source": [
"print(yellowstone.info)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### add build-in instances"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Example: `__str__` and `__repr__` instances"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
">* instance description ugly by default: <__main__.ExplosiveVolcano at 0x7fb66dca6160>\n",
">* \\_\\_str\\_\\_() is supposed to give a nice string representation of the class, but uses \\_\\_repr\\_\\_() as a fallback"
]
},
{
"cell_type": "code",
"execution_count": 514,
"metadata": {},
"outputs": [],
"source": [
"class ExplosiveVolcano(Volcano):\n",
" def __init__(self, name):\n",
" super().__init__(name)\n",
" \n",
" def set_expected_VEI(self, VEI):\n",
" '''Volcanic Explosivity Index (VEI) is a relative measure of the explosiveness of volcanic eruptions.'''\n",
" self.expected_VEI = VEI\n",
" \n",
" def __repr__(self):\n",
" return '< Volcano: name=' + self.name + '>'"
]
},
{
"cell_type": "code",
"execution_count": 516,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"popo = ExplosiveVolcano('Popocatépetl') # needs to parse arguments for parent class Volcano"
]
},
{
"cell_type": "code",
"execution_count": 519,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"< Volcano: name=Popocatépetl>\n"
]
}
],
"source": [
"print(popo)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Modules and packages"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* a `module` is python file, which can be imported if in your `PYTHONPATH`\n",
"* a `package` is a collection of python modules, in practice as a directory containing python modules and a `__init__.py` file. \n",
"Packages can be imported as a whole, or only modules of it can be imported."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### import"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Import the `numpy` package:"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"import numpy"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 42,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"numpy.add(2,3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Import the `numpy` package using a shorter name (recommended):"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.add(2,3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Import a specific function from numpy:"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [],
"source": [
"from numpy import add"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"add(2,3)"
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [],
"source": [
"from numpy import add as npadd"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"npadd(2,3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Import everything from the package in your current workspace using `*` (not recommended):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from numpy import * # not recommended"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"Check where the module is located:"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
""
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.add"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Check version of a module:"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'1.19.2'"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"np.__version__"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Check out package architecture (using Linux's `tree` command):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!tree /home/khola/anaconda3/lib/python3.8/site-packages/numpy/"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Check out module content (using Linux's `cat` command):"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!cat /home/khola/anaconda3/lib/python3.8/site-packages/numpy/__init__.py"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### install third-party packages"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Third-party packages are usually installed using `package managers`:\n",
"- `pip` => Python Packaging Authority’s recommended tool for installing packages from the Python Package Index ([PyPI](https://pypi.org/))\n",
"```console\n",
"$ pip install \n",
"```\n",
"- `conda` => Anaconda's package manager for installing packages from the [Anaconda repository](https://repo.anaconda.com/) and [Anaconda cloud](https://anaconda.org/):\n",
"```console\n",
"$ conda install \n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Note: there are some differences between the `pip` and `conda`, see [here](https://www.anaconda.com/blog/understanding-conda-and-pip) for details.
\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"### create packages"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"You can create your own packages and modules to reuse your code in an organized manner."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"#### create directory and python module"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"1. **Create directory for python package:**"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [],
"source": [
"!mkdir /home/khola/Documents/CODE/python/volcano/"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"2. **Create empty `__init__.py` file to tell python the directory is a package:**"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [],
"source": [
"!touch /home/khola/Documents/CODE/python/volcano/__init__.py"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"3. **Create python script:**"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Overwriting /home/khola/Documents/CODE/python/volcano/mymodule.py\n"
]
}
],
"source": [
"%%writefile /home/khola/Documents/CODE/python/volcano/mymodule.py \n",
"\n",
"import numpy\n",
"\n",
"myvariable1 = 1\n",
"myvariable2 = 2\n",
"\n",
"def add(x,y):\n",
" return x+y"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"4. **Check result:**"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {
"collapsed": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[01;34m/home/khola/Documents/CODE/python/\u001b[00m\r\n",
"|-- __init__.py\r\n",
"|-- \u001b[01;34mcmapme\u001b[00m\r\n",
"| |-- __init__.py\r\n",
"| |-- __init__.pyc\r\n",
"| |-- \u001b[01;34m__pycache__\u001b[00m\r\n",
"| | `-- __init__.cpython-38.pyc\r\n",
"| |-- cmaps.py\r\n",
"| `-- cmaps.pyc\r\n",
"|-- notabene.md\r\n",
"|-- \u001b[01;34msegmentation\u001b[00m\r\n",
"| |-- __init__.py\r\n",
"| |-- __init__.pyc\r\n",
"| |-- \u001b[01;34m__pycache__\u001b[00m\r\n",
"| | |-- __init__.cpython-35.pyc\r\n",
"| | |-- __init__.cpython-36.pyc\r\n",
"| | |-- scribble.cpython-35.pyc\r\n",
"| | |-- scribble_seb.cpython-36.pyc\r\n",
"| | `-- stat.cpython-35.pyc\r\n",
"| |-- \u001b[01;34mbuild\u001b[00m\r\n",
"| | |-- \u001b[01;34mtemp.linux-x86_64-2.7\u001b[00m\r\n",
"| | | `-- geoseg.o\r\n",
"| | |-- \u001b[01;34mtemp.linux-x86_64-3.5\u001b[00m\r\n",
"| | | `-- geoseg.o\r\n",
"| | `-- \u001b[01;34mtemp.linux-x86_64-3.7\u001b[00m\r\n",
"| | `-- geoseg.o\r\n",
"| |-- \u001b[01;32mcl_build.sh\u001b[00m\r\n",
"| |-- geoseg.cpp\r\n",
"| |-- \u001b[01;32mgeoseg.cpython-35m-x86_64-linux-gnu.so\u001b[00m\r\n",
"| |-- geoseg.pyx\r\n",
"| |-- \u001b[01;32mgeoseg.so\u001b[00m\r\n",
"| |-- \u001b[01;34minclude\u001b[00m\r\n",
"| | `-- NDArray.h\r\n",
"| |-- notabene.md\r\n",
"| |-- scribble.py\r\n",
"| |-- scribble.pyc\r\n",
"| |-- scribble_old.py\r\n",
"| |-- scribble_seb.py\r\n",
"| |-- scribble_seb_v0.py\r\n",
"| |-- scribble_seb_v1.py\r\n",
"| |-- scribble_seb_v2.py\r\n",
"| |-- setup.py\r\n",
"| |-- \u001b[01;34msrc\u001b[00m\r\n",
"| | `-- geoseg_lib.h\r\n",
"| |-- stat.py\r\n",
"| `-- stat.pyc\r\n",
"`-- \u001b[01;34mvolcano\u001b[00m\r\n",
" |-- __init__.py\r\n",
" |-- \u001b[01;34m__pycache__\u001b[00m\r\n",
" | |-- __init__.cpython-38.pyc\r\n",
" | `-- mymodule.cpython-38.pyc\r\n",
" `-- mymodule.py\r\n",
"\r\n",
"12 directories, 39 files\r\n"
]
}
],
"source": [
"!tree /home/khola/Documents/CODE/python/"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"#### add path to .bashrc (on Linux)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You should add the following line to your `.bashrc` file (in Linux):\n",
"```console\n",
"export PYTHONPATH=/path/to/your/python/dir\n",
"#export PYTHONPATH=/home/khola/Documents/CODE/python\n",
"```"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"The cell below adds the line 'export PYTHONPATH=/home/khola/Documents/CODE/python' to the end of your .bashrc file. "
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [],
"source": [
"#!echo 'export PYTHONPATH=/home/khola/Documents/CODE/python' >> ~/.bashrc"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Check results:"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"else\r\n",
" if [ -f \"/home/khola/anaconda3/etc/profile.d/conda.sh\" ]; then\r\n",
" . \"/home/khola/anaconda3/etc/profile.d/conda.sh\"\r\n",
" else\r\n",
" export PATH=\"/home/khola/anaconda3/bin:$PATH\"\r\n",
" fi\r\n",
"fi\r\n",
"unset __conda_setup\r\n",
"# <<< conda initialize <<<\r\n",
"\r\n"
]
}
],
"source": [
"!tail /home/khola/.bashrc # replace with your path"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"Source your file (or restart your computer):"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [],
"source": [
"# !source ~/.bashrc"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"#### import your module"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [],
"source": [
"from volcano import mymodule"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n"
]
}
],
"source": [
"print(mymodule.myvariable1)"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mymodule.add(2,3)"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"### make packages installable"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "skip"
}
},
"source": [
"TODO"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "slide"
}
},
"source": [
"## Functional Programming"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"source": [
"Python supports functional programming with `list/dict/set comprehensions`, `map`, `reduce`, etc."
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"source": [
"> Functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data ([wikipedia](https://en.wikipedia.org/wiki/Functional_programming))"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### list/dict comprehension"
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {
"slideshow": {
"slide_type": "-"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[0, 2, 4, 6, 8]\n",
"[4]\n",
"[0, 1, 4, 3, 4]\n"
]
}
],
"source": [
"# - list comprehension\n",
"squares = [x*2 for x in range(5)] # list comprehension\n",
"print(squares)\n",
"\n",
"squares = [x**2 for x in range(5) if x == 2] # list comprehension with if condition\n",
"print(squares)\n",
"\n",
"squares = [x**2 if x == 2 else x*1 for x in range(5)] # list comprehension with if-else condition\n",
"print(squares)"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"{0: '0', 1: '1', 2: '4', 3: '9', 4: '16'}"
]
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# - dictionary comprehension\n",
"squares_d = {x: str(x ** 2) for x in range(5)}\n",
"squares_d"
]
},
{
"cell_type": "markdown",
"metadata": {
"slideshow": {
"slide_type": "subslide"
}
},
"source": [
"### map"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`map` maps a function to an iterable:"
]
},
{
"cell_type": "code",
"execution_count": 104,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[range(0, 0), range(0, 1), range(0, 2), range(0, 3), range(0, 4)]"
]
},
"execution_count": 104,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list_of_iteratables = [range(x) for x in range(5)]\n",
"list_of_iteratables"
]
},
{
"cell_type": "code",
"execution_count": 105,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"[0, 1, 2, 3]"
]
},
"execution_count": 105,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list(range(0, 4))"
]
},
{
"cell_type": "code",
"execution_count": 106,
"metadata": {
"slideshow": {
"slide_type": "fragment"
}
},
"outputs": [
{
"data": {
"text/plain": [
"