{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. előadás\n", "_Tartalom:_ String II. (replace, find, count, lower, stb), feltételek (if, elif, else), boolean logika\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Névadási konvenciók\n", "\n", "Eddig nem esett róla szó, de a Python változóknak, konstansokak stb. is vannak elnevezési irányelvei. Erről részletesen a `PEP 8 - Style Guide for Python Code`-ban lehet olvasni. A fontosabbak a következők: \n", "\n", "|Típus | Jelölés |\n", "|---|---|\n", "| konstansok | `IN_ALL_CAPS` |\n", "| változók | `snake_case` |\n", "| metódusok | `snake_case` |\n", "| függvények | inkább `snake_case`, de ritkávbaan használt és megengedett a `mixedCase` is |\n", "| osztályok | `StudlyCaps` (`CamelCaps`, `camelCase` nagybetűvel kezdődően) | " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Stringek" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Ez egy példa mondat, python funkciók szemléltetésére\n" ] } ], "source": [ "palindrom = \"Indul a görög aludni\"\n", "mondat = \"Ez egy példa mondat, python funkciók szemléltetésére\"\n", "abece = \"A,Á,B,C,Cs,D,Dz,Dzs,E,É,F,G,Gy,H,I,Í,J,K,L,Ly,M,N,Ny,O,Ó,Ö,Ő,P,R,S,Sz,T,Ty,U,Ú,Ü,Ű,V,Z,Zs\"\n", "csak_egyes_betuk = \"A,Á,B,C,D,E,É,F,G,H,I,Í,J,K,L,M,N,O,Ó,Ö,Ő,P,R,S,T,U,Ú,Ü,Ű,V,Z\"\n", "print(mondat)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'E'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat[0] # Karakterlánc első eleme" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'e'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat[-1] # Karakterlánc utolsó eleme" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "``` python\n", "mondat[0] = 'h' # Karakterlánc így nem módosítható :(\n", "```\n", "\n", "Erre válaszként a\n", "``` python\n", "TypeError: 'str' object does not support item assignment\n", "```\n", "üzenetet kapnánk. Ehelyett rendelkezésünkre állnak a string \"szeletelő jelölések\" (célszerűbb az angol terminológia: `slice notation`), a stringek összefűzése (pl. `+=`, `+`), a csere (`replace`), stb. műveletek.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Nézzünk példákat `slice notation`-ra." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ez egy példa'" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat[:12] # Első 12 karakter" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'példa mondat, python funkciók szemléltetésére'" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat[7:] # Karakterlánc vége, 7. eletől" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'szemléltetésére'" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat[-15:] # az utolsó 15 elem" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'példa mondat, python funkciók'" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat[7:36]" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "52" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "len(mondat) # Karakterlánc hossza" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ez egy példa mondat, python funkciók kipróbálására'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat[:-15] + ' kipróbálására'" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ez egy példa mondat, python funkciók szemléltetésére\n", "EZ EGY PÉLDA MONDAT, PYTHON FUNKCIÓK SZEMLÉLTETÉSÉRE\n" ] } ], "source": [ "print(mondat.lower())\n", "print(mondat.upper())" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'indula görög a ludnI'" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "palindrom[::-1]" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'erésétetlélmezs kóicknuf nohtyp ,tadnom adlép yge zE'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat[::-1]" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'A,Á,B,C,D,E,É,F,G,H,I,Í,J,K,L,M,N,O,Ó,Ö,Ő,P,R,S,T,U,Ú,Ü,Ű,V,Z'" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "csak_egyes_betuk # emlékeztetőül" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'AÁBCDEÉFGHIÍJKLMNOÓÖŐPRSTUÚÜŰVZ'" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "csak_egyes_betuk[::2]" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'A,Á,B,C,Cs,D,Dz,Dzs,E,É,F,G,Gy,H,I,Í,J,K,L,Ly,M,N,Ny,O,Ó,Ö,Ő,P,R,S,Sz,T,Ty,U,Ú,Ü,Ű,V,Z,Zs'" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abece # emlékeztetőül" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'A Á B C Cs D Dz Dzs E É F G Gy H I Í J K L Ly M N Ny O Ó Ö Ő P R S Sz T Ty U Ú Ü Ű V Z Zs'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abece.replace(\",\", \" \")" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ez egy teszt mondat, python funkciók szemléltetésére'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat.replace(\"példa\", \"teszt\")" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ez _X_gy példa mondat, python funkciók sz_X_mlélt_X_tésér_X_'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat.replace(\"e\", \"_X_\")" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Ez _X_gy példa mondat, python funkciók sz_X_mléltetésére'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat.replace(\"e\", \"_X_\", 2) # csak az első 2-t cseréli" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Összefoglalva a `Python slice notation` (magyarul talán ~szelet):\n", "``` python\n", "x[start:end] # az elemek starttól end-1-ig\n", "x[start:] # az elemek starttól végig\n", "x[:end] # az elemek az elejétől end-1-ig\n", "x[:] # az összes elem\n", "```\n", "Mindegyiket ki lehet egészíteni `step` értékkel, így minden `step`-edik elemet érhetjük el:\n", "``` python\n", "x[start:end:step]\n", "``` \n", "\n", "A legfontosabb észben tartani, hogy az `:end` érték az első olyan értéket képviseli, amely nincs a kiválasztott szeletben. Tehát a különbség a `end` és a `start` között a kiválasztott elemek számát jelenti (ha 1 lépés az alapértelmezett).\n", "\n", "A másik lehetőség az, hogy a kezdet vagy a vég negatív szám lehet, ami azt jelenti, hogy az elejétől kezdve a tömb végéig számít. Így:\n", "``` python\n", "x[-1] # az utolsó elem\n", "x[-2:] # az utolsó 2 elem\n", "x[:-2] # minden kivéve az utolsó 2 elem\n", "```\n", "Így már érhető, hogy a negatív érték lépésként is működik:\n", "``` python\n", "x[::-1] # minden elem, de megfordítva\n", "x[1::-1] # az első 2 elem megfordítva\n", "x[:-3:-1] # utolsó 2 elem megfordítva\n", "x[-3::-1] # utolsó 2 elemen kívül minden, megfordítva\n", "```\n", "\n", "_Fontos megjegyzés:_ ez nem csak stringeknél, hanem általánosságban tömböknél is működik" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "21" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat.find(\"python\") # a string helyét adja vissza" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "-1" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat.find(\"-----\") # illetve -1-et, ha nem találja" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "mondat.count(\"él\") # megszámoljuk az előfordulást (itt a \"példa\" és \"szemléltetésére\" szavakban találhatunk ilyet)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Összefűzésre használhatjuk a `+` vagy a `+=` operátort:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello világ\n" ] } ], "source": [ "str1 = \"Hello \"\n", "str2 = \"világ\"\n", "str3 = str1 + str2\n", "print(str3)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello világ\n" ] } ], "source": [ "str1 += str2\n", "print(str1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Stringek darabolására alkalmas a `split`, pl:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['A', 'Á', 'B', 'C', 'Cs', 'D', 'Dz', 'Dzs', 'E', 'É', 'F', 'G', 'Gy', 'H', 'I', 'Í', 'J', 'K', 'L', 'Ly', 'M', 'N', 'Ny', 'O', 'Ó', 'Ö', 'Ő', 'P', 'R', 'S', 'Sz', 'T', 'Ty', 'U', 'Ú', 'Ü', 'Ű', 'V', 'Z', 'Zs']\n" ] } ], "source": [ "print(abece.split(\",\"))" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Hello', 'világ']\n" ] } ], "source": [ "print(str1.split(\" \"))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Megjegyzés:_ a `split` listát készít, amiről még nem beszéltünk, de később fogunk. A visszatérési érték típusát akár ellenőrizhetjük is:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<class 'list'>\n" ] } ], "source": [ "print(type(abece.split(\",\")))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Input belvasása stringbe\n", "Pythonban ez szerencsére szintén egyszerűbb, mint a legtöbb nyelven." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Adjon meg tetszőleges szöveget: Hello\n", "A beolvasott szöveg *Hello* volt.\n" ] } ], "source": [ "szoveg = input(\"Adjon meg tetszőleges szöveget: \")\n", "print(\"A beolvasott szöveg \", szoveg, \" volt.\", sep = \"*\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Boolean logika\n", "\n", "Pythonban a legtöbb nyelvhez hasonló logikai műveleteink vannak.\n", "\n", "|`b`|`Not b`|\n", "|-|-|\n", "|`True`|`False`|\n", "|`False`|`True`|\n", "\n", "|`And`|`False`|`True`|\n", "|-|-|-|\n", "|**`False`**|`False`|`False`|\n", "|**`True`**|`False`|**`True`**|\n", "\n", "|`Or`|`False`|`True`|\n", "|-|-|-|\n", "|**`False`**|`False`|**`True`**|\n", "|**`True`**|**`True`**|**`True`**|" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "b1 = True\n", "b2 = False\n", "print(b1 is True)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b1 and b2" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b1 or b2" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "not b1" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "not b2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Feltételes utasítások (if, elif, else)\n", "Az `if`, `elif`, `else` vezérlési szerkezetek hasonlóan működnek más népszerű programozási nyelvek hasnoló szerkezeteihez. A vezérlési szerkezetek lényege, hogy bizonyos programrészlet végrehajtását feltételhez köthetjük.Ez egy logikai kifejezés, amelynek igaz (`True`) / hamis (`False`) voltától függ, hogy végrehajtódik-e az adott programrészlet.\n", "\n", "Igaz ág, `if`\n", "- Az a programrészlet, amely akkor hajtódik végre, ha a feltétel igaz volt.\n", "\n", "Igaz ág, ha ez előző feltétel nem volt igaz, `elif`\n", "- Az a programrészlet, amely akkor hajtódik végre, ha ez előző feltétel nem volt igaz, de ez a feltétel már igaz volt.\n", "\n", "Hamis ág, `else` ág\n", "- Ez akkor hajtódik végre, ha minden felette lévő feltétel hamis volt." ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Nem pozitív\n" ] } ], "source": [ "szam = -10\n", "\n", "if szam > 0:\n", " print(\"Pozitív\");\n", "else:\n", " print(\"Nem pozitív\");" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "n = 1\n", "n = 2\n", "n = 3\n", "n = 4\n", "n = 5\n", "Az n érteke pontosan hat\n", "n = 7\n", "Az n érteke pontosan nyolc\n", "n = 9\n" ] } ], "source": [ "for n in range(1, 10) :\n", " if n == 6:\n", " print(\"Az n érteke pontosan hat\")\n", " elif n == 8:\n", " print(\"Az n érteke pontosan nyolc\")\n", " else:\n", " print(\"n =\", n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### String bejárása ciklussal" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Itt a ch egy konkrét karakter nem pedig integer:\n", "h e l l o \n", "\n", "While ciklus és i (int) változó:\n", "h e l l o \n", "\n", "For ciklus és i (int) változó:\n", "h e l l o " ] } ], "source": [ "st = \"hello\"\n", "\n", "print(\"Itt a ch egy konkrét karakter nem pedig integer:\")\n", "for ch in st:\n", " print(ch, end = \" \")\n", "\n", "\n", "print(\"\\n\\nWhile ciklus és i (int) változó:\")\n", "i = 0\n", "while i < len(st):\n", " print(st[i], end = \" \")\n", " i += 1\n", " \n", " \n", "print(\"\\n\\nFor ciklus és i (int) változó:\")\n", "i = 0\n", "for _ in st:\n", " print(st[i], end = \" \")\n", " i += 1\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### String bejárása - comprehension" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['h', 'e', 'l', 'l', 'o']\n" ] } ], "source": [ "lst = [x for x in st]\n", "print(lst)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### _Used sources_ / Felhasznált források\n", "- [Shannon Turner: Python lessons repository](https://github.com/shannonturner/python-lessons) MIT license (c) Shannon Turner 2013-2014\n", "- [Siki Zoltán: Python mogyoróhéjban](http://www.agt.bme.hu/gis/python/python_oktato.pdf) GNU FDL license (c) Siki Zoltán" ] } ], "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.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }