{ "cells": [ { "cell_type": "markdown", "id": "1832c051", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "

Python course 2022

\n", "

Introduction to Python

\n", "\n", "
\"POuL
\n", "\n", "

Mirko <mroik@poul.org>

\n" ] }, { "cell_type": "markdown", "id": "1d18559e", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "# Why use Python\n", "\n", "- Easy to learn\n", "- Nonexistent boilerplate\n", "- Big and active community --> Lots of libraries\n", "- The best [documentation](https://docs.python.org/3)\n", "- And honestly, docstrings done right.\n" ] }, { "cell_type": "markdown", "id": "a84df39b", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## What we will talk about\n", "\n", "The basics of Python:\n", "\n", "- Variables\n", "- Control-flow\n", "- Functions\n", "- Data Structures\n" ] }, { "cell_type": "markdown", "id": "7f08ef93", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### What you will need in order to use Python\n", "\n", "I would suggest starting at Python's [website](https://www.python.org/)...\n", "in the _download_ section, you will find instructions to download Python for your operating system.\n", "\n", "A good text editor I recommended if you're writing scripts/programs is [PyCharm](https://www.jetbrains.com/pycharm/). It's an excellent choice, it performs well on popular OSes (Though, note that it really isn't a text editor but an IDE).\n", "\n", "If PyCharm is too heavy you may also want to try Visual Studio Code (which is an editor).\n", "\n", "Whatever you choose just make sure to install a vim plugin.\n", "Just kidding, that's just my thing.\n" ] }, { "cell_type": "markdown", "id": "7e2ba3f2", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Let's start!\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "19853476", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12\n" ] } ], "source": [ "variable = 12 # Integer\n", "print(variable)" ] }, { "cell_type": "code", "execution_count": 2, "id": "fb51da4f", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dodici\n" ] } ], "source": [ "variable = \"dodici\" # String\n", "variable2 = 'tredici' # Another string\n", "print(variable)" ] }, { "cell_type": "code", "execution_count": 3, "id": "dd2b96bc", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "15\n" ] } ], "source": [ "alfa, beta = 12, 3 # Fancy way to declare\n", "theta = alfa + beta # a third variable containing the sum of the other two\n", "print(theta)" ] }, { "cell_type": "markdown", "id": "a4e7b63f", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Easy to use.. and VERSATILE\n", "\n", "It adapts to the programmer:\n", "\n", "- [Complex architectures](https://www.djangoproject.com/download/)\n", "- [Command Line applications](https://en.wikipedia.org/wiki/Command-line_interface)\n", "- [Scraping](https://www.crummy.com/software/BeautifulSoup/bs4/doc/)\n", "- [Telegram bots](https://github.com/python-telegram-bot/python-telegram-bot)\n", "- Data science\n", "- And more...\n" ] }, { "cell_type": "markdown", "id": "23eb6909", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## In Python there are many ways to do the same thing\n" ] }, { "cell_type": "markdown", "id": "b9721e29", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## The complicated way\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "7f7628ed", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello, world\n" ] } ], "source": [ "def greet(what):\n", " def decorator(foo):\n", " def hello():\n", " print(what, end=\", \")\n", " foo()\n", " return hello\n", " return decorator\n", "\n", "@greet(\"hello\")\n", "def hello_world():\n", " print(\"world\")\n", "\n", "hello_world()" ] }, { "cell_type": "markdown", "id": "42e8c06b", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## The modular one\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "f60870ed", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "hello, world\n" ] } ], "source": [ "class Class_hello:\n", " def __init__(self, who):\n", " self.who = who\n", "\n", " def hello(self):\n", " print(f\"hello, {self.who}\")\n", " \n", "clss = Class_hello(\"world\")\n", "clss.hello()" ] }, { "cell_type": "markdown", "id": "49c2a540", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## The simple one\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "a39340e6", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, world!\n" ] } ], "source": [ "print(\"Hello, world!\")" ] }, { "cell_type": "markdown", "id": "436159b1", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# How do I start coding in Python?" ] }, { "cell_type": "markdown", "id": "3f34f14f", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "First of all, create a file with the *dot py* extenstion (`.py`).\n", "Then open it up with your favorite editor." ] }, { "cell_type": "markdown", "id": "13dcc7a5", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "If you have experience with code, usually you'll know that before starting to code we'll need to write down some boilerplate.\n", "In Python that's not a thing. You can start writing right away." ] }, { "cell_type": "markdown", "id": "02bee160", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# The language\n" ] }, { "cell_type": "markdown", "id": "8feb317e", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Variables\n", "\n", "Python is a `weakly-typed` language, meaning that we can get\n", "away with assigning a different type of value in a already defined\n", "variable.\n", "\n", "Once declared, the variable type in a language like _C_, cannot change:\n", "\n", "```c\n", "int x;\n", "x = 2.5;\n", "```\n", "The decimal part will be pruned 'cause `x` is declared as Integer." ] }, { "cell_type": "code", "execution_count": 7, "id": "215d0c74", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12\n", "a string\n" ] } ], "source": [ "x = 12\n", "print(x)\n", "x = \"a string\"\n", "print(x)" ] }, { "cell_type": "markdown", "id": "9757674f", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### \"Storing Values in Variables\"\n", "\n", "> A variable is like a box in the computer’s memory where you can store a single value.\n", ">\n", "> If you want to use the result of an evaluated expression later in your program, you can save it inside a variable.\n", ">\n", "> [@AlSweigart python books](https://automatetheboringstuff.com/2e/chapter1/)\n" ] }, { "cell_type": "markdown", "id": "bffb1568", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Types/Operators\n", "\n", "Variables can contain many different types of data, here are some...\n", "\n", "We can form expressions that the python interpreter will solve for us.\n", "\n", "...this is for those who want to [deepen the topic...](https://docs.python.org/3/tutorial/introduction.html#using-python-as-a-calculator)\n" ] }, { "cell_type": "markdown", "id": "b6b37f12", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "| Name | Exampl |\n", "| ------- | ---------- |\n", "| Integer | 11 |\n", "| Float | 2.3 |\n", "| Boolean | True/False |\n", "| String | \"apple\" |\n", "| ...... | .... |\n" ] }, { "cell_type": "markdown", "id": "362ccee3", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "| Operator | Name | Example |\n", "| --------- | ----------- | ------------------------------- |\n", "| / | Division | 5 / 2 ⇒ 2.5 |\n", "| // | Floor Divis | 5 // 2 ⇒ 2 |\n", "| % | Modulo | 5 % 2 ⇒ 1 |\n", "| \\* | Multiplic. | 2 \\* 3 ⇒ 6 |\n", "| + | Sum | 2 + 2 ⇒ 4 |\n", "| - | Subtraction | 3 - 2 ⇒ 1 |\n", "| \\*\\* | Power | 2 \\*\\* 3 ⇒ 8 |\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "06eba7f4", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.5\n" ] } ], "source": [ "## Order of operations\n", "x = 10\n", "y = 5\n", "\n", "print((x % y) + 1**2 / 2) ## What is the result?" ] }, { "cell_type": "markdown", "id": "48686371", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### A program using the things we just demonstrated\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "b7559721", "metadata": { "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "🍎 The basket contains 14 apples.\n", "🍎 6 apples were added, for a total of 20 apples.\n", "🍎 Sharing them with 3 people would leave 2 apples in the basket\n" ] } ], "source": [ "basket = 14\n", "print(f\"🍎 The basket contains {basket} apples.\")\n", "added_apples = 6\n", "basket += added_apples # basket = basket + added_apples\n", "print(f\"🍎 {added_apples} apples were added, for a total of {basket} apples.\")\n", "\n", "print(f\"🍎 Sharing them with 3 people would leave {basket % 3} apples in the basket\")" ] }, { "cell_type": "markdown", "id": "c57c59ee", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Control-Flow\n", "\n", "A block of code can be executed based on the evaluation of a logical expression.\n", "\n", "We will talk about:\n", "\n", "- Logical expressions\n", "- Conditionals\n", "- Iterations\n", "- Code Blocks <-- let's be precise\n", "\n", "...the title is also a link\n" ] }, { "cell_type": "markdown", "id": "b6974e2e", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Logical expressions\n", "\n", "Evaluate the logical outcome of two or more statements.\n" ] }, { "cell_type": "code", "execution_count": 10, "id": "710a290a", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "True\n", "True\n", "False\n", "True\n", "True\n", "True\n" ] } ], "source": [ "print(True != False) #True\n", "print(not True) #False\n", "print(1 == True) #True\n", "print(0 == False) #True\n", "print(1 > 1.1) #False\n", "print(2 <= 2) #True\n", "print(True and not False) #True\n", "print(True or False) #True" ] }, { "cell_type": "markdown", "id": "5a2ee7d0", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Conditional execution\n", "\n", "- `if`: checks the expression, executes the code block if `True`\n", "- `elif`: checks another expression, executes code block if `True`\n", "- `else`: executes the code block if the previous are `False`\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "a5502bc7", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[*] The basket contains 10 apples\n" ] } ], "source": [ "basket = 10\n", "\n", "if basket == 10:\n", " print(\"[*] The basket contains 10 apples\")\n", "elif basket > 10:\n", " print(\"[*] The basket contains more than 10 apples\")\n", "else:\n", " print(\"[*] The basket contains less than 10 apples\")" ] }, { "cell_type": "code", "execution_count": 12, "id": "82f16964", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[*] The basket is empty\n" ] } ], "source": [ "basket = 0\n", "\n", "if basket == 0:\n", " print(\"[*] The basket is empty\")\n", "else:\n", " print(\"[*] The basket contains something\")" ] }, { "cell_type": "markdown", "id": "9efbb974", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Execution by Iteration\n", "\n", "- `while`: Executes the code block while the expression results `True`.\n", "- `for`: Executes the code block in a loop for every item in a sequence.\n", "\n", "```python\n", "while expression_is_true:\n", " # Do something\n", "\n", "for some_index in this_sequence:\n", " # Do something\n", "```\n" ] }, { "cell_type": "code", "execution_count": 13, "id": "2b0f2b31", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Gnam, we now have 3 🍏\n", "Gnam, we now have 2 🍏\n", "Gnam, we now have 1 🍏\n", "Gnam, we now have 0 🍏\n", "\n", "No more apples :(\n" ] } ], "source": [ "basket = 4\n", "while basket > 0:\n", " basket = basket - 1\n", " print(f\"Gnam, we now have {basket} 🍏\")\n", "print(\"\\nNo more apples :(\")" ] }, { "cell_type": "code", "execution_count": 14, "id": "b735e4f5", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "9 * 1 = 9\n", "9 * 2 = 18\n", "9 * 3 = 27\n", "9 * 4 = 36\n", "9 * 5 = 45\n", "9 * 6 = 54\n", "9 * 7 = 63\n", "9 * 8 = 72\n", "9 * 9 = 81\n", "9 * 10 = 90\n" ] } ], "source": [ "# Multiplication table\n", "i, base = 1, 9\n", "while i <= 10:\n", " print(f\"{base} * {i} = {i*base}\")\n", " i += 1" ] }, { "cell_type": "code", "execution_count": 15, "id": "4bb34b90", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apples\n", "bananas\n", "pears\n", "turkeys\n" ] } ], "source": [ "for value in [\"apples\", \"bananas\", \"pears\", \"turkeys\"]:\n", " print(value)" ] }, { "cell_type": "code", "execution_count": 16, "id": "07c05863", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 \n", "1 🍎\n", "2 🍎🍎\n", "3 🍎🍎🍎\n", "4 🍎🍎🍎🍎\n" ] } ], "source": [ "for i in range(5):\n", " print(f\"{i} {'🍎' * i}\")" ] }, { "cell_type": "markdown", "id": "2ef8aa5d", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Break & Continue\n" ] }, { "cell_type": "code", "execution_count": 17, "id": "9fab3f84", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "😀 Happy\n", "😁 Happy\n", "😂 Happy\n", "🤬 Error\n" ] } ], "source": [ "for value in [\"😀\",\"😁\",\"😂\",\"🤬\",\"🤣\",\"😃\"]:\n", " print(value, end=\" \")\n", " if value == \"🤬\":\n", " print(\"Error\")\n", " break\n", " print(\"Happy\")" ] }, { "cell_type": "code", "execution_count": 18, "id": "f1331407", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "😀 Happy\n", "😁 Happy\n", "😂 Happy\n", "🤬 🤣 Happy\n", "😃 Happy\n" ] } ], "source": [ "for value in [\"😀\",\"😁\",\"😂\",\"🤬\",\"🤣\",\"😃\"]:\n", " print(value, end=\" \")\n", " if value == \"🤬\":\n", " continue\n", " print(\"Error\")\n", " print(\"Happy\")" ] }, { "cell_type": "markdown", "id": "e6120a5b", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Functions\n", "\n", "[\"Black boxes\"](https://docs.python.org/3/tutorial/controlflow.html#defining-functions), functions take input parameters, give output data (not always).\n", "\n", "Functions allow you to reuse code you have already written,\n", "saving up time (most of the time, with code written by other people).\n" ] }, { "cell_type": "markdown", "id": "ed5e4e18", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "```python\n", "def name_of_function():\n", " some_variable = \"an instruction\"\n", " some_other_variable = \"another instruction\"\n", " a_third_instruction()\n", " # and so on....\n", "\n", "name_of_function()\n", "```" ] }, { "cell_type": "code", "execution_count": 19, "id": "8ce5dc96", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, world!\n", "Hello, world!\n" ] } ], "source": [ "def say_hello():\n", " print(\"Hello, world!\")\n", "\n", "say_hello()\n", "say_hello()" ] }, { "cell_type": "code", "execution_count": 20, "id": "b7602820", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12\n", "11\n" ] } ], "source": [ "def add_10(number):\n", " number += 10\n", " print(number)\n", " \n", "add_10(2)\n", "add_10(1)" ] }, { "cell_type": "code", "execution_count": 21, "id": "3d5775fd", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I had 15, now I have 25\n", "Look mom! Without auxiliary variables: 25\n" ] } ], "source": [ "def add_10(number):\n", " number += 10\n", " return number\n", "\n", "base = 15\n", "result = add_10(base)\n", "\n", "print(f\"I had {base}, now I have {result}\")\n", "print(f\"Look mom! Without auxiliary variables: {add_10(base)}\")" ] }, { "cell_type": "code", "execution_count": 22, "id": "ef6890cd", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12\n", "11\n", "10\n" ] } ], "source": [ "def add_10(number=0):\n", " number += 10\n", " print(number)\n", " \n", "add_10(2)\n", "add_10(1)\n", "add_10()" ] }, { "cell_type": "code", "execution_count": 23, "id": "bcd3c9c1", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 x 1 = 2\n", "2 x 2 = 4\n", "2 x 3 = 6\n", "2 x 4 = 8\n", "\n", "Multiplication Table of 8\n", "8 x 1 = 8\n", "8 x 2 = 16\n", "8 x 3 = 24\n" ] } ], "source": [ "### Rewritten the previous while example as a function\n", "def tables(x, length=10, show_title=False):\n", " if show_title:\n", " print(f\"Multiplication Table of {x}\")\n", "\n", " for i in range(length):\n", " print(f\"{x} x {i+1} = {x * (i+1)}\")\n", " i += 1\n", "\n", "\n", "tables(2, 4)\n", "print()\n", "tables(8, show_title=True, length=3)" ] }, { "cell_type": "markdown", "id": "9e1c3bae", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## [Scope](https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces), or code visibility\n", "\n", "Variables and functions have their own context, for pragmatic reasons.\n", "\n", "- name collision\n", "- unexpected behaviours\n" ] }, { "cell_type": "code", "execution_count": 24, "id": "ca699f1d", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "x = \"abercrombie\" #Global 🌍\n", "\n", "def fun1():\n", " print(f\"fun1: x = {x}\")\n", "\n", "def fun2():\n", " x = \"2️\"\n", " print(f\"fun2: x = {x}\")\n", " \n", "def fun3():\n", " global x\n", " x = \"3️\"\n", " print(f\"fun3: x = {x}\")" ] }, { "cell_type": "code", "execution_count": 25, "id": "43e2fa73", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "🌍: x = abercrombie\n", "fun1: x = abercrombie\n", "fun2: x = 2️\n", "🌍: x = abercrombie\n", "fun3: x = 3️\n", "fun1: x = 3️\n", "fun2: x = 2️\n", "🌍: x = 3️\n" ] } ], "source": [ "print(f\"🌍: x = {x}\")\n", "fun1()\n", "fun2()\n", "print(f\"🌍: x = {x}\")\n", "\n", "fun3()\n", "fun1()\n", "fun2()\n", "print(f\"🌍: x = {x}\")" ] }, { "cell_type": "markdown", "id": "f15f0b15", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Data Structures\n", "\n", "Data organized in a [structure](https://docs.python.org/3/tutorial/datastructures.html) to facilitate processing.\n" ] }, { "cell_type": "markdown", "id": "78606f2d", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Sequences\n", "### List -- **mutable sequences**\n", "\n", "- **ordered** collections\n", "- defined inside squared brackets\n", "\n", "```python\n", "list_name = [\"first item\", \"second item\", ...]\n", "```\n" ] }, { "cell_type": "markdown", "id": "e85ddcb5", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Sequences\n", "\n", "### Tuple -- **immutable sequences**\n", "\n", "- **ordered** collections\n", "- defined inside parenthesis\n", "\n", "```python\n", "tuple_name = (item, item, ...)\n", "tuple_name = (item, ) # If a tuple only has 1 item\n", "```" ] }, { "cell_type": "code", "execution_count": 26, "id": "49ded31e", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dog\n", "cat\n", "eleven\n", "13\n", "\n", "[*!!!*]\n", "cat\n", "eleven\n", "13\n" ] } ], "source": [ "# Function definition\n", "def print_sequence(seq):\n", " for i in seq:\n", " print(i)\n", " \n", "def modify_sequence(seq):\n", " seq[0] = \"[*!!!*]\"\n", " print_sequence(seq)\n", " \n", "# Structures\n", "lst = [\"dog\", \"cat\", \"eleven\", 13]\n", "tpl = (\"dog\", \"cat\", \"eleven\", 13)\n", "\n", "# Execute functions with structures as parameters\n", "print_sequence(lst)\n", "print()\n", "modify_sequence(lst)" ] }, { "cell_type": "markdown", "id": "97901482", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Dictionaries -- key/value pairs\n", "\n", "- **mutable** sequences\n", "- defined inside _{_ _}_\n", "\n", "```python\n", "dict_name = {key : value, key : value,...}\n", "```\n" ] }, { "cell_type": "code", "execution_count": 27, "id": "87d6bf3f", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "dct = {1: \"cane\", 2: \"gatto\", 3: \"alpaca\"}\n", "dct2 = {\"alfabeto\": \"alpaca\", \"cane\": 1}" ] }, { "cell_type": "code", "execution_count": 28, "id": "4e295477", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Mario', 'Rossi', 27]\n", "{'firstname': 'Mario', 'lastname': 'Rossi', 'age': 27}\n" ] } ], "source": [ "# A more pragmatic one...\n", "\n", "def return_person_list():\n", " lst = []\n", " lst.append(\"Mario\")\n", " lst.append(\"Rossi\")\n", " lst.append(27)\n", " return lst\n", "\n", "def return_person_dict():\n", " d = {}\n", " d[\"firstname\"] = \"Mario\"\n", " d[\"lastname\"] = \"Rossi\"\n", " d[\"age\"] = 27\n", " return d\n", "\n", "print(return_person_list())\n", "print(return_person_dict())" ] }, { "cell_type": "markdown", "id": "7b5fd216", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Other data types...\n", "\n", "For other unmentioned data types...\n", "\n", "- **Strings** (`str`)\n", "- **Complex numbers** (`complex`)\n", "- **Bytes** (`bytes`)\n", "- **Queues** (`queue.Queue`, `multiprocessing.Queue`)\n", "- ...\n", "\n", "For everything you don't know/remember about the language.. \n", "there is a section in the docs for that.\n", "\n", "In this case: [python - Data Model ](https://docs.python.org/3/reference/datamodel.html#the-standard-type-hierarchy).\n" ] }, { "cell_type": "markdown", "id": "28d2f026", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# [I/O](https://docs.python.org/3/tutorial/inputoutput.html) -- or Input/Output\n", "\n", "User interaction, or the thing that makes your program useful.. \n", "it is also very dangerous.\n" ] }, { "cell_type": "code", "execution_count": 29, "id": "1ab7c5fc", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Whats your name?Mirko\n", "Hello, world with inputs --> Hello, Mirko!\n" ] } ], "source": [ "name = input(\"Whats your name?\")\n", "print(\"Hello, world with inputs --> Hello, {}!\".format(name))" ] }, { "cell_type": "code", "execution_count": 30, "id": "59028774", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Simple Addition:\n", "First term: 2\n", "Second term: 3\n", "2 + 3 = 5\n", "2 + 3 = 5\n" ] } ], "source": [ "print(\"Simple Addition:\")\n", "add1 = int(input(\"First term: \"))\n", "add2 = int(input(\"Second term: \"))\n", "print(f\"{add1} + {add2} = {add1 + add2}\") # with f-strings!\n", "\n", "# or\n", "print(\"{} + {} = {}\".format(add1, add2, add1 + add2))" ] }, { "cell_type": "markdown", "id": "7cbf16cb", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Modules\n", "A big advantage of Python is the quantity of libraries that are available. So how do we write/use a library?\n", "\n", "If you want to reference a python script you already wrote simply use the `import` statement.\n", "\n", "Let's say that we have a script called _test.py_, to reference it we simply type `import test`.\n", "\n", "What this will do is execute that script, so if we want to make a \"library\" of our own, we simply make a python file with only function definitions." ] }, { "cell_type": "code", "execution_count": 31, "id": "da0ace1d", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Module loaded successfully\n" ] } ], "source": [ "# test.py\n", "def hello_world():\n", " print(\"Hello world!\")\n", "\n", "def add_10(n):\n", " return n + 10\n", "\n", "print(\"Module loaded successfully\")" ] }, { "cell_type": "code", "execution_count": null, "id": "bbcefe2e", "metadata": { "scrolled": true, "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# test2.py\n", "import test\n", "\n", "test.hello_world()\n", "n = add_10(5)\n", "print(n)" ] }, { "cell_type": "markdown", "id": "d47d0a59", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "If the name of a module is too long, we can rename the namespace by using the keyword `as` after the import followed by the new name." ] }, { "cell_type": "code", "execution_count": null, "id": "6b311280", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "import test as ts" ] }, { "cell_type": "markdown", "id": "79f16bc0", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Another thing we can do is import specific functions, values or classes that we might need instead of importing the entire module." ] }, { "cell_type": "code", "execution_count": null, "id": "2150cb86", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "from test import hello_world\n", "hello_world()\n", "# Note that here we didn't need begin with test." ] }, { "cell_type": "markdown", "id": "f24e00e4", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Lastly, if the project gets too big we might want to structure our\n", "files in subdirectories.\n", "\n", "You're free to do that, when you want to import them you'll need to\n", "go into the directories as if you had a module inside a module." ] }, { "cell_type": "code", "execution_count": null, "id": "a9e74bd9", "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "# Let's say that test.py is under \"libs/utils/\"\n", "# So libs/utils/test.py\n", "import libs.utils.test\n", "\n", "# or\n", "from lib.utils import test" ] }, { "cell_type": "markdown", "id": "secondary-recording", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "

Thank you!

\n", "\n", "
\"POuL
\n", "\n", "\"Creative\n", "\n", "

Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
\n", " Notebook source code available in this repo

\n", "\n", "

Mirko <mroik@poul.org>

\n" ] } ], "metadata": { "celltoolbar": "Slideshow", "interpreter": { "hash": "a12e2872633f051906de0dc7e50f36abb8c54899133a3bc5ba53c7d1324972a4" }, "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.10.4" }, "latex_envs": { "LaTeX_envs_menu_present": true, "autoclose": false, "autocomplete": true, "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 1, "hotkeys": { "equation": "Ctrl-E", "itemize": "Ctrl-I" }, "labels_anchors": false, "latex_user_defs": false, "report_style_numbering": false, "user_envs_cfg": false } }, "nbformat": 4, "nbformat_minor": 5 }