{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Podstawy języka Python\n", "\n", " \n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The area of the triangle is 14.696938456699069\n" ] } ], "source": [ "sides = [5, 6, 7]\n", "\n", "# calculate the semi-perimeter\n", "s = sum(sides) / 2\n", "\n", "# calculate the area\n", "area = s\n", "for side in sides:\n", " area = area * (s - side)\n", "area = area ** 0.5\n", "\n", "print(f'The area of the triangle is {area}')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Zmienne" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "user1 = \"Alicja\"\n", "user2 = \"Bartosz\"\n", "user3 = \"Cecylia\"" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "user = \"t.dwojak\"\n", "mail_domain = \"amu.edu.pl\"\n", "\n", "email = user + '@' + mail_domain" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Zmienne\n", " * Nazwy zmiennych muszą być unikatowe.\n", " * Wielkość liter w nazwie zmiennych ma znaczenie.\n", " * Brak konieczności określenia typu." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Funkcja `print`" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello Python!\n" ] } ], "source": [ "print('Hello Python!')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello\n", "Python\n", "Hello Python !\n" ] } ], "source": [ "print('Hello') \n", "print('Python')\n", "print('Hello', 'Python', '!')" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "tomasz\n", "Użytkownik: tomasz\n" ] } ], "source": [ "user = 'tomasz'\n", "\n", "print(user)\n", "print('Użytkownik:', user)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Typy liczbowe\n", "\n", " * liczby całkowite: `int`\n", " * liczby rzeczywiste (zmiennoprzecinkowe): `float`" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "year = 2021\n", "pi = 3.14159" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Dziś jest 17 / 10 / 2021\n" ] } ], "source": [ "day = 17\n", "month = 10\n", "year = 2021\n", "\n", "print('Dziś jest', day, '/', month, '/', year)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Operacje arytmetyczne na liczbach:\n", " * dodawanie `+`, np. `2 + 3`\n", " * odejmowanie `-`, np. `10-9`\n", " * mnożenie `*`, np. `2.0 * 3.0`\n", " * dzielenie `/`, np. `3 / 4` ( == 0.75)\n", " * dzielenie całkowite `//`, np. `3 / 4` (0)\n", " * reszta z dzielenia `%`, np. `6 % 4` (2)\n", " * potęgowanie `**`, np. `10 ** 3` (1000)\n", " * nawiasy `(...)`" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Dziś upłynęło 36840 sekund.\n" ] } ], "source": [ "hour = 10\n", "minutes = 14\n", "seconds = ((60 * 60 * hour) + 60 * minutes)\n", "print(\"Dziś upłynęło\", seconds, \"sekund.\")" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n" ] } ], "source": [ "print( 1 + (20 // 3) + (4 * -5) % 6)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Operacje na zmiennej\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "x = 5\n", "\n", "x = x + 5\n", "\n", "x += 5" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Operatory\n", "\n", "Na przykład:\n", " * `+=`\n", " * `-=`\n", " * `/=`\n", " * `*=`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Konwersja typów" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-3\n", "3.0\n", "3\n" ] } ], "source": [ "pi_int = int(-3.14)\n", "print(pi_int)\n", "\n", "trzy = float(3)\n", "print(trzy)\n", "print(3)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6.28\n", "7.0\n" ] } ], "source": [ "x = '3.14'\n", "print(float(x) * 2)\n", "\n", "print(int('42') / 6)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Wartości logiczne\n", "\n", "W Pythonie są dwie wartości logiczne:\n", " * prawda (`True`),\n", " * fałsz (`False`).\n", "\n" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n" ] } ], "source": [ "x = False\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "* Wszystkie liczby różne od 0 mają wartość logiczną `True`.\n", "* Funkcja `bool` pozwala na konwersję do zmiennej logicznej.\n", "* Do negacji służy słowo kluczowe `not`." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wartość logiczna sumy: True\n", "Wartość logiczna zera to: False False\n", "True\n" ] } ], "source": [ "suma = 1 + 2\n", "\n", "print('Wartość logiczna sumy:', bool(suma))\n", "\n", "print('Wartość logiczna zera to: ', bool(0), bool(0.0))\n", "\n", "print(not False)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Operatory porównania\n", " * równość: `==`\n", " * różne: `!=`\n", " * większy: `>`\n", " * większy lub równy: `>=`\n", " * mniejszy: `<`\n", " * mniejszy lub równy `<=`\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n", "False\n" ] } ], "source": [ "user = 'bob'\n", "\n", "print(user == 'bob')\n", "\n", "print(3 < 7)\n", "\n", "print(0 != 0.0)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Do łączenia warunków logicznych służą dwa słowa kluczowe:\n", " * `and`: koniunkcja,\n", " * `or`: alternatywa." ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "True\n", "False\n" ] } ], "source": [ "print(True and True)\n", "print(True and False)\n", "print(True or False)\n", "print(False or False)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "W Pythonie istnieje jeszcze jeden typ wartości `None`, który oznacza brak wartości lub wartość pustą. " ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Wartość zmiennej: None\n", "Wartość logiczna zmiennej: False\n", "False\n" ] } ], "source": [ "user = None\n", "\n", "print('Wartość zmiennej:', user)\n", "print('Wartość logiczna zmiennej:', bool(user))\n", "print(user == False)\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Czas na pierwsze zadanie (1a i 1b)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Komentarze\n", " * Komentarze nie są interpretowane.\n", " * Komentarze w Pythonie zaczynają się od znaku '#'\n", " * Istnieją komentarze wielolinijkowe tagowane potrójnym \", czyli \"\"\" \"\"\"\n" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Bardzo ważna wiadomość\n", "Mamy piękną jesień.\n" ] } ], "source": [ "print(\"Bardzo ważna wiadomość\") # A to jest komentarz\n", "\"\"\"\n", "Komentarz\n", "wielo-\n", "linijkowy\n", "\"\"\"\n", "# print(\"Nie chcę być wydrukowanym\")\n", "print(\"Mamy piękną jesień.\")" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true, "slideshow": { "slide_type": "slide" } }, "source": [ "# Ciągi znaków (łańcuchy znakowe lub stringi)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ " * Możemy zdefiniować je na 3 sposoby: `''`, `\"\"` lub `str`.\n", " * Python preferuje pojedynczy cudzysłów.\n", " * Domyślne kodowanie to UTF-8." ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "user0 = 'John'\n", "user1 = \"Alice\"\n", "\n", "nun_users = str(2)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "It's fine.\n" ] } ], "source": [ "sent = \"It's fine.\"\n", "\n", "sent = 'It\\'s fine.'\n", "\n", "print(sent)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "rok: 2021\n", "False\n", "True\n" ] } ], "source": [ "var = str(2021)\n", "\n", "print('rok:', var)\n", "print(var == 2021)\n", "print(var == '2021')" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "# Pusty ciąg znaków\n", "x = ''" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Operacje na stringach\n", " * łączenie: `+`\n", " * powtórzenie: `*`" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "t.dwojak@amu.edu.pl\n" ] } ], "source": [ "username = 't.dwojak'\n", "domain = 'amu.edu.pl'\n", "email = username + '@' + domain\n", "print(email)" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "NOOOOOOOO!\n" ] } ], "source": [ "big_no = 'N' + 'O' * 8 + '!'\n", "print(big_no)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Dziś jest 2021/10/17\n" ] } ], "source": [ "date = str(2021) + '/' + str(10) + '/' + str(17)\n", "print('Dziś jest', date)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Operacje na stringach, cd.\n", " * długość łańcucha znakowego: `len`: np. `len('Ala') == 3`,\n", " * zamiana na małe litery `lower` lub na wielkie: `upper`,\n", " * zamiana liter: `replace`,\n", " * usuwanie białych znaków: `strip`,\n", " * sprawdzenie czy string rozpoczyna sie danych prefiksem: `startswith`." ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Słowo mickiewicz ma 10 liter.\n", "python\n", "mickiewicz\n", "2021\n", "True\n" ] } ], "source": [ "user = 'mickiewicz'\n", "print('Słowo', user, 'ma', len(user), 'liter.')\n", "\n", "print('Python'.lower())\n", "\n", "print(user.replace('T', 'R'))\n", "\n", "print(' 2021 '.strip())\n", "\n", "print(user.startswith('mic'))" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Słowo tomasz ma 6 liter.\n", "Słowo tomasz ma 6 liter.\n", "3\n" ] } ], "source": [ "user = 'tomasz'\n", "print('Słowo', user, 'ma', len(user), 'liter.')\n", "\n", "print(f'Słowo {user} ma {len(user)} liter.')\n", "\n", "\n", "print(len(str(123)))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Czas na zadanie (1c)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Listy (`list`)\n", " * Typ danych, który pozwala przechowywać wiele wartości.\n", " * Dostęp do poszczególnych elementów jest przez indeks elementu.\n", " * Indeksowanie zaczyna się od 0.\n", " * Funkcja `list` zamienia obiekt na listę." ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "x = [] # albo równoważnie\n", "y = list()\n", "oceny = [5, 4, 3, 5, 5]\n", "misc = [3.14, \"pi\", [\"pi\"], 3]\n", "\n", "list_0_9 = list(range(10))\n" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Liczba elementów: 4\n" ] } ], "source": [ "numbers = [6, 7, 9, 11]\n", "print('Liczba elementów:', len(numbers))" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n" ] } ], "source": [ "numbers = [6, 7, 9, 11]\n", "\n", "print(numbers[1])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Dodawanie i usuwanie elementów z listy\n", "\n", "Istnieją dwie metody:\n", " * `append(x)`: dodaje x na koniec listy\n", " * `extend(x)`: rozszerza listę o każdy element z x " ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['duck-duck-go', 'yahoo']\n" ] } ], "source": [ "engines = []\n", "\n", "engines.append('duck-duck-go')\n", "engines.append(\"yahoo\")\n", "print(engines)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['duck-duck-go', 'yahoo', 'google', 'bing']\n" ] } ], "source": [ "engines = ['duck-duck-go', 'yahoo']\n", "searches = [\"google\", 'bing']\n", "engines.extend(searches)\n", "print(engines)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['duck-duck-go', 'yahoo', 'google', 'bing']\n", "['duck-duck-go', 'yahoo']\n" ] } ], "source": [ "engines = ['duck-duck-go', 'yahoo']\n", "searches = [\"google\", 'bing']\n", "\n", "print(engines + searches)\n", "print(engines)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 3, 2, 3, 1, 2, 4]\n", "[1, 3, 3, 1, 2, 4]\n" ] } ], "source": [ "liczby = [1, 2, 3, 2, 3, 1, 2, 4]\n", "liczby.pop(1) # Domyślnie usuwa ostatni element z listy\n", "print(liczby)\n", "liczby.remove(2)\n", "print(liczby)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Inne przydatne metody:\n", " * `sort()`: sortuje listę rosnąco\n", " * `count(x)`: zlicza wystąpienia x w liście\n", " * `index(x)`: zwraca indeks pierwszego wystąpienia x" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "7\n", "[1, 1, 2, 2, 2, 3, 3, 4]\n" ] } ], "source": [ "liczby = [1,2,3,2,3,1,2,4]\n", "print(liczby.count(1))\n", "print(liczby.index(4))\n", "liczby.sort()\n", "print(liczby)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Indeksowanie" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "pierwszy element: 1\n", "ostatni element: 4\n", "5 pierwszych: [1, 3, 2, 3, 1]\n", "5 ostatnich [2, 3, 1, 2, 4]\n", "od drugiego, do piątego [3, 2, 3, 1]\n", "parzyste: [3, 3, 2]\n", "od tyłu [4, 2, 1, 3, 2, 3, 1]\n" ] } ], "source": [ "oceny = [1, 3, 2, 3, 1, 2, 4]\n", "print('pierwszy element:', oceny[0])\n", "print('ostatni element:', oceny[-1])\n", "print('5 pierwszych:', oceny[:5])\n", "print('5 ostatnich', oceny[-5:])\n", "print('od drugiego, do piątego', oceny[1:5])\n", "print('parzyste:', oceny[1:6:2])\n", "print('od tyłu', oceny[::-1])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Funkcje wbudowane\n", " * `len` - zwraca liczbę elementów listy.\n", " * `min` - zwraca wartość najmniejszgo elementu.\n", " * `max` - zwraca wartość największego elementu.\n", " * `sum` - zwraca sumę elementów.\n", " * `all` - zwraca `True`, gdy wszystkie elementy mają wartość `True`.\n", " * `any` - Zwraca `True`, gdy przynajmniej jeden element ma wartość `True`." ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Liczba elementów: 6\n", "Najmniejszy element: 0\n", "Największy element: 32\n", "Suma elementów: 74\n", "False\n", "True\n" ] } ], "source": [ "numbers = [4, 8, 12, 18, 0, 32]\n", "\n", "print('Liczba elementów:', len(numbers))\n", "print('Najmniejszy element:', min(numbers))\n", "print('Największy element:', max(numbers))\n", "print('Suma elementów:', sum(numbers))\n", "\n", "print(all(numbers))\n", "print(any(numbers))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Krotki (`tuple`)\n", "Podobnym typem do listy jest krotka (`tuple`):\n", " * definiuje się ją `()` lub `tuple()`,\n", " * nie można zmieniać krotki: nie można dodawać ani usuwać elementów,\n", " * nie można również zmieniać elementów*,\n", " * Indeksowanie identyczne jak w listach." ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "7" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "numbers = (4, 5, 7)\n", "\n", "numbers[2]" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "([0, 1], [1, 2], [3, 4, 5])\n" ] } ], "source": [ "users = ([0], [1, 2], [3, 4, 5])\n", "\n", "users[0].append(1)\n", "\n", "print(users)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Czas na zadanie (2a, 2b, 2c)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Słowniki (`dict`)\n", "Pewnego rodzaju uogólnieniem listy jest słownik (`dict`), który przechowuje dane jako `klucz`: `wartość`.\n", " * Słowniki pozwala na dodawanie, usuwanie i zmianę elementów.\n", " * Definiujemy jako `{}` lub `dict()`.\n", " * Klucze słownika muszą być niezmienialne (haszowalne)." ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "store = {}\n", "store = dict()\n", "s_oceny = {\n", " \"Justyna\": [5,5,5],\n", " \"Bartek\": [3,4,5],\n", " \"Ola\": [3,3,3]}\n", "s_oceny = dict([(\"Justyna\", [5,5,5]), (\"Bartek\", [3,4,5]), (\"Ola\", [3,3,3])])\n" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Justyna': [5, 5, 5], 'Bartek': [3, 4, 5], 'Ola': [3, 3, 3]}\n" ] } ], "source": [ "s_oceny = {\"Justyna\" : [5,5,5], \"Bartek\" : [3,4,5], \"Ola\": [3,3,3]}\n", "\n", "print(s_oceny)" ] }, { "cell_type": "code", "execution_count": 43, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[3, 4, 5]\n" ] } ], "source": [ "s_oceny = {\"Justyna\" : [5,5,5], \"Bartek\" : [3,4,5], \"Ola\": [3,3,3]}\n", "user = 'Bartek'\n", "print(s_oceny[user])" ] }, { "cell_type": "code", "execution_count": 44, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Justyna': [5, 5, 5], 'Bartek': [3, 4, 5], 'Ola': [3, 3, 3], 'Jan': [4, 4, 5]}\n" ] } ], "source": [ "s_oceny = {\"Justyna\" : [5,5,5], \"Bartek\" : [3,4,5], \"Ola\": [3,3,3]}\n", "\n", "s_oceny['Jan'] = [4, 4, 5]\n", "\n", "print(s_oceny)" ] }, { "cell_type": "code", "execution_count": 45, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Justyna': [5, 5, 5], 'Bartek': [3, 4, 5], 'Ola': [3, 3, 3, 1, 4]}\n" ] } ], "source": [ "s_oceny = {\"Justyna\" : [5,5,5], \"Bartek\" : [3,4,5], \"Ola\": [3,3,3]}\n", "\n", "s_oceny['Ola'].extend([1,4])\n", "\n", "print(s_oceny)" ] }, { "cell_type": "code", "execution_count": 46, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'Bartek': [3, 4, 5], 'Ola': [3, 3, 3]}\n" ] } ], "source": [ "s_oceny = {\"Justyna\" : [5,5,5], \"Bartek\" : [3,4,5], \"Ola\": [3,3,3]}\n", "\n", "del s_oceny[\"Justyna\"]\n", "\n", "print(s_oceny)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Operacje\n", " * Funkcja `len` zwraca liczbę elementów w słowniku.\n", " * Domyślnie operacje funkcji wykonywane są na kluczach.\n", " * metoda `keys()` zwraca klucze słownika, `values()` -- wartości, a `items()` -- pary (klucz, wartość). " ] }, { "cell_type": "code", "execution_count": 47, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "dict_keys([1, 3, 5, 11])\n", "dict_values([1, 2, 2, 3])\n", "dict_items([(1, 1), (3, 2), (5, 2), (11, 3)])\n" ] } ], "source": [ "binary_ones = {1: 1, 3: 2, 5: 2, 11: 3}\n", "max(binary_ones)\n", "\n", "print(binary_ones.keys())\n", "print(binary_ones.values())\n", "print(binary_ones.items())" ] }, { "cell_type": "code", "execution_count": 48, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n" ] } ], "source": [ "s_oceny = {\"Justyna\" : [5,5,5], \"Bartek\" : [3,4,5], \"Ola\": [3,4,3]}\n", "\n", "print(s_oceny[\"Ola\"][1])" ] }, { "cell_type": "code", "execution_count": 49, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "28\n" ] } ], "source": [ "users = {'ali99': {'name': 'Alice', 'age': 28}, 'bob90': {'name': 'Bob', 'age': 19}}\n", "\n", "print(users['ali99']['age'])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Czas na zadanie (3)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Instrukcja warunkowa (`if ... elif ... else`)\n", " * Pozwala na wykonanie (wciętego) fragmentu kodu w zależności od czy podany warunek jest spełniony:\n", " ```python\n", " if :\n", " instrukcja 1\n", " ...\n", " ```\n", " * `elif` pozwala na sprawdzenie kolejnego warunku.\n", " * `else` zostanie wykonany, gdy żaden warunek nie został spełniony.\n", " * Elementy `elif` i `else` nie są obowiązkowe.\n" ] }, { "cell_type": "code", "execution_count": 50, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "score_theory = 40\n", "score_practical = 45\n", "\n", "if score_theory + score_practical > 100:\n", " print(\"Zdobyłeś wystarczającą liczbę punktów.\")\n", " print('------')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Jedną ważną rzeczą jest to, że kod, który następuje po instrukcji `if` jest wcięty. Dzięki temu interpreter Pythona jest w stanie określić, które instrucje wchodzą w skład bloku warunkowego, a które nie." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Blok `else` jest opcjonalny i jest wykonywany, gdy warunek zawarty w instrukcji `if` nie jest spełniony. \n", "\n", "Na poniższym przykładnie mamy własnie taki przypadek. Warunek w `if`ie: `score_theory + score_practical > 100` nie jest spełniony, stąd wykonają się instrukcje z bloku `else`." ] }, { "cell_type": "code", "execution_count": 51, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Nie zdobyłeś wystarczającej liczby punktów.\n" ] } ], "source": [ "\n", "score_theory = 40\n", "score_practical = 45\n", "\n", "if score_theory + score_practical > 100:\n", " print(\"Zdobyłeś wystarczającą liczbę punktów.\")\n", " print('------')\n", "else:\n", " print(\"Nie zdobyłeś wystarczającej liczby punktów.\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Instrukcja warunkowa `if` pozwala na sprawdzenie wielu warunków -- służy do tego instrukcja `elif` (else if). Warunki są sprawdzane po kolei (od góry): jeżeli warunek zawarty po `if` nie jest spełniony, wtedy sprawdzany jest pierszy warunek z `elif`. Gdy żaden warunek nie jest spełniony, wtedy wykona się kod zawarty w bloku `else`." ] }, { "cell_type": "code", "execution_count": 52, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Będziesz mieć dodatkowy egzamin.\n" ] } ], "source": [ "score_theory = 40\n", "score_practical = 45\n", "\n", "if score_theory + score_practical > 100:\n", " print(\"Zdobyłeś wystarczającą liczbę punktów.\")\n", " print('------')\n", "elif score_theory + score_practical > 80:\n", " print(\"Będziesz mieć dodatkowy egzamin.\")\n", "else:\n", " print(\"Nie zdobyłeś wystarczającej liczby punktów.\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Nic nie stoi na przeszkodzie, żeby zagnieżdżać instrukcje warunkowe. W poniższym przykładzie widzimy, że druga instrukcja warunkowa jest zawarta w bloku po pierwszym `if`. " ] }, { "cell_type": "code", "execution_count": 53, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Zdobyłeś wystarczającą liczbę punktów.\n", "Wolisz teorię od praktyki\n" ] } ], "source": [ "score_theory = 55\n", "score_practical = 50\n", "\n", "if score_theory + score_practical > 100:\n", " print(\"Zdobyłeś wystarczającą liczbę punktów.\")\n", " if score_theory > score_practical:\n", " print('Wolisz teorię od praktyki')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Sprawdzenie obecności w kolekcji (`in`)\n", " * Słowo kluczowe `in` sprawdza czy dany element znajduje sie w kolekcji (np. lista, słownik).\n", " * Jego negacja to `not in`.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Python zawiera bardzo przydatny warunek `in`, który sprawdza czy dany element jest zawarty w danej kolecji, np. w liście lub w słowniku.\n", "\n", "W poniższym przykładzie sprawdzamy, czy liczba `67` jest zawarta w liście." ] }, { "cell_type": "code", "execution_count": 54, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "67 jest na liście.\n" ] } ], "source": [ "numbers = [67, 101, 303]\n", "\n", "if 67 in numbers:\n", " print('67 jest na liście.')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "W przypadku słowników (`dict`) sprawdzane jest czy istnieje w słowniku zadany klucz." ] }, { "cell_type": "code", "execution_count": 55, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Jabłko jest składnikiem.\n" ] } ], "source": [ "ingredients = {'apple': 4, 'lemon': 1, 'cherry': 14}\n", "\n", "if 'apple' in ingredients:\n", " print('Jabłko jest składnikiem.')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Możemy wykorzystać warunek `in` do sprawdzenie, czy dany tekst jest podciągiem w drugim." ] }, { "cell_type": "code", "execution_count": 56, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Yes!\n" ] } ], "source": [ "my_programming_lang = \"Python\"\n", "\n", "if \"Pyt\" in my_programming_lang:\n", " print('Yes!')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Żeby sprawdzić czy dany element __nie występuje__ możemy wykorzystać instrukcję `not in`." ] }, { "cell_type": "code", "execution_count": 57, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Omiń alejkę ze słodyczami.\n" ] } ], "source": [ "shopping_list = ['apples', 'bread', 'carrots']\n", "\n", "if 'cookies' not in shopping_list:\n", " print('Omiń alejkę ze słodyczami.')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Obiekty o wartości logicznej `False`\n", " * `0`\n", " * `0.0`\n", " * `[]`\n", " * `()`\n", " * `{}`\n", " * `None`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Bardzo często można spotkać się, gdy chcemy sprawdzić np. czy data lista jest pusta." ] }, { "cell_type": "code", "execution_count": 58, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "numbers = []\n", "\n", "if numbers:\n", " print('średnia liczb to:', sum(numbers) / len(numbers))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Czas na zadanie (4a, 4b)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Pętla typu ```for```\n", " * W Pythonie pętla *for* działa jak pętla *for each* w innych językach;\n", " ```python\n", " for zmienna in kolekcja:\n", " instukcja 1\n", " instrukcja 2\n", " ...\n", "```\n", " * Pętla pozwala na zapętlenie kodu, który znajduje w wciętym bloku.\n", " * Konstrukcja pętli jest następująca: po słowie `for` musimy podać nazwę zmiennej, która po kolei będzie przyjmować wartości z kolekcji, np. z listy. Pętla wykona się tyle razy, ile jest elementów w kolekcji.\n", " * Funkcja `range(n)` zwraca kolekcję liczb od `0` do `n-1`." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "To na co warto zwrócić uwagę to wcięcie. Kod, który ma zostać wykonany w pętli musi być wcięty." ] }, { "cell_type": "code", "execution_count": 59, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "element apples\n", "element cherries\n", "element pineapple\n" ] } ], "source": [ "ingredients = ['apples', 'cherries', 'pineapple']\n", "\n", "for ingredient in ingredients:\n", " print('element', ingredient)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Funkcja `range(n)` zwraca obiekt, który możemy przekonwertowąć na listę elementów od 0 do `n-1`." ] }, { "cell_type": "code", "execution_count": 60, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4]\n" ] } ], "source": [ "print(list(range(5)))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Bardzo często można spotkać poniżsżą kombinację funkcji `range` i `len` w kontekście pętli:" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apples\n", "cherries\n", "pineapple\n" ] } ], "source": [ "ingredients = ['apples', 'cherries', 'pineapple']\n", "\n", "for i in range(len(ingredients)):\n", " print(ingredients[i])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "W przypadku połączenia słownika i pętli, do zmiennej przypisywane są kolejne klucze ze słownika (przykład poniżej):" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "apple\n", "lemon\n", "cherry\n" ] } ], "source": [ "shopping_list = {'apple': 4, 'lemon': 1, 'cherry': 14}\n", "for item in shopping_list:\n", " print(item)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Jak wcześniej wspomniałem, metoda `items()` zwraca listę krotek: `(klucz, wartość)` i możemy wykorzystać to w pętli `for`. W tym przypadku musimy podać dwie zmienne:" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Buy 4 apples\n", "Buy 1 lemon\n", "Buy 14 cherries\n" ] } ], "source": [ "shopping_list = {'apples': 4, 'lemon': 1, 'cherries': 14}\n", "for item, number in shopping_list.items():\n", " print('Buy', number, item)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Możemy też iterować po stringu -- znak po znaku:" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "P\n", "y\n", "t\n", "h\n", "o\n", "n\n" ] } ], "source": [ "for char in 'Python':\n", " print(char)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Ćwiczenie: czy rozumiesz kod, który był na początku zajęć?" ] }, { "cell_type": "code", "execution_count": 65, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The area of the triangle is 14.696938456699069\n" ] } ], "source": [ "sides = [5, 6, 7]\n", "\n", "# calculate the semi-perimeter\n", "s = sum(sides) / 2\n", "\n", "# calculate the area\n", "area = s\n", "for side in sides:\n", " area = area * (s - side)\n", "area = area ** 0.5\n", "\n", "print(f'The area of the triangle is {area}')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Zagnieżdżając dwie pętle musimy pamiętać o dodatkowym wcięciu (tak jak w przykładzie poniżej)." ] }, { "cell_type": "code", "execution_count": 66, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "4\n", "3\n", "6\n", "9\n" ] } ], "source": [ "for i in range(3):\n", " for j in range(i+1):\n", " print((i + 1) * (j + 1))\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Czas na zadanie (5a, 5b, 5c i 5d)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Funkcje\n", " * Pozwalają na uniknięcie pisania tego samego kodu za każdym razem.\n", " * Pozwalają na wielokrotne wykorzystanie tego samego fragmentu kodu.\n", " * Zwiększają czytelność kodu.\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Definicja funkcji wygląda następująco:\n", " * najpierw piszemy słowo kłuczowe `def`, następnie nazwę funkcji, później w nawiasach okrągłych listę argumentów i kończymy dwukropkiem.\n", " * następnie wcięty blok to będzie kod funkcji." ] }, { "cell_type": "code", "execution_count": 67, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello!\n" ] } ], "source": [ "def hello():\n", " print('Hello!')\n", "\n", "hello()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "W powyższym przykładzie zdefiniowaliśmy funkcje `hello`, która nie przyjmuje żadnych argumentów. Wywołanie tej funkcji nie różni się od wywołań innych funkcji." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Słowo kluczowe `return` pozwala na zwrócenie wartości przez funkcję. Poniższa funkcja `get_five` zwraca liczbę pięć." ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n" ] } ], "source": [ "def get_five():\n", " return 5\n", "x = get_five()\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Argumenty funkcji umieszczamy w nawiasach:" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "```python\n", "def nazwa_funkcji(arg_1, arg_2, arg_3):\n", " instrukcja 1\n", " instrukcja 2\n", " return jakaś wartość\n", "```" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Przykład: poniższa funkcja `get_bigger` przyjmuje dwa argumenty: `a` i `b`, które rozdzielamy przecinkiem." ] }, { "cell_type": "code", "execution_count": 69, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "512\n" ] } ], "source": [ "def get_bigger(a, b):\n", " if a >= b:\n", " return a\n", " return b\n", "print(get_bigger(56, 512))" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8.0\n" ] } ], "source": [ "def srednia(lista):\n", " s = 0\n", " for item in lista:\n", " s += item\n", " return s / len(lista) \n", "\n", "print(srednia([7,8,9]))" ] }, { "cell_type": "code", "execution_count": 71, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "def count(lista, item):\n", " l = 0\n", " for i in lista:\n", " if i == item:\n", " l += 1\n", " return l" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Podczas wywoływania funkcji możemy dopowiedzieć, która argument jaką przyjmuje wartość." ] }, { "cell_type": "code", "execution_count": 72, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "count([5,5,5,4], 5)\n", "count(lista=[5,5,5,4], item=5)\n", "count(item=5, lista=[5,5,5,4])" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Czas na zadanie (7a i 7b)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Korzystanie z bibliotek" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Python posiada bogatą kolekcję bibliotek wbudowanych, tzn. które są dostarczone wraz z interpreterem.\n", "\n", "Żeby móc wykorzystać daną bibliotekę, to musimy ją zaimportować. Możemy to zrobić na dwa sposoby:\n", " * `import `. Dostęp do elementów jest poprzez `.nazwa_funkcji`.\n", " * `from import `: pozwala na dołączenie elementów biblioteki, tak jakby były częścią naszego skryptu.\n", " \n", "Przykłady:" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "posix\n", "Nazwa uzytkownika: kuba\n" ] } ], "source": [ "import os\n", "print(os.name)\n", "\n", "from os import getenv\n", "print('Nazwa uzytkownika: {}'.format(getenv(\"USER\")))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "1. Importujemy bibliotekę `os`. Dostęp do stałej jest \"przez kropkę\".\n", "2. Z biblioreki `os` importujemy funkcję `getenv` (zwraca wartości zmiennych systemowych)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Wystarczy, że zaimportujemy raz daną bibliotekę:" ] }, { "cell_type": "code", "execution_count": 74, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "-1.0" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import math\n", "math.cos(math.pi)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Jeżeli nazwa biblioteki jest za długa, to możemy użyć aliasu: `import as `:" ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " October 2021\n", "Mo Tu We Th Fr Sa Su\n", " 1 2 3\n", " 4 5 6 7 8 9 10\n", "11 12 13 14 15 16 17\n", "18 19 20 21 22 23 24\n", "25 26 27 28 29 30 31\n" ] } ], "source": [ "import calendar as cal\n", "cal.TextCalendar().prmonth(2021, 10)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "Ważniejsze biblioteki wbudowane:\n", " * `os`, `sys`: obsługa rzeczy dt. systemu i środowiska\n", " * `datetime`: wszystko co jest związane z czasem\n", " * `collections`: zawiera `Counter` i `defaultdict`" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Czas na zadanie (9a i 9b)." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Obsługa plików" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "fragment" } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": 76, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n" ] } ], "source": [ "zen_file = open('./zen_of_python.txt')\n", "zen_text = zen_file.read()\n", "print(zen_text[:95])\n", "\n", "zen_file.close()" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n" ] } ], "source": [ "zen_file = open('./zen_of_python.txt')\n", "\n", "zen_lines = list(zen_file)\n", "\n", "for line in zen_lines[:3]:\n", " print(line.strip())\n", "\n", "\n", "zen_file.close()" ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Beautiful is better than ugly.\n", "Explicit is better than implicit.\n", "Simple is better than complex.\n" ] } ], "source": [ "with open('./zen_of_python.txt') as zen_file:\n", " print(zen_file.read()[:95])" ] }, { "cell_type": "code", "execution_count": 79, "metadata": { "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "tree_per_sqkm = {\n", " \"Brazil\": 39542,\n", " \"Bulgaria\": 24987,\n", "}\n", "\n", "with open('./zalesienie.txt', mode='w') as plik:\n", " for country, num_trees in tree_per_sqkm.items():\n", " plik.write(country + ',' + str(num_trees) + '\\n')\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Podstawy Obiektowości\n", "\n", " - W Pythonie każda wartość jest obiektem, tzn. może zostać przypisana do zmiennej lub zostać\n", "przekazane do funkcji.\n", " - Każda wartość może mieć metody lub atrybuty." ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "11\n", "5\n" ] } ], "source": [ "from datetime import date\n", "\n", "today = date(2022, 11, 5)\n", "\n", "print(today.month) # atrybut\n", "print(today.weekday()) # metoda" ] } ], "metadata": { "celltoolbar": "Slideshow", "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.3" } }, "nbformat": 4, "nbformat_minor": 1 }