{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Algoritmusok Python nyelven\n", "\n", "## Hol is tartunk?\n", "- Python alapjai - ennek a vége felé\n", "- Hasznos könyvtárak\n", "- Matematikai algoritmusok\n", "\n", "## 5. Előadás: Kivételkezelés.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### String formatálás\n", "Több módszer van arra, hogy kényelmesebben generáljunk szöveges kimenetet. Az egyik a `format()` függvény. Ez egy stringből egy másik stringet készít úgy, hogy hogy a megadott paramétereket behelyettesíti a kapcsos zárójelek közé. A függvényekhez hasonlóan több féle paraméter átadás működik:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# default argumentumok\n", "print(\"Kedves {}, az ön egyenlege {}.\".format(\"Ádám\", 230.2346))\n", "\n", "# pozíció szerintei argumentumok \n", "print(\"Kedves {0}, az ön egyenlege {1}.\".format(\"Ádám\", 230.2346))\n", "\n", "# kucsszavas argumentumok\n", "print(\"Kedves {nev}, az ön egyenlege {egyen}.\".format(nev=\"Ádám\", egyen=230.2346))\n", "\n", "# vegyes\n", "print(\"Kedves {0}, az ön egyenlege {egyen}.\".format(\"Ádám\",egyen= 230.2346))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ha az adatok egy dicitionaryben vannak, azt is használhatjuk. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "person = {'eletkor': 23, 'nev': 'Ádam'}\n", "\n", "print(\"{p[nev]} életkora: {p[eletkor]}\".format(p=person))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "### string interpolation\n", "Egy másik lehetőség az f-stringek használata. (részletek: [PEP498](https://www.python.org/dev/peps/pep-0498/))\n", "- Hasonló az előzőhöz, de bármilyen változót használhatunk\n", "- Figyeld meg a `f` betűt a string előtt!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "szam1 = 12\n", "szam2 = 1\n", "nev=\"Paprika Jancsi\"\n", "print(f\"{nev}nak {szam1} almája és {szam2} kutyája van.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Feladvány\n", "Mi fog történni ha lefuttatjuk az alábbi kódot?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import random" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(20):\n", " print(1/random.randrange(10))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Kivételkezelés\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Néhány tipikus hiba:\n", "\n", "| Hiba neve | Tipikusan miért történt |\n", "| --- | --- |\n", "| IndexError: string index out of range | Egy stringnél túlindexeltél |\n", "| KeyError: 'some_text_here' | Egy dictionaryben olyan kulcsot használtál, ami nincs benne |\n", "| ModuleNotFoundError: No module named 'some_text_here' | Egy olyan modult próbáltál importálni, ami nem található |\n", "| NameError: name 'some_text_here' is not defined | Olyan változó nevet próbáltál kiértékelni, ami még nem mutat objektumra | \n", "| SyntaxError: can't assign to literal | Egy stringet próbáltál meg változó névként használni. Pl `'a'=3` |\n", "| SyntaxError: EOL while scanning string literal | Valamelyik stringet rosszul adtad meg. |\n", "| IndentationError: expected an indented block | Elrontottad az indentálást. |\n", "| SyntaxError: invalid syntax | Szintaktikai hiba. Gyakran azért van, mert lemarad a `:` valahonnan. |\n", "| TypeError: can only concatenate str (not \"int\") to str | Stringként kezeltél valamit, ami nem string. Pl egy számot. | \n", "| TypeError: 'str' object is not callable | Függvényként kezeltél egy stringet. Pl: `\"asd\"(5)` |\n", "| ValueError: invalid literal for int() with base 10: 'some_text_here' | Számmá próbáltál konvertálni egy szöveget, ami nem számokból áll. | \n", "| ZeroDivisionError: division by zero | Nullával osztottál |\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Futásidejő kivételek\n", "A futásidejű hibákat tudjuk futásidőben kezelni. Erre való a `try` és ` except` parancsok. Megadhatjuk, hogy hiba esetén mit tegyen a program, így nem fog rögtön elszállni. A `try` és az `except` közti részben figyel a program és ha olyan hibába ütközik, ami az `except` után áll, akkor végrehajtja a megadott parancsokat. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(10):\n", " try:\n", " print(1/random.randrange(10))\n", " except ZeroDivisionError as e:\n", " print(\"nullával osztottál, megszűnt az univerzum\")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "invalid literal for int() with base 10: 'Süsü'\n" ] } ], "source": [ "try:\n", " int(\"Süsü\")\n", "except ValueError as e:\n", " print(type(e))\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- több ágat is megadhatunk\n", "- a legspecifikusabbtól megyünk a legkevésbé specifikus felé\n", "- mi is megadhatunk hibákat" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "SÜSÜ\n", "ValueError\n" ] } ], "source": [ "try:\n", " eletkor = int(input())\n", " if eletkor < 0:\n", " raise Exception(\"Az életkor nem lehet negatív\")\n", "except ValueError as e:\n", " print(\"ValueError\")\n", "except Exception as e:\n", " print(\"Egy másik típusú kivétel: \"+ str(type(e)))\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Többféle kivételt tudunk együtt is kezelni " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Külön:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "TypeErrorba futottunk \n" ] } ], "source": [ "def age_printer(eletkor):\n", " kovetkezo_kor = eletkor + 1\n", " print(\"Jövő évben az életkorod:\" + kovetkezo_kor)\n", " \n", "try:\n", " your_age = input()\n", " your_age = int(your_age)\n", " age_printer(your_age)\n", "except ValueError:\n", " print(\"ValueErrorba futottunk\")\n", "except TypeError:\n", " print(\"TypeErrorba futottunk \")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Együtt:\n", " " ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "süs\n", "ValueErrorba futottunk\n" ] } ], "source": [ "def age_printer(eletkor):\n", " kovetkezo_kor = eletkor + 1\n", " print(\"Jövő évben az életkorod:\" + kovetkezo_kor)\n", " \n", "try:\n", " your_age = input()\n", " your_age = int(your_age)\n", " age_printer(your_age)\n", "except (ValueError, TypeError) as e:\n", " print(\"{}ba futottunk\".format(type(e).__name__))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### except típus nélkül\n", "\n", "- ha nem adjuk meg a kivétel típusát, akkor minden hibát elkapunk, de elveszítjük az információkat a hiábról\n", "- utolsónak kell megadni az üres except utasítást. " ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "süsü\n", "ValueError\n" ] } ], "source": [ "try:\n", " eletkor = int(input())\n", " if eletkor < 0:\n", " raise Exception(\"Az életkor nem lehet negatív\")\n", "except ValueError:\n", " print(\"ValueError\")\n", "except:\n", " print(\"Egy másik típusú kivétel.\")\n", " " ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "süsü\n", "Exception caught: \n" ] } ], "source": [ "try:\n", " age = int(input())\n", " if age < 0:\n", " raise Exception(\"Age cannot be negative\")\n", "except Exception as e:\n", " print(\"Exception caught: {}\".format(type(e)))\n", "except ValueError:\n", " print(\"ValueError caught\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### finally\n", "\n", "- A `finally` kód rész mindenképpen lefut, ha volt hiba, ha nem. " ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "Ez mindig lefut\n" ] } ], "source": [ "try:\n", " age = int(input())\n", "except Exception as e:\n", " print(type(e), e)\n", "finally:\n", " print(\"Ez mindig lefut\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### else\n", "\n", "- Az else utáni rész csak akkor fut le ha nem volt hiba" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "15\n", "Nem volt hiba\n", "Ez mindig lefut\n" ] } ], "source": [ "try:\n", " age = int(input())\n", "except ValueError as e:\n", " print(\"Exception\", e)\n", "else:\n", " print(\"Nem volt hiba\")\n", "finally:\n", " print(\"Ez mindig lefut\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Hibakezelés kibővitése\n", "- Magunk is megadhatjuk, hogy mikor dobjon kivételt a program.\n", "- Saját kivétel osztályt is definiálhatunk." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### `raise` kulcsszó\n", "\n", "- `raise` az utána megadott hibát dobja a program. " ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-10\n", "Egy másik típusú kivétel: \n", "Az életkor nem lehet negatív\n" ] } ], "source": [ "try:\n", " eletkor = int(input())\n", " if eletkor < 0:\n", " raise Exception(\"Az életkor nem lehet negatív\")\n", "except ValueError as e:\n", " print(\"ValueError\")\n", "except Exception as e:\n", " print(\"Egy másik típusú kivétel: \"+ str(type(e)))\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Hibák definiálása\n", "\n", "- Bármilyen típus, ami a az `Exception` (pontosabban a `BaseException`) osztály leszármazotja, használható hiba objektumként. " ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(Exception,)" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "ValueError.__bases__ # Így kérdezhetjük le, hogy egy osztálynak kik a szülő osztályai. " ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(BaseException,)" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Exception.__bases__" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(object,)" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "BaseException.__bases__" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "süsü\n", "Valami más hiba történt, a típusa , az üzenete invalid literal for int() with base 10: 'süsü'\n" ] } ], "source": [ "class NegativeAgeError(Exception):\n", " pass\n", "\n", "try:\n", " eletkor = int(input())\n", " if eletkor < 0:\n", " raise NegativeAgeError(\"Az életkor nem lehet negatív\")\n", "except NegativeAgeError as e:\n", " print(e)\n", "except Exception as e:\n", " print(\"Valami más hiba történt, a típusa {}, az üzenete {}\".format(type(e), e))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " Az ős osztály elkapja a leszármazotjait is. " ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-10\n", "Exception caught: \n" ] } ], "source": [ "try:\n", " age = int(input())\n", " if age < 0:\n", " raise NegativeAgeError(\"Age cannot be negative. Invalid age: {}\".format(age))\n", "except Exception as e:\n", " print(\"Exception caught: {}\".format(type(e)))\n", "except NegativeAgeError:\n", " print(\"ValueError caught\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A python a háttérben sokszor használja a kivételkezelést, ahogy az látni is fogjuk. " ] } ], "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.4" } }, "nbformat": 4, "nbformat_minor": 2 }