{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "xor84onNuod5" }, "source": [ "# Introduction to Python\n", "\n", "* [Notebook](https://colab.research.google.com/drive/1tse3vtBc9iLrMNC9AW_K7L7qOscXg_gJ) of this section (open in a separate tab)\n", "\n", "* [Video](https://youtu.be/cPGSbcIxe14) of this section (31 minutes)\n" ] }, { "cell_type": "markdown", "source": [ "## Overview\n", "- Variables are mainly integers, real numbers, Boolean variables, characters, lists, dictionaries, etc., each of which defines operations and comparison operators.\n", "- The elements of a list start from the zero th element.\n", "- A partial list can be extracted from a list in slice notation.\n", "- In for and if statements, processing blocks are distinguished by a colon and indentation. An error occurs if the indentation is not aligned in a block.\n", "- Functions and classes are defined in the same way, using a colon and indentation.\n", "- Classes allow variables to be used in multiple functions (class functions). This also makes it easier to avoid variable name collisions.\n", "\n" ], "metadata": { "id": "3Xv58AkND3zJ" } }, { "cell_type": "markdown", "metadata": { "id": "e2HlKtP5Eq1p" }, "source": [ "## Python Basics" ] }, { "cell_type": "markdown", "metadata": { "id": "86Rih_-RBnlW" }, "source": [ "### Version check" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uYqfUe62DE-C", "outputId": "729c34f5-1728-4955-a496-2979cb0b638e" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python 3.7.12\n" ] } ], "source": [ "!python --version" ] }, { "cell_type": "markdown", "metadata": { "id": "7c6Gd171DrKc" }, "source": [ "### Arithmetic calculations\n", "\n", "Arithmetic calculations are intuitive in Python: one instruction per line.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "B3m5Fe43JzhY", "outputId": "1ced590d-1204-4233-f443-75b968ba064e" }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 + 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "X7hRKkubJy7D", "outputId": "2a4f6fff-8901-44e4-82f9-b9aa3ff0d985" }, "outputs": [ { "data": { "text/plain": [ "20" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "4 * 5" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Ov8-FwW2EvTm", "outputId": "7b5a2cc8-ceee-4070-8253-48efdcb8eff9" }, "outputs": [ { "data": { "text/plain": [ "0.2857142857142857" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 / 7" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "QEi4C5dBEvnq", "outputId": "bd63408b-365a-477b-8601-184796309e05" }, "outputs": [ { "data": { "text/plain": [ "81" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 ** 4 # 3 to the fourth power" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Ahzt0OSt7rMO", "outputId": "2d56926a-6188-40e8-c8dc-bc15962803f2" }, "outputs": [ { "data": { "text/plain": [ "1.7320508075688772" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 ** 0.5 # 0.5 power of 3 = root 3" ] }, { "cell_type": "markdown", "metadata": { "id": "95uXrgaFFFOy" }, "source": [ "### Data types\n", "\n", "Each variable in Python has a data type, which can be displayed using the type() function. Data types include integer (int), floating-point (float), and string (str)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "LJ1yV2EeFNr2", "outputId": "dcf3bcb8-0465-4f4b-d278-930ff133c6be" }, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(10)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "axTweFqhFbjl", "outputId": "3068e5eb-7243-4c46-bdf3-2e69a75d2a60" }, "outputs": [ { "data": { "text/plain": [ "float" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(1.3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "jyj20Ni8Fe4a", "outputId": "6fcc4339-bb93-47e6-bb07-a13d6e3b2632" }, "outputs": [ { "data": { "text/plain": [ "str" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type('hello')" ] }, { "cell_type": "markdown", "metadata": { "id": "Fa6LUv0pF5cl" }, "source": [ "### list\n", "\n", "Data type is list\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "yS0FX_DJGLfz", "outputId": "e3d102e4-f177-498e-b9a4-48aabb43d81c" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[10, 31, 2.4, 6]\n" ] }, { "data": { "text/plain": [ "list" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = [10, 31, 2.4, 6]\n", "print(a)\n", "type(a)" ] }, { "cell_type": "markdown", "metadata": { "id": "lN6oQtPDEE2s" }, "source": [ "length of lists" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Ll51WzXRD97o", "outputId": "42a72a6a-e6f5-4c26-f949-fba5f465ce2e" }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(a)" ] }, { "cell_type": "markdown", "metadata": { "id": "9JlxFzNYNXwp" }, "source": [ "Lists differ from vectors in the rules of operation." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "uyTnZkDJM5we", "outputId": "430c0772-769d-4fd6-ca87-5bce5bcc5a19" }, "outputs": [ { "data": { "text/plain": [ "[1, 2, 3, 4]" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[1, 2] + [3, 4]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "OkTCZzMnNGuQ", "outputId": "c07e14e7-0bc5-4100-de43-feb1e194a6dd" }, "outputs": [ { "data": { "text/plain": [ "[1, 'ABC', 1, 'ABC', 1, 'ABC']" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[1,'ABC'] * 3" ] }, { "cell_type": "markdown", "metadata": { "id": "84jUfTkIR6KU" }, "source": [ "**The first element in the list is the zeroth**." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "aMZhfQuTR83c", "outputId": "7b04549a-281a-42b8-a91d-ef9bd6766fea" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "31\n", "2.4\n", "6\n" ] } ], "source": [ "print(a[0])\n", "print(a[1])\n", "print(a[2])\n", "print(a[3])" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "9NuY03OpHkz3", "outputId": "9ee6bae4-1210-46f7-9f7f-312c21fc19d0" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n" ] } ], "source": [ "print(a[-1])" ] }, { "cell_type": "markdown", "metadata": { "id": "TJ8tvO5mJKxA" }, "source": [ "To extract a partial list, the notation **Slicing** can be used. The first number is zero, the second is one, and so on." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "OM8FaKwtKfH8", "outputId": "a8c441e8-7eff-4936-9fee-6f547544efd2" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[0, 1, 2, 3, 4, 5]\n", "[1, 2]\n", "[2, 3, 4, 5]\n" ] } ], "source": [ "a=[0,1,2,3,4,5]\n", "print(a[:]) # from the first to the last, that is, a itself\n", "print(a[1:3]) # from the first to the third \"one before\n", "print(a[2:]) # from the second to the last" ] }, { "cell_type": "markdown", "metadata": { "id": "mbMQs6tZN2tQ" }, "source": [ "### Dictionary\n", "\n", "A dictionary is a set of keyed (labeled) values:\n", "\n", "```\n", "{key0: value0,key1: value1,... , key N-1: value N-1}\n", "```\n", "\n", "The data type is dict." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "1X_LlI0YO4y3", "outputId": "1f2cf1da-3c44-4b71-9bf3-209bd78aa40a" }, "outputs": [ { "data": { "text/plain": [ "{'height': 160, 'weight': 50}" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alice = {'height': 160, 'weight': 50}\n", "alice" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "U59oMWYWUgqt", "outputId": "f7df9f66-ef7d-4c0e-dfe5-2834453d35c6" }, "outputs": [ { "data": { "text/plain": [ "dict" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(alice)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Mm6yt717PZ7K", "outputId": "4f4cef4f-1377-43ef-ef70-8c9924636036" }, "outputs": [ { "data": { "text/plain": [ "160" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alice['height']" ] }, { "cell_type": "markdown", "metadata": { "id": "XZkJ38Oo8K6F" }, "source": [ "Adds a new element to the dictionary." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "eo-ZDLJ_8QtX", "outputId": "e7e7306e-cc65-4514-b031-ed81b22f1d2b" }, "outputs": [ { "data": { "text/plain": [ "{'height': 160, 'nationality': 'UK', 'weight': 50}" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "alice['nationality'] = 'UK'\n", "alice" ] }, { "cell_type": "markdown", "metadata": { "id": "tH5qQRuIQEb_" }, "source": [ "## Control statements" ] }, { "cell_type": "markdown", "metadata": { "id": "E_gx4QTFOnN8" }, "source": [ "### If\n", "\n", "If statements can be used for conditional branching.\n", "```\n", "if Condition: True\n", " If True, execute.\n", " If true, then execute.\n", "else: Execute if False.\n", " Execute if False.\n", " Execute if False.\n", "````\n", "\n", "In Python, indentation must be aligned within the same block." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "IkGVXlIoPPlU", "outputId": "aa47290b-c4d1-4142-e3ec-92379fdb5a10" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "a = 5 の方が大きい\n" ] }, { "output_type": "execute_result", "data": { "text/plain": [ "5" ] }, "metadata": {}, "execution_count": 2 } ], "source": [ "# Compare two numbers and return the larger one\n", "\n", "a = 5\n", "b = 3\n", "\n", "if a > b:\n", " c = a\n", " print('a =', c ,'の方が大きい')\n", "else:\n", " c = b\n", " print('b =', c ,'の方が大きい')\n", "\n", "c" ] }, { "cell_type": "markdown", "metadata": { "id": "AGlG7iMdQ079" }, "source": [ "### for\n", "\n", "You can iterate using ``for'' statements.\n", "```\n", "for i in range(10):\n", " \"process\"\n", "```\n", "the \"process\" is executed from `i=0` to `i=9`." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "MmYH3aftQ08W", "outputId": "0dee6a79-a26e-4321-c1b4-8fca7e5880a9" }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "55" ] }, "metadata": {}, "execution_count": 5 } ], "source": [ "# Add 1 to 10\n", "\n", "s = 0\n", "for i in range(10):\n", " s += i+1\n", "\n", "s" ] }, { "cell_type": "markdown", "metadata": { "id": "JSl3b9LqRuDC" }, "source": [ "where `+=` is the operation of adding the right-hand side to the original value.\n", "\n", "It can also be written as follows." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Kg1ccIK7Puaq", "outputId": "bac6a4f7-2cac-4d3d-af5a-877e3c636705" }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "55" ] }, "metadata": {}, "execution_count": 4 } ], "source": [ "# Add 1 to 10\n", "\n", "s = 0\n", "for i in range(1,11):\n", " s += i\n", "\n", "s" ] }, { "cell_type": "markdown", "metadata": { "id": "gYlmeQdpOdAy" }, "source": [ "### Function\n", "\n", "Define a new function using def.\n", "```\n", "def function name(argument):\n", " Calculation rule\n", " Calculation rule\n", " Calculation rule\n", " return Return value.\n", "\n", "````" ] }, { "cell_type": "markdown", "metadata": { "id": "vLgtLK35hGdv" }, "source": [ "##### Example 1 (using if statement)\n", "\n", "Function to output the maximum of three numbers." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "I45MbolLQDQ8" }, "outputs": [], "source": [ "def max3(a,b,c): # a, b, c are arguments\n", " x = a\n", " if b > x:\n", " x = b\n", " if c > x:\n", " x = c\n", " return x\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "93uKQ0mbXnsq", "outputId": "a48b1ff1-a956-494e-c5a9-5c1eecd63c36" }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "7" ] }, "metadata": {}, "execution_count": 7 } ], "source": [ "m = max3(3,7,-2)\n", "m" ] }, { "cell_type": "markdown", "metadata": { "id": "70Onh-7Ahum8" }, "source": [ "#### Example 2 (using for statement)\n", "\n", "Function that returns $1 + 2 + \\cdots + n$ for a given number $n$.\n", "\n", "where `+=` is the operation of adding the right-hand side to the original value." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "Mkm70f0yimpV" }, "outputs": [], "source": [ "def f(n):\n", " y = 0\n", " for i in range(n): #i from 0 to n-1\n", " y += i + 1\n", " return y" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "daMFYQhcjP7y", "outputId": "aeb3e5b8-c4fe-4c46-ee6e-ca724ed801f1" }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "55" ] }, "metadata": {}, "execution_count": 12 } ], "source": [ "f(10)" ] }, { "cell_type": "markdown", "metadata": { "id": "8YhYMKAiSZd2" }, "source": [ "## Classes" ] }, { "cell_type": "markdown", "metadata": { "id": "THp08hCbUD7x" }, "source": [ "### Definition of Classes\n", "\n", "Classes allow you to define your own data types and functions for those data types.\n", "\n", "\n", "* Class: A class has its own data type, class variables and methods.\n", "* Class variables: various variables that objects of a class have. In this course, they are sometimes called parameters for the sake of explanation.\n", "* Methods: functions for the class.\n", "* Instance: An object (variable) with the data type of the class.\n", "\n", "\n", "Variables of objects of a class are called by `instance.variable`\n", "\n", "Functions of a class are called by\n", " `instance.method()` or `class.method(instance)`." ] }, { "cell_type": "markdown", "metadata": { "id": "6W4wMEbIcDKt" }, "source": [ "#### Example" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ruuHi6pLZDD-" }, "outputs": [], "source": [ "class Person:\n", " def __init__(self, name): # Constructor\n", " self.name = name\n", "\n", " def hello(self, keisho): # hello() method\n", " print('Hello '+ self.name +' ' + keisho + '!')\n", "\n", " def bye(self, keisho): # bye() method\n", " print('Good bye '+ self.name +' ' + keisho + '!')" ] }, { "cell_type": "markdown", "metadata": { "id": "ABboEN1kcYiZ" }, "source": [ "where\n", "\n", "```\n", " def __init__(self, name): # Constructor\n", " self.name = name\n", "```\n", "is the constructor, which is the default definition. `self `` is a temporary instance name used in the class definition." ] }, { "cell_type": "markdown", "metadata": { "id": "cTh7YwqZRuT3" }, "source": [ "Instance Creation" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "gMAPnSITTBaR" }, "outputs": [], "source": [ "abc = Person('Sato')" ] }, { "cell_type": "markdown", "metadata": { "id": "4oGpavhAUD8N" }, "source": [ "Checking class variables" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 36 }, "id": "JUzWH902T_-F", "outputId": "ab85fda2-c5bf-4343-851c-883f92c54250" }, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "'Sato'" ], "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" } }, "metadata": {}, "execution_count": 16 } ], "source": [ "abc.name" ] }, { "cell_type": "markdown", "metadata": { "id": "pVFf80RFTHvo" }, "source": [ "Using a method: There are two ways to write it." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "DsxnUV50cBxJ", "outputId": "34d957e6-0fd7-48ef-fe61-150ee82dda0d" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Hello Sato san!\n", "Hello Sato san!\n" ] } ], "source": [ "abc.hello('san')\n", "\n", "# Same if written as follows\n", "Person.hello(abc, 'san')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "GnZAaZtwTim1", "outputId": "03f916a1-4182-4720-adf7-fad14f21ebaf" }, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Good bye Sato san!\n" ] } ], "source": [ "abc.bye('san')" ] }, { "cell_type": "markdown", "metadata": { "id": "Lmw8UxK0TqIb" }, "source": [ "As shown in this example, class functions can be used without specifying the class variable abc.name." ] } ], "metadata": { "colab": { "provenance": [] }, "kernelspec": { "display_name": "Python 3", "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.8.8" } }, "nbformat": 4, "nbformat_minor": 0 }