{ "cells": [ { "cell_type": "code", "execution_count": 3, "metadata": { "init_cell": true, "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "skip" }, "tags": [ "hide-input" ] }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "%%html\n", "\n", "\n", "" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "hide-input" ] }, "outputs": [], "source": [ "# Install the necessary dependencies\n", "\n", "import os\n", "import sys\n", "!{sys.executable} -m pip install --quiet pandas scikit-learn numpy matplotlib jupyterlab_myst ipython" ] }, { "cell_type": "markdown", "metadata": { "tags": [ "remove-cell" ] }, "source": [ "---\n", "license:\n", " code: MIT\n", " content: CC-BY-4.0\n", "github: https://github.com/ocademy-ai/machine-learning\n", "venue: By Ocademy\n", "open_access: true\n", "bibliography:\n", " - https://raw.githubusercontent.com/ocademy-ai/machine-learning/main/open-machine-learning-jupyter-book/references.bib\n", "---" ] }, { "cell_type": "markdown", "metadata": { "notebookRunGroups": { "groupValue": "" }, "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "slide" } }, "source": [ "# Python programming advanced" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Table of Content\n", "\n", "- Control flow\n", " - ```if```, ```for```, `range`, ```while```, ```break```, ```continue```\n", "- Functions\n", " - Default argument values, keyword arguments, arbitrary argument lists, unpacking argument lists\n", " - Lambda expressions, documentation strings, function annotations, function decorators\n", "- Classes\n", " - Class, object, method, inheritance, multiple inheritance\n", "- Modules\n", " - ```import```, Packages\n", "- Errors and exceptions" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Control flow\n", "### The ```if``` statement\n", "\n", "- Used for conditional execution\n", "- If a condition is true, we run a block of statements\n", "- There can be zero or more `elif` parts\n", "- The `else` part is optional\n", "- An `if … elif … elif …` sequence is a substitute for the switch or case statements found in other languages" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Number bigger than or equal to one\n" ] } ], "source": [ "number = 15\n", "if number < 0:\n", " print('Number is less than zero')\n", "elif number == 0:\n", " print('Number equals to zero')\n", "elif number < 1:\n", " print('Number is greater than zero but less than one')\n", "else:\n", " print('Number bigger than or equal to one')" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Control flow\n", "### The ```for``` statement\n", "\n", "- Sequence: an ordered collection of items\n", "- A looping statement which iterates over a sequence of objects, i.e. go through each item in a sequence\n", "- An ```else``` clause is optional, when included, it is always executed once after the for loop is over unless a break statement is encountered." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "6\n", "1\n", "12\n" ] } ], "source": [ "words = ['cat', 'window', 'a', 'defenestrate']\n", "\n", "for word in words:\n", " print(len(word))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "6\n" ] } ], "source": [ "words = ['cat', 'window', 'a', 'defenestrate']\n", "\n", "for word in words:\n", " if len(word) == 1:\n", " break\n", " print(len(word))\n", "else:\n", " print('All words are printed!')" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Control flow\n", "### The ```for``` statement\n", "\n", "The `for` statement can be used in tandem with:\n", "- `range()`: to iterate over a sequence of numbers" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4]\n" ] } ], "source": [ "iterated_numbers = []\n", "\n", "for number in range(5):\n", " iterated_numbers.append(number)\n", "\n", "print(iterated_numbers)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Control flow\n", "### The ```for``` statement\n", "\n", "The `for` statement can be used in tandem with:\n", "- `enumerate()`: to get a counter and the value from the iterable at the same time" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 Mary\n", "1 goes\n", "2 to\n", "3 school\n" ] } ], "source": [ "words = ['Mary', 'goes', 'to', 'school']\n", "\n", "for word_index, word in enumerate(words):\n", " print(str(word_index) + ' ' + word)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Control flow\n", "### The ```for``` statement\n", "\n", "The `for` statement can be used in tandem with:\n", "- `items()`: to loop through dictionaries\n", "- the key and corresponding value can be retrieved at the same time" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Ming', 'Hong']\n", "['Shanghai University', 'Peking University']\n" ] } ], "source": [ "student_admission = {'Ming': 'Shanghai University', 'Hong': 'Peking University'}\n", "names = []\n", "universities = []\n", "\n", "for key, value in student_admission.items():\n", " names.append(key)\n", " universities.append(value)\n", "\n", "print(names)\n", "print(universities)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Control flow\n", "### The ```while``` statement\n", "\n", "- Repeatedly executes a block of statements as long as a condition is true\n", "- `True` and `False`\n", "- Any non-zero integer value is true; zero is false" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "number = 2\n", "power = 5\n", "result = 1\n", "\n", "while power > 0: # or, while power:\n", " result *= number\n", " power -= 1\n", "\n", "# 2^5 = 32\n", "assert result == 32" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Control flow\n", "### The ```break``` statement\n", "\n", "- Breaks out of the innermost enclosing \"for\" or \"while\" loop\n" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "number_to_be_found = 42\n", "\n", "# This variable will record how many time we've entered the \"for\" loop.\n", "number_of_iterations = 0\n", "\n", "for number in range(100):\n", " if number == number_to_be_found:\n", " # Break here and don't continue the loop.\n", " break\n", " else:\n", " number_of_iterations += 1\n", "\n", "assert number_of_iterations == 42" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Control flow\n", "### The ```continue``` statement\n", "\n", "- Continues with the next iteration of the loop" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 2, 4, 6, 8]\n" ] } ], "source": [ "even_numbers = []\n", "\n", "for number in range(0, 10):\n", " if number % 2 == 0:\n", " even_numbers.append(number)\n", " continue\n", "\n", "print(even_numbers)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Functions\n", "\n", "- A function is a group of statements that exist within a program for the purpose of performing a specific task\n", "- Since the beginning of the session, we have been using a number of Python’s built-in functions, including:\n", " - `len()`\n", " - `range()`\n", " - `print()`\n", "- The keyword `def` introduces a function definition, which is followed by the function name and the parenthesized list of formal parameters" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Functions\n", "\n", "### Defining a function" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [ "def myfunction():\n", " print (\"Printed from inside a function\")" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "fragment" } }, "source": [ "### Calling the function" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Printed from inside a function\n" ] } ], "source": [ "myfunction()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, John\n" ] } ], "source": [ "# Defining a function\n", "def greet(name):\n", " return 'Hello, ' + name\n", "\n", "# Calling the function\n", "print(greet('John'))" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, John\n" ] } ], "source": [ "# Defining a function\n", "def greet(name):\n", " return 'Hello, ' + name\n", "\n", "# Assign functions to variables\n", "greet_someone = greet\n", "\n", "# Calling the function\n", "print(greet_someone('John'))" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, John\n" ] } ], "source": [ "# Define functions inside other functions\n", "\n", "def greet_again(name):\n", " def get_message():\n", " return 'Hello, '\n", "\n", " result = get_message() + name\n", " return result\n", "\n", "print(greet_again('John'))" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, John\n" ] } ], "source": [ "# Functions can be passed as parameters to other functions\n", "\n", "def greet_one_more(name):\n", " return 'Hello, ' + name\n", "\n", "def call_func(func):\n", " other_name = 'John'\n", " return func(other_name)\n", "\n", "print(call_func(greet_one_more))" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Functions\n", "### Scopes of variables inside functions\n", "\n", "- Local variable:\n", " - Variables that are defined inside a function are considered “local” to that function\n", " - Objects outside the “scope” of the function will not be able to access that variable\n", " - Different functions can have their own local variables that use the same variable name\n", " - These local variables will not overwrite one another since they exist in different “scopes”\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Shanghai has 1000 bugs\n" ] } ], "source": [ "def count_bugs():\n", " numbugs = 1000\n", " print (\"Shanghai has\", numbugs, \"bugs\")\n", "\n", "count_bugs()" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Functions\n", "### Scopes of variables inside functions\n", "\n", "- Global Variables:\n", " - When a variable is created outside all of your functions it is considered a “global variable”\n", " - Global variables can be accessed by any statement in your program file, including by statements in any function\n", " - If you want to be able to change a global variable inside a function you must first tell Python that you wish to do this using the “global” keyword inside your function\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Before calling the function: Mary\n", "Function 1: Mary\n", "Function 2: John\n", "After calling the function: John\n" ] } ], "source": [ "name = 'Mary'\n", "\n", "def show_name():\n", " global name\n", " print(\"Function 1:\", name)\n", " name = 'John'\n", " print(\"Function 2:\", name)\n", "\n", "print(\"Before calling the function:\", name)\n", "show_name()\n", "print(\"After calling the function:\", name)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "25\n" ] } ], "source": [ "# Passing Arguments to a function\n", "\n", "def square(num):\n", " print(num ** 2)\n", "\n", "square(5)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5.0\n" ] } ], "source": [ "# Passing Multiple Arguments to a function\n", "\n", "def average(num1, num2, num3):\n", " sum = num1 + num2 + num3\n", " avg = sum / 3\n", " print(avg)\n", "\n", "average(2, 4, 9)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "10\n" ] } ], "source": [ "# A function can return multiple values\n", "\n", "def myfunction():\n", " x = 5\n", " y = 10\n", " return x, y\n", "\n", "p, q = myfunction()\n", "\n", "print(p)\n", "print(q)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9\n", "16\n", "16\n" ] } ], "source": [ "# Default argument values\n", "\n", "def power_of(number, power=2):\n", " \"\"\" Raises number to specific power.\n", " You may notice that by default the function raises number to the power of two.\n", " \"\"\"\n", " return number ** power\n", "\n", "print(power_of(3))\n", "print(power_of(2, 4))\n", "print(power_of(2, power=4))" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "James John 22\n" ] } ], "source": [ "# Keyword arguments\n", "\n", "def my_function(first_name, last_name, age):\n", " print(first_name, last_name, age)\n", "\n", "my_function(age=22, last_name=\"John\", first_name=\"James\")" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n", "12\n", "40\n" ] } ], "source": [ "# Arbitrary argument lists\n", "\n", "def product(*numbers):\n", " total = 1\n", " for n in numbers:\n", " total *= n\n", " return total\n", "\n", "print(product(2, 4))\n", "print(product(3, 4))\n", "print(product(4, 5, 2))" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n", "12\n", "120\n" ] } ], "source": [ "# Arbitrary argument lists with keyword arguments\n", "\n", "def product(*numbers, initial=1):\n", " total = initial\n", " for n in numbers:\n", " total *= n\n", " return total\n", "\n", "print(product(2, 4))\n", "print(product(3, 4, initial=1))\n", "print(product(4, 5, 2, initial=3))" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Unpacking argument lists (`*` and `**` statements)\n", "\n", "```py\n", "def fun(a, b, c, d):\n", " print(a, b, c, d)\n", "\n", "my_list = [1, 2, 3, 4]\n", "\n", "# This doesn't work\n", "fun(my_list)\n", "```\n", "\n", "### Code output:\n", "**TypeError**: `fun()` takes exactly 4 arguments (1 given)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Unpacking argument lists (`*` and `**` statements)\n", "\n", "- `*args` (Non-keyword arguments)\n", "- `**kwargs` (Keyword arguments)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3 4\n" ] } ], "source": [ "# Unpacking argument lists (`*` and `**` statements)\n", "\n", "def print_four_numbers(a, b, c, d):\n", " print(a, b, c, d)\n", "\n", "my_list = [1, 2, 3, 4]\n", "\n", "# Unpacking list into four arguments\n", "print_four_numbers(*my_list)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" }, "tags": [ "raises-exception" ] }, "outputs": [ { "ename": "TypeError", "evalue": "print_four_numbers() takes 4 positional arguments but 5 were given", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_30912\\2198447506.py\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[1;31m# Unpacking list into four arguments\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 9\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 10\u001b[1;33m \u001b[0mprint_four_numbers\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mmy_list\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: print_four_numbers() takes 4 positional arguments but 5 were given" ] } ], "source": [ "# Unpacking argument lists (`*` and `**` statements)\n", "\n", "def print_four_numbers(a, b, c, d):\n", " print(a, b, c, d)\n", "\n", "my_list = [1, 2, 3, 4, 5]\n", "\n", "# Unpacking list into four arguments\n", "\n", "print_four_numbers(*my_list)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n", "Welcome\n", "to\n", "Open\n", "Academy\n", "Machine\n", "Learning\n" ] } ], "source": [ "def fun(*args):\n", " for arg in args:\n", " print(arg)\n", "\n", "fun('Hello', 'Welcome', 'to', 'Open', 'Academy', 'Machine', 'Learning')" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 4 10\n" ] } ], "source": [ "# Unpacking argument lists (`*` and `**` statements)\n", "\n", "def fun(a, b, c):\n", " print(a, b, c)\n", "\n", "d = {'a' : 2, 'b' : 4, 'c' : 10}\n", "fun(**d)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, World!\n", "Hello, World!\n" ] } ], "source": [ "# Unpacking argument lists (`*` and `**` statements)\n", "\n", "def fun(first_word, second_word):\n", " return first_word + ', ' + second_word + '!'\n", "\n", "dict_1 = {'first_word': 'Hello', 'second_word': 'World'}\n", "print(fun(**dict_1))\n", "\n", "dict_2 = {'second_word': 'World', 'first_word': 'Hello'}\n", "print(fun(**dict_2))" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "15\n" ] } ], "source": [ "# Lambda expressions\n", "\n", "x = lambda a : a + 10\n", "print(x(5))" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "30\n" ] } ], "source": [ "# Lambda expressions\n", "\n", "x = lambda a, b : a * b\n", "print(x(5, 6))" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]\n" ] } ], "source": [ "# Lambda expressions\n", "\n", "pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]\n", "pairs.sort(key=lambda pair: pair[1])\n", "\n", "print(pairs)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[5, 7, 97, 77, 23, 73, 61]\n" ] } ], "source": [ "# Using lambda() Function with filter()\n", "\n", "# Example 1: Filter out all odd numbers using filter() and lambda function\n", "\n", "li = [5, 7, 22, 97, 54, 62, 77, 23, 73, 61]\n", "final_list = list(filter(lambda x: (x % 2 != 0), li))\n", "print(final_list)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[90, 59, 21, 60]\n" ] } ], "source": [ "# Using lambda() Function with filter()\n", "\n", "# Example 1: Example 2: Filter all people having age more than 18, using lambda and filter() function\n", "\n", "ages = [13, 90, 17, 59, 21, 60, 5]\n", "adults = list(filter(lambda age: age > 18, ages))\n", "print(adults)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[10, 14, 44, 194, 108]\n" ] } ], "source": [ "# Using lambda() Function with map()\n", "# Example 1: Multiply all elements of a list by 2 using lambda and map() function\n", "\n", "li = [5, 7, 22, 97, 54]\n", "final_list = list(map(lambda x: x * 2, li))\n", "print(final_list)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['DOG', 'CAT', 'PARROT', 'RABBIT']\n" ] } ], "source": [ "# Using lambda() Function with map()\n", "# Example 2: Transform all elements of a list to upper case using lambda and map() function\n", "\n", "animals = ['dog', 'cat', 'parrot', 'rabbit']\n", "uppered_animals = list(map(lambda animal: animal.upper(), animals))\n", "print(uppered_animals)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Functions\n", "\n", "### Documentation strings (docstring)\n", "\n", "> “Code is more often read than written.”\n", ">\n", "> — Guido van Rossum\n", "\n", "- A docstring is a string literal that occurs as the first statement in a module, function, class, or method definition.\n", "- Such a docstring becomes the `__doc__` special attribute of that object." ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Takes in a number n, returns the square of n\n" ] } ], "source": [ "# Documentation strings\n", "\n", "def square(n):\n", " '''Takes in a number n, returns the square of n'''\n", " return n**2\n", "\n", "print(square.__doc__)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n", "\n", "Prints the values to a stream, or to sys.stdout by default.\n", "Optional keyword arguments:\n", "file: a file-like object (stream); defaults to the current sys.stdout.\n", "sep: string inserted between values, default a space.\n", "end: string appended after the last value, default a newline.\n", "flush: whether to forcibly flush the stream.\n" ] } ], "source": [ "# Documentation strings\n", "\n", "print(print.__doc__)" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Create portable serialized representations of Python objects.\n", "\n", "See module copyreg for a mechanism for registering custom picklers.\n", "See module pickletools source for extensive comments.\n", "\n", "Classes:\n", "\n", " Pickler\n", " Unpickler\n", "\n", "Functions:\n", "\n", " dump(object, file)\n", " dumps(object) -> string\n", " load(file) -> object\n", " loads(string) -> object\n", "\n", "Misc variables:\n", "\n", " __version__\n", " format_version\n", " compatible_formats\n", "\n", "\n" ] } ], "source": [ "# Documentation strings\n", "\n", "import pickle\n", "\n", "print(pickle.__doc__)" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function print in module builtins:\n", "\n", "print(...)\n", " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n", " \n", " Prints the values to a stream, or to sys.stdout by default.\n", " Optional keyword arguments:\n", " file: a file-like object (stream); defaults to the current sys.stdout.\n", " sep: string inserted between values, default a space.\n", " end: string appended after the last value, default a newline.\n", " flush: whether to forcibly flush the stream.\n", "\n" ] } ], "source": [ "help(print)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Functions\n", "### Function annotations\n", "\n", "- Function annotations are completely optional metadata information about the types used by user-defined functions.\n" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'ham': , 'eggs': , 'return': }\n" ] } ], "source": [ "# Function annotations\n", "\n", "def breakfast(ham: str, eggs: str = 'eggs') -> str:\n", " return ham + ' and ' + eggs\n", "\n", "print(breakfast.__annotations__)" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Functions\n", "### Function decorators\n", "\n", "- Wrappers to existing functions\n", "- Dynamically alter the functionality of a function\n", "- Ideal when you need to extend the functionality of functions that you don't want to modify" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, John!\n", "

Hello, John!

\n" ] } ], "source": [ "# Function decorators\n", "\n", "def greeting(name):\n", " return \"Hello, {0}!\".format(name)\n", "\n", "def decorate_with_p(func):\n", " def function_wrapper(name):\n", " return \"

{0}

\".format(func(name))\n", " return function_wrapper\n", "\n", "my_get_text = decorate_with_p(greeting)\n", "\n", "print(greeting('John'))\n", "print(my_get_text('John'))" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "

Hello, John!

\n" ] } ], "source": [ "# Function decorators\n", "\n", "def decorate_with_p(func):\n", " def function_wrapper(name):\n", " return \"

{0}

\".format(func(name))\n", " return function_wrapper\n", "\n", "@decorate_with_p\n", "def greeting(name):\n", " return \"Hello, {0}!\".format(name)\n", "\n", "print(greeting('John'))" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "
Hello, John!
\n", "

Hello, John!

\n" ] } ], "source": [ "# Function decorators\n", "\n", "def decorate_with_div(func):\n", " def function_wrapper(text):\n", " return \"
{0}
\".format(func(text))\n", " return function_wrapper\n", "\n", "@decorate_with_div\n", "def greeting(name):\n", " return \"Hello, {0}!\".format(name)\n", "\n", "print(greeting('John'))\n", "\n", "@decorate_with_div\n", "@decorate_with_p\n", "def greeting(name):\n", " return \"Hello, {0}!\".format(name)\n", "\n", "print(greeting('John'))" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Classes\n", "\n", "- To group data and functions belonging together to form custom data types\n", "- A Class is like an object constructor or a \"blueprint\" for creating objects" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello my name is John, I am 36 years old.\n", "Hello my name is Mary, I am 25 years old.\n", "Hello my name is John, I am 39 years old.\n" ] } ], "source": [ "# Classes\n", "\n", "class Person:\n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", "\n", " def say_hello(self):\n", " print(\"Hello my name is \" + self.name + \", I am \" + str(self.age) + \" years old.\")\n", "\n", "p1 = Person(\"John\", 36)\n", "p1.say_hello()\n", "\n", "p2 = Person(\"Mary\", 25)\n", "p2.say_hello()\n", "\n", "p1.age = 39\n", "p1.say_hello()" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Classes\n", "### Inheritance\n", "\n", "- Allows a derived class to reuse the same code and modify it accordingly\n", "- Derived classes may override methods of their base classes." ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "John, A23\n" ] } ], "source": [ "# Inheritance\n", "\n", "class Person:\n", " def __init__(self, name):\n", " self.name = name\n", "\n", " def get_name(self):\n", " return self.name\n", "\n", "class Employee(Person):\n", " def __init__(self, name, staff_id):\n", " Person.__init__(self, name) # super().__init__(name)\n", " self.staff_id = staff_id\n", "\n", " def get_full_id(self):\n", " return self.get_name() + ', ' + self.staff_id\n", "\n", "employee = Employee('John', 'A23')\n", "print(employee.get_full_id())" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12/08/2018\n", "11:23 PM\n" ] } ], "source": [ "# Multiple inheritance\n", "\n", "class Clock:\n", " time = '11:23 PM'\n", " def get_time(self):\n", " return self.time\n", "\n", "class Calendar:\n", " date = '12/08/2018'\n", " def get_date(self):\n", " return self.date\n", "\n", "class CalendarClock(Clock, Calendar):\n", " pass\n", "\n", "calendar_clock = CalendarClock()\n", "print(calendar_clock.get_date())\n", "print(calendar_clock.get_time())" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "slide" } }, "source": [ "## Modules\n", "\n", "- As your program gets longer, you may want to split it into several files for easier maintenance\n", "- Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter\n", "- Such a file is called a module\n", "- A module is a file containing Python definitions and statements\n", "- A Package is a way of structuring Python’s module namespace by using “dotted module names”" ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "data": { "text/plain": [ "['C:\\\\Users\\\\lunde\\\\PycharmProjects\\\\machine-learning-ocademy-ai\\\\open-machine-learning-jupyter-book\\\\slides\\\\python-programming',\n", " 'd:\\\\programs\\\\python3_7_4\\\\python37.zip',\n", " 'd:\\\\programs\\\\python3_7_4\\\\DLLs',\n", " 'd:\\\\programs\\\\python3_7_4\\\\lib',\n", " 'd:\\\\programs\\\\python3_7_4',\n", " '',\n", " 'C:\\\\Users\\\\lunde\\\\AppData\\\\Roaming\\\\Python\\\\Python37\\\\site-packages',\n", " 'd:\\\\programs\\\\python3_7_4\\\\lib\\\\site-packages',\n", " 'd:\\\\programs\\\\python3_7_4\\\\lib\\\\site-packages\\\\docloud-1.0.257-py3.7.egg',\n", " 'd:\\\\programs\\\\python3_7_4\\\\lib\\\\site-packages\\\\win32',\n", " 'd:\\\\programs\\\\python3_7_4\\\\lib\\\\site-packages\\\\win32\\\\lib',\n", " 'd:\\\\programs\\\\python3_7_4\\\\lib\\\\site-packages\\\\Pythonwin',\n", " 'C:\\\\Users\\\\lunde\\\\AppData\\\\Roaming\\\\Python\\\\Python37\\\\site-packages\\\\IPython\\\\extensions',\n", " 'C:\\\\Users\\\\lunde\\\\.ipython']" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Modules\n", "\n", "import sys\n", "sys.path" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The value of pi is 3.141592653589793\n" ] } ], "source": [ "# Packages\n", "\n", "# import only pi from math module\n", "from math import pi\n", "\n", "print(\"The value of pi is\", pi)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The value of pi is 3.141592653589793\n", "The value of sin(pi) is 1.2246467991473532e-16\n" ] } ], "source": [ "# Packages\n", "\n", "# import all names from the standard module math\n", "from math import *\n", "\n", "print(\"The value of pi is\", pi)\n", "print(\"The value of sin(pi) is\", sin(pi))" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Let's try with our own module\n", "\n", "We write those code into the file `my_module.py`:\n", "```\n", "def my_sum(a, b):\n", " return a + b\n", "```" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing my_module.py\n" ] } ], "source": [ "%%writefile my_module.py\n", "\n", "def my_sum(a, b):\n", " return a + b" ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8\n" ] } ], "source": [ "from my_module import my_sum\n", "\n", "print(my_sum(3, 5))" ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "!rm my_module.py" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Errors and exceptions\n", "\n", "- Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it\n", "- Errors detected during execution are called exceptions and are not unconditionally fatal" ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Error: division by zero\n" ] } ], "source": [ "try:\n", " result = 10 * (1 / 0) # division by zero\n", " print(\"Result: \", result)\n", "except ZeroDivisionError:\n", " print(\"Error: division by zero\")" ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "pycharm": { "name": "#%%\n" }, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Result: 10\n", "Error: unexpected error\n" ] } ], "source": [ "try:\n", " result = 10\n", " print(\"Result: \", result)\n", " result += 'a'\n", " print(\"Result: \", result)\n", "except ZeroDivisionError:\n", " print(\"Error: division by zero\")\n", "except:\n", " # We should get here because of division by zero.\n", " print(\"Error: unexpected error\")" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "subslide" } }, "source": [ "## Your turn! 🚀\n", "\n", "- Practice the Python programming (advanced) by following the assignment" ] }, { "cell_type": "markdown", "metadata": { "pycharm": { "name": "#%% md\n" }, "slideshow": { "slide_type": "slide" } }, "source": [ "## References:\n", "\n", "- https://www.geeksforgeeks.org/packing-and-unpacking-arguments-in-python/\n", "- https://cs.nyu.edu/courses/summer16/CSCI-UA.0002-002/slides/Python_Functions.pdf\n", "- https://moodle2.units.it/pluginfile.php/375147/mod_resource/content/2/python_3_2021.pdf\n", "- https://www.geeksforgeeks.org/python-lambda-anonymous-functions-filter-map-reduce/\n" ] } ], "metadata": { "celltoolbar": "Slideshow", "init_cell": "run_on_kernel_ready", "jupytext": { "formats": "ipynb" }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.18" }, "rise": { "autolaunch": true, "chalkboard": { "color": [ "rgb(250, 250, 250)", "rgb(250, 250, 250)" ] }, "enable_chalkboard": true, "header": "", "progress": true, "scroll": true }, "vscode": { "interpreter": { "hash": "aee8b7b246df8f9039afb4144a1f6fd8d2ca17a180786b69acc140d282b71a49" } } }, "nbformat": 4, "nbformat_minor": 2 }