{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Algoritmusok Python nyelven\n", "\n", "## 1. Előadás, Bevezetés a programozásba és a Python nyelvbe.\n", "\n", "### 2020 február 13." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Technikai információk\n", "\n", "### Diák elérhetősége:\n", "[damasdigabor.web.elte.hu/teaching](https://damasdigabor.web.elte.hu/teaching)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Oktatók\n", "Előadás: Damásdi Gábor \n", " - Iroda: Déli 3.508\n", " - Fogadó óra: Csütörtök 10:00-12:00 \n", " \n", "Gyakorlat: Csanády Bálint \n", " - http://web.cs.elte.hu/~csbalint/oktatas.html\n", " - Iroda: Déli 3.604\n", "\n", "Gyakorlat: Varga Bálint \n", " - Iroda: Déli 3.605\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Előadás időpontja: 14:00-15:30\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tantárgy célja\n", "\n", "- **Matematikusok számára hasznos programozási tudás átadása**\n", "- Programozás általános folyamatának gyakorlása\n", "- Egy programozási nyelv (Python) alapjainak elsajátítása\n", "- Matematikusoknak hasznos programozási könyvtárak megismerése\n", "- Matematikai algoritmusok implementálása\n", "\n", "- Alapozás későbbi órákhoz(Algoritmusok tervezése és elemzése, Adatbányászat, Deep learning)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tematika\n", "Három fő témakör lesz:\n", " - Python alapjai\n", " - Hasznos könyvtárak\n", " - Matematikai algoritmusok" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Tananyag\n", "Az előadás és a gyakorlat anyaga mindig elérhető lesz a honlapon az óra kezdete előtt. [damasdigabor.web.elte.hu/teaching](https://damasdigabor.web.elte.hu/teaching)\n", "#### Források\n", "- [Ács Judit anyaga](https://github.com/bmeaut/python_nlp_2018_spring)\n", "- [SciPy tananyag](https://scipy-lectures.org/index.html)\n", "- [A Python nyelv hivatalos honlapja](https://www.python.org/)\n", "- Sok egyéb\n", "\n", "#### Tutorialok\n", " - [Runestone Academy](https://runestone.academy/runestone/books/published/thinkcspy/index.html)\n", " - [RealPython](https://realpython.com/)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Gyakorlat" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Követelmények\n", "- A gyakorlat elvégzése\n", "- Két beadandó feladat elkészítése \n", "- A második beadandó feladat bemutatása (viszgaidőszakban)\n", "- Mindkét feladat osztályozva lesz 1-től 5-ig. \n", "- A végső jegy, A és B osztályzat esetén: " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def vegsojegy(a,b):\n", " if a==1 or b==1:\n", " return 1\n", " if (a+b)%2==0:\n", " return (a+b)/2\n", " else:\n", " if b>a:\n", " return (a+b+1)/2\n", " else:\n", " return (a+b-1)/2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tehát a két jegy átlaga, és ha az nem egész, akkor a második beadandó jegye dönt. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Kérdések?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Az általunk használt programozási környezet\n", "\n", "### A programozás sokszínűsége\n", "- Python\n", "- Anaconda\n", "- Jupyter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jupyter\n", "\n", "\n", "- Jupyter - Egy web applikáció melyben olyan dokumentumokat hozhatunk létre, melyek élő kódot, képleteket, grafikonokat tartalmaznak. \n", "- A Jupyter fájlok kiterjesztése `.ipynb`\n", "- de konvertálható sok féle formátumba (HTML, PDF, LateX ...)\n", "- A tartalom cellákba van rendezve. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Cella típusok\n", "\n", "\n", "1. kód cella (Python/R/Lua/... kód) \n", "2. szöveg cella\n", "3. markdown cella: Markdown által formatált szöveg" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Kód cella" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Hello world\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Az utolsó parancs visszatérési értéke kiíródik. (Általában)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "2 + 3\n", "3 + 4" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Ez akár egy több értékből álló \"tuple\" is lehet. (Ahogy sok mindenre, a \"tuple\" szóra sem találtam jó fordítást. Talán \"többes\"?) " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "2 + 3, 3 + 4, \"hello \" + \"world\"" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Markdown cella\n", "\n", "**Ez itt félkövér**\n", "\n", "*Ez meg dőlt*\n", "\n", "| Ez | meg itt |\n", "| --- | --- |\n", "| egy | táblázat |\n", "\n", "Még a Latex is működik:\n", "\n", "$$\n", " \\frac{1}{n}\\sin x= \\frac{sinx}{n}= \\frac{sixn}{n}= six\\frac{n}{n}=six=6\n", "$$\n", "\n" ] }, { "cell_type": "raw", "metadata": {}, "source": [ "Ez meg csak egy unalmas szöveges cella" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "\n", "# Jupyter használata\n", "\n", "## Parancs mód és szerkesztési mód\n", "\n", "1. Parancs mód: utasítások végrehajtása a cellákon, a tartalmuk megváltoztatása nélkül. \n", " - A kijelölt cellák kékek\n", "2. Szerkesztési mód: Egy adott cella tartalmának módosítása. \n", " - A kijelölt cella zöld színű" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Váltás a módok között\n", "\n", "1. Esc: Szerkesztési -> Parancs\n", "2. Enter vagy dupla klikk: Parancs -> Szerkesztési" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Cella futtatása szerkesztési módban\n", "\n", "1. Ctrl + Enter: cella futtatása\n", "2. Shift + Enter: cella futtatása és ugrás a következőre\n", "3. Alt + Enter: cella futtatása és új cella beszúrása" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Hasznos shortcutok parancs módban\n", "- enter: cella szerkesztése\n", "- a/b : cella beszúrása a kijelölt cella alá/fölé (az above/below alapján)\n", "- m/y : cella típusának váltása: Markdown/Kód\n", "- dd : cella törlése" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Cella mágia (cell magic)\n", "\n", "Speciális parancsok, amik módosítják a cella működését." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time\n", "\n", "for x in range(1000000):\n", " pass" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%timeit\n", "\n", "x = 2" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "%%writefile hello.py\n", "\n", "print(\"Hello world\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!python hello.py" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Az elérhető mágiák listája:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%lsmagic" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "help()\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Mi történik a háttérben\n", "\n", "- minden notebook rendelkezik egy saját _Kernel_ -el (Python interpreter)\n", " - a kernel megszakítható vagy újraindítható a menüből (interrupt/restart) \n", " - **mindig** futtasd a `Kernel -> Restart & Run All` parancsot mielőtt beadnád a házifeladatot/beadandót, hogy megbizonyosodj róla, hogy minden rendben működik\n", "- minden cella egy közös namespace-ben él. \n", "- a cellák tetszőleges sorrendben futtathatóak \n", "- ha újra megnyitunk egy notebookot akkor alapvetően az inputok és az outputok maradnak meg. Az objektumok nem!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "print(\"Ez fut először\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Aztán meg ez. Figyeld a számot bal oldalt.\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`a` mutasson a 2 értékre." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`a` még mindig a 2-re mutat" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "## A cellák ki és bemenete később is elérhető. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "42" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "_" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "Utolsó előtti output:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "\"first\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "\"second\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "__" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "__" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "Utolsó előtti előtti:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "___" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "Az n. output is elérhető a `_output_count` változón keresztül. Ez csak akkor definiált ha az n. cellának volt kimenete.\n", "\n", "Itt egy módszer az összes elérhető output listázására. (A kódot majd később megérted)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "list(filter(lambda x: x.startswith('_') and \n", " x[1:].isdigit(), globals()))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "## A bemenet hasonlóan elérhető\n", "\n", "Előző input:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "_i" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "skip" } }, "source": [ "N. input:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "skip" } }, "outputs": [], "source": [ "_i2" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# A Python programozási nyelv" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## A Python története\n", "\n", "\n", "- A Python egy holland programozó hobbi projektjeként indult. (Guido van Rossum)\n", "- Python 1.0 1994\n", "- Python 2.0 2000\n", " - garbage collector\n", " - Unicode támogatás\n", "- Python 3.0 2008\n", " - nem kompatibilis a korábbi verziókkal!! \n", "- Python2 End-of-Life (EOL): January 1, 2020 \n", " - Ezért mi is csak a 3-al foglalkozunk\n", " - Frissítsétek a SAGE-t!" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true, "slideshow": { "slide_type": "slide" } }, "source": [ "## Python közösség és fejlesztés\n", "\n", "- Python Software Foundation nonprofit szervezet (Delaware, US)\n", "- egy erős közösség alakult ki, akik aktívan részt vesznek a fejlesztésben\n", "- nagy standard library\n", "- nagyon nagy third-party modul rendszer: PyPI (Python Package Index)\n", "- pip installer (pip = pip installs packages)\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "import antigravity" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python felhasználása\n", " - Web és Internet \n", " - Tudományos számítások \n", " - Tanítás" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# A Python általános tulajdonságai" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Interpretált és fordított (compiled) nyelvek. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "![interpreted](https://runestone.academy/runestone/books/published/thinkcspy/_images/interpret.png)\n", "![compiled](https://runestone.academy/runestone/books/published/thinkcspy/_images/compile.png)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Valójában sok nyelv használ vegyes stratégiát, így a python is. Mi főleg interpretált nyelvként fogjuk használni.\n", "###### Interpretált\n", " - gyors programírás\n", " - könnyű hibajavítás\n", " - általában lassabb\n", " - kód és program nincs szétválasztva" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Whitespaces\n", "\n", "- zárójelek helyett indentáció van és befolyásolja a program futását \n", "- nincsenek pontosvesszők " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n = 12\n", "if n % 2 == 0:\n", " print(\"n páros\")\n", "else:\n", " print(\"n páratlan\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Dinamikus típuskezelés \n", "\n", "- Típusellenőrzés futásidőben történik és nem fordítási időben." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n = 2\n", "print(type(n))\n", "\n", "n = 2.1\n", "print(type(n))\n", "\n", "n = \"foo\"\n", "print(type(n))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Értékadás (Assignment)\n", "\n", "Kicsit más mint a legtöbb nyelvben:\n", "\n", "- C++-ban `i = 2` kb azt jelenti, hogy a típussal rendelkező i változó megkapja a 2 érték másolatát.\n", "- Python `i = 2` kb azt jelenti hogy az i név kap egy referenciát egy egy numerikus objektumhoz, aminek az értéke 2. \n", "\n", "- mindig a jobb oldal értékelődik ki először, majd pedig a bal oldali név kap egy referenciát a jobb oldali értékhez\n", "\n", "Az `id` függvény visszaadja az objektum egyedi azonosító számát. (Miért lehet gond az id használatából?)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "i = 2\n", "print(id(i))\n", "\n", "i = 3\n", "print(id(i))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "i = \"elte\"\n", "print(id(i))\n", "\n", "s = i\n", "print(id(s) == id(i))\n", "\n", "old_id = id(s)\n", "s += \"matek\"\n", "print(id(s) == id(i))\n", "print(old_id == id(s))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = 2\n", "b = a\n", "print(id(a) == id(b))\n", "a += 1\n", "print(id(a) == id(b))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=25\n", "b=25\n", "a is b" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a=300\n", "b=300\n", "a is b" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "25 is 25" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "300 is 300" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Egyszerű utasítások" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## if, elif, else" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#n = int(input())\n", "n = 12\n", "\n", "if n < 0:\n", " print(\"N negatív\")\n", "elif n > 0:\n", " print(\"N pozitív\")\n", "else:\n", " print(\"N se nem negatív se nem pozitív\")" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Feltételes kifejezések\n", "\n", "- egysoros `if` utasítások is vannak \n", "- Az operátorok sorrendje viszont különbözik a C nyelvben megszokottaktól. C-ben így nézne ki a kód:\n", "\n", "~~~C\n", "int x = -2;\n", "int abs_x = x>=0 ? x : -x;\n", "~~~\n", "- Csak nagyon rövid kódok esetén ajánlott. \n", "\n", "Pythonban:\n", "\n", "` if else `" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "n = -2\n", "abs_n = n if n >= 0 else -n\n", "abs_n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Listák\n", "\n", "- leggyakrabban használt beépített adatszerkezet\n", "- operációk: indexelés, hossz, hozzáfűzés\n", "- részletesen szó lesz róla később " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "l = [] # empty list\n", "l.append(2)\n", "l.append(2)\n", "l.append(\"foo\")\n", "\n", "len(l), l" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "l[1] = \"bar\"\n", "l.extend([-1, True])\n", "len(l), l" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## for, range\n", "\n", "### lista iterálása" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for e in [\"foo\", \"bar\"]:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### Az egészek egy intervallumán való iterálás\n", "\n", "Így nézne ki C++-ban:\n", "~~~C++\n", "for (int i=0; i<5; i++)\n", " cout << i << endl;\n", "~~~\n", "\n", "A `range` mindig 0-val kezdődik!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Megadhatjuk a kezdőértéket:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "for i in range(2, 5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Megadhatjuk a növekedés értékét is. Ekkor viszont kötelező megadni a kezdőértéket is. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "-" } }, "outputs": [], "source": [ "for i in range(0, 10, 2):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## while" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "i = 0\n", "while i < 5:\n", " print(i)\n", " i += 1\n", "i" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Nincs `do...while` Pythonban." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## break és continue\n", "\n", "- `break`: ha korábban ki akarunk lépni egy ciklusból\n", "- `continue`: ha korábban szeretnénk a következő ciklus futásra lépni" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(10):\n", " if i % 2 == 0:\n", " continue\n", " print(i)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "subslide" } }, "outputs": [], "source": [ "for i in range(10):\n", " if i > 4:\n", " break\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Függvények\n", "\n", "Fontos, hogy ezek nem matematikai függvények. Például nem csak a bemenettől függ a függvényérték. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Függvény definíció\n", "\n", "Függvényeket a `def` kulcsszó segítségévek használhatunk:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def foo():\n", " print(\"én egy nagyon okos függvény vagyok\")\n", " \n", "foo()" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Függvény argumentumok, paraméterek \n", "\n", "1. pozíció szerinti (positional)\n", "2. kulcsszavas (named or keyword arguments)\n", "\n", "Először a pozíció szerintieket kell írni aztán a kulcsszavasokat" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def foo(arg1, arg2, arg3):\n", " print(\"arg1 \", arg1)\n", " print(\"arg2 \", arg2)\n", " print(\"arg3 \", arg3)\n", " \n", "foo(1, 2, \"asdfs\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "foo(1, arg3=2, arg2=29)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "arg3=4" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "## Alapértelmezett argumentum (Default arguments)\n", "\n", "- Az argumentumoknak lehet alapértelmezett értéke.\n", "- Először kell megadni azokat az argumentumokat, amiknek nincs alapértelmezett értéke." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "def foo(arg1, arg2, arg3=3):\n", " print(\"arg1 \", arg1)\n", " print(\"arg2 \", arg2)\n", " print(\"arg3 \", arg3)\n", "foo(1, 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alapértelmezett argumentumokat nem is kötelező megadni. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "foo(1, 2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "foo(arg1=1, arg3=33, arg2=222)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Tetszőleges kihagyható közülük. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def foo(arg1, arg2=2, arg3=3):\n", " print(\"arg1 \", arg1)\n", " print(\"arg2 \", arg2)\n", " print(\"arg3 \", arg3)\n", " \n", "foo(11, 33)\n", "print(\"\")\n", "foo(11, arg3=33)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "Emiatt rengeteg argumentumod lehet úgy is, hogy ez nem nehezíti meg a függvény használatát. Sok könyvtárban találunk olyan függvényeket, amiknek rengeteg argumentumunk van." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "Például a következő függvényt a `pandas` könyvtárban találjuk:\n", "\n", "~~~python\n", " pandas.read_csv(filepath_or_buffer, sep=', ', delimiter=None, header='infer', names=None, index_col=None, usecols=None, squeeze=False, prefix=None, mangle_dupe_cols=True, dtype=None, engine=None, converters=None, true_values=None, false_values=None, skipinitialspace=False, skiprows=None, nrows=None, na_values=None, keep_default_na=True, na_filter=True, verbose=False, skip_blank_lines=True, parse_dates=False, infer_datetime_format=False, keep_date_col=False, date_parser=None, dayfirst=False, iterator=False, chunksize=None, compression='infer', thousands=None, decimal=b'.', lineterminator=None, quotechar='\"', quoting=0, escapechar=None, comment=None, encoding=None, dialect=None, tupleize_cols=False, error_bad_lines=True, warn_bad_lines=True, skipfooter=0, skip_footer=0, doublequote=True, delim_whitespace=False, as_recarray=False, compact_ints=False, use_unsigned=False, low_memory=True, buffer_lines=None, memory_map=False, float_precision=None)\n", " ~~~" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Visszatérési érték, a `return` parancs\n", "\n", "- Egy függvénynek több visszatérési értéke is lehet\n", " - Ilyenkor az értékek egy tuple-be kerülnek.\n", "- ha a függvény futása úgy ér véget, hogy nem ér el `return` parancsot, a visszatérési érték automatikusan `none` lesz.\n", "- Egy üres `return` parancs is `None`-nal tér vissza. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def foo(n):\n", " if n < 0:\n", " return \"negative\"\n", " if 0 <= n < 10:\n", " return \"positive\", n\n", " # return None\n", " # return\n", "\n", "print(foo(-2))\n", "print(foo(3), type(foo(3)))\n", "print(foo(12))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import this" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random\n", "def make_maze(w = 16, h = 8):\n", " vis = [[0] * w + [1] for _ in range(h)] + [[1] * (w + 1)]\n", " ver = [[\"| \"] * w + ['|'] for _ in range(h)] + [[]]\n", " hor = [[\"+--\"] * w + ['+'] for _ in range(h + 1)]\n", " \n", " def walk(x, y):\n", " vis[y][x] = 1\n", " \n", " d = [(x - 1, y), (x, y + 1), (x + 1, y), (x, y - 1)]\n", " random.shuffle(d)\n", " for (xx, yy) in d:\n", " if vis[yy][xx]: continue\n", " if xx == x: hor[max(y, yy)][x] = \"+ \"\n", " if yy == y: ver[y][max(x, xx)] = \" \"\n", " walk(xx, yy)\n", " \n", " walk(random.randrange(w), random.randrange(h))\n", " \n", " s = \"\"\n", " for (a, b) in zip(hor, ver):\n", " s += ''.join(a + ['\\n'] + b + ['\\n'])\n", " return s " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\n", "print(make_maze())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "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.7.3" } }, "nbformat": 4, "nbformat_minor": 2 }