├── .gitignore ├── 01_tryb_interaktywny.md ├── 02_tekst.md ├── 03_help.md ├── 04_liczby.md ├── 05_bledy.md ├── 06_zmienne.md ├── 07_funkcje.md ├── 08_funkcja_print.md ├── 09_listy.md ├── 10_for.md ├── 11_krotki.md ├── 12_prawda_i_falsz.md ├── 13_slowniki.md ├── 14_none.md ├── 15_petla_while.md ├── 16_biblioteka_standardowa.md ├── 17_podsumowanie.md ├── README.md ├── d01_instalacja_pythona.md ├── d02_moduly.md ├── d03_input.md ├── d04_pliki.md ├── d05_zadania.md ├── d06_replit.md ├── english ├── 01_interactive_mode.md ├── 02_text.md ├── 03_help.md ├── 04_numbers.md ├── 05_errors.md ├── 06_variables.md ├── 07_functions.md ├── 08_print_function.md ├── 09_lists.md ├── 10_for.md ├── 11_tuples.md ├── 12_true_and_false.md ├── 13_dictionaries.md ├── 14_none.md ├── 15_while_loop.md ├── 16_standard_library.md ├── 17_summarizon.md ├── README.md ├── d01_python_installation.md ├── d02_modules.md ├── d03_input.md ├── d04_files.md ├── d05_tasks.md └── d06_replit.md └── obrazy ├── d01 ├── krok_1.png ├── krok_2.png ├── krok_3.png ├── krok_4.png ├── krok_5.jpg ├── krok_6.jpg └── krok_7.jpg └── d06 ├── krok_1.png ├── krok_2.png ├── krok_3.png └── krok_4.png /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | -------------------------------------------------------------------------------- /01_tryb_interaktywny.md: -------------------------------------------------------------------------------- 1 | # Rozdział 1. Tryb interaktywny 2 | 3 | Warsztaty zaczniemy od wyjaśnienia w jaki sposób będziemy programowali 4 | w Pythonie. 5 | 6 | ## Zaczynamy! 7 | 8 | ### Obsługa trybu interaktywnego na replit.com 9 | 10 | Jeśli posiadasz lokalnie zainstalowany interpreter Pythona, to możesz pominąć tę sekcję. 11 | 12 | Jeśli nie posiadasz zainstalowanego lokalnie interpretera Pythona, to otwórz 13 | [ten link](https://replit.com/languages/python3) w osobnej karcie przeglądarki. 14 | 15 | Jeżeli nie posiadasz konta na stronie `replit.com` to będziesz musiał/a je 16 | założyć. 17 | 18 | Przejdź do [tego poradnika aby założyć konto](d06_replit.md). 19 | 20 | Strona, którą widzisz, jest podzielona na dwie części: 21 | 22 | * z lewej strony, na białym tle, jest **edytor** tekstu, 23 | * z prawej strony widać konsolę (**Console**) oraz powłokę (**Shell**). 24 | 25 | ![Konsola i powłoka](obrazy/d06/krok_4.png) 26 | 27 | Edytor pozwala stworzyć cały kod programu, a następnie uruchomić go przez 28 | wciśnięcie przycisku "Run" (lub kombinacją klawiszy Ctrl + Enter). 29 | Jeżeli program wypisze jakiś tekst, to zobaczymy go w konsoli. 30 | 31 | Tryb interaktywny możemy aktywować przechodząc do zakładki **Shell** i uruchamiając 32 | polecenie `python`. Wtedy zobaczymy znak zachęty `>>>`, który oznacza, że 33 | możemy wpisać polecenie Pythona. 34 | 35 | ### Tryb interaktywny na własnym komputerze 36 | 37 | Tryb interaktywny możemy aktywować uruchamiając w terminalu polecenie `python`. 38 | Wtedy zobaczymy znak zachęty `>>>`, który oznacza, że 39 | możemy wpisać polecenie Pythona. 40 | 41 | ## Tryb interaktywny - jak działa? 42 | 43 | Gdy wpiszesz polecenie i wciśniesz Enter, tryb interaktywny wykonuje je i wypisuje jego wynik. 44 | W ten sposób możesz programować i od razu oglądać rezultaty. 45 | 46 | Praca z trybem interaktywnym jest wygodna, kiedy chcesz przetestować 47 | działanie pojedynczej operacji lub kiedy nie masz pewności jakie operacje 48 | chcesz wykonać. Jeżeli już wiesz jaki program chcesz napisać, wtedy 49 | łatwiej jest skorzystać z edytora. 50 | 51 | Jest jeszcze jedna ważna różnica między trybem interaktywnym a edytorem: 52 | tryb interaktywny po wykonaniu operacji zawsze wypisze jej wynik. Edytor 53 | zrobi to tylko jeżeli mu wydamy takie polecenie (poprzez instrukcję 54 | `print`, o której opowiemy później). 55 | 56 | Póki co będziemy korzystali z **trybu interaktywnego**, ponieważ będziemy 57 | uczyli się pojedynczych instrukcji i oglądali ich rezultaty. Nie bój się 58 | eksperymentować z różnymi wariantami tych poleceń. W najgorszym wypadku 59 | Python poinformuje Cię, że wpisanego kodu nie można wykonać. 60 | 61 | ## Znak zachęty 62 | 63 | W przykładach kodu, które znajdziesz w kolejnych rozdziałach, wielokrotnie 64 | zobaczysz ciąg znaków `>>>`. Jest to **znak zachęty**. Używamy go aby 65 | odróżnić tekst, który należy wpisać w trybie interaktywnym od tekstu, który 66 | interpreter Pythona sam wypisuje. Jeżeli w jakiejś linijce przykładu 67 | zobaczysz znak zachęty, to znaczy, że wszystko co następuje po znaku - aż 68 | do końca linii - należy wpisać w trybie interaktywnym, a następnie wcisnąć 69 | Enter. Samego znaku zachęty nie wpisujemy! 70 | 71 | ## :pushpin: Podsumowanie 72 | 73 | W tym rozdziale: 74 | 75 | * otworzyliśmy stronę `repl.it`, na której możemy programować w **edytorze** 76 | lub w **trybie interaktywnym** Pythona, 77 | * dowiedzieliśmy się jak wygląda **znak zachęty** i że pokazuje nam kod, 78 | który należy wpisać w trybie interaktywnym. 79 | 80 | --- 81 | 82 | :checkered_flag: Następny rozdział: [Tekst](./02_tekst.md) :checkered_flag: 83 | -------------------------------------------------------------------------------- /03_help.md: -------------------------------------------------------------------------------- 1 | # Rozdział 3. Funkcja `help` 2 | 3 | W tym rozdziale: 4 | 5 | * poznasz funkcję `help`. 6 | 7 | 8 | ## Pomoc w Pythonie 9 | 10 | Nawet najlepszy programista nigdy nie zapamięta wszystkich funkcji i metod, 11 | jakie oferuje Python. W trakcie tego szkolenia poznasz ich wiele, ale 12 | za kilka dni zapomnisz, jak działają. Nie przejmuj się, twórcy Pythona 13 | pomyśleli o tym... 14 | 15 | 16 | ## Dokumentacja metod w Pythonie 17 | 18 | Każda metoda zdefiniowana w Pythonie posiada **dokumentację**, która 19 | w kilku słowach opisuje jej działanie. Aby przeczytać tę dokumentację, 20 | należy wywołać funkcję `help`, na przykład: 21 | 22 | ```python 23 | >>> help('jakiś string'.find) 24 | Help on built-in function find: 25 | 26 | find(...) 27 | S.find(sub [,start [,end]]) -> int 28 | 29 | Return the lowest index in S where substring sub is found, 30 | such that sub is contained within S[start:end]. Optional 31 | arguments start and end are interpreted as in slice notation. 32 | 33 | Return -1 on failure. 34 | ``` 35 | 36 | Dokumentacja nie zawsze jest pisana prostym językiem, ale nie zrażaj się. 37 | Warto oswajać się z nią od samego początku. Przeczytaj powyższy fragment 38 | jeszcze raz, a zaraz wyjaśnimy, co dokładnie oznaczają poszczególne części. 39 | 40 | Dokumentacja pokazuje wszystkie argumenty jakie przyjmuje dana metoda. 41 | Tę informację zawiera linia "S.find(sub [,start [,end]])". 42 | Dalej dokumentacja informuje jakiego typu wynik jest zwracany oraz w skrócie 43 | wyjaśnia, co ta metoda robi. Dzięki temu możemy ją sobie bardzo szybko 44 | przypomnieć. 45 | 46 | Zwróć uwagę, że w tym przykładzie nie otworzyliśmy nawiasu przy nazwie 47 | metody `find`, a co za tym idzie, nie podaliśmy jej żadnych argumentów. 48 | W ten sposób zamiast wywołać tę metodę, po prostu posłużyliśmy się jej 49 | nazwą. Kiedy przekażemy taką nazwę do funkcji `help`, Python pokaże nam 50 | dokumentację danej metody. 51 | 52 | :snake: Użyj funkcji `help` i przeczytaj dokumentację do metod `replace` 53 | i `count` oraz do funkcji `len`. 54 | 55 | 56 | ## :pushpin: Podsumowanie 57 | 58 | W tym rozdziale: 59 | 60 | * poznaliśmy funkcję `help` i dowiedzieliśmy się, że warto jej używać 61 | wtedy, kiedy nie rozumiemy jakiejś metody lub nie pamiętamy jak działa. 62 | 63 | 64 | --- 65 | 66 | :checkered_flag: Następny rozdział: [Liczby](./04_liczby.md) :checkered_flag: 67 | -------------------------------------------------------------------------------- /04_liczby.md: -------------------------------------------------------------------------------- 1 | # Rozdział 4. Liczby 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się czym jest `integer` oraz `float`, 6 | * nauczysz się wykonywać operacje arytmetyczne na liczbach. 7 | 8 | ## Liczby całkowite 9 | 10 | Aby zdefiniować liczbę całkowitą (**integer**) po prostu wpisz ją nie stawiając 11 | spacji między cyframi: 12 | 13 | ```python 14 | >>> 2017 15 | 2017 16 | ``` 17 | 18 | Liczby możemy dodawać i odejmować: 19 | 20 | ```python 21 | >>> 20 + 17 22 | 37 23 | >>> 2 + 0 + 1 + 7 24 | 10 25 | >>> 20 - 17 26 | 3 27 | >>> 20 - 1 - 7 28 | 12 29 | ``` 30 | 31 | ...mnożyć i dzielić: 32 | 33 | ```python 34 | >>> 20 * 17 35 | 340 36 | >>> 20 / 17 37 | 1.1764705882352942 38 | ``` 39 | 40 | ...dzielić bez reszty: 41 | 42 | ```python 43 | >>> 20 // 17 44 | 1 45 | ``` 46 | 47 | ...podnosić do potęgi: 48 | 49 | ```python 50 | >>> 201 ** 7 51 | 13254776280841401 52 | ``` 53 | 54 | ...albo sprawdzić resztę z dzielenia (ang. modulo): 55 | 56 | ```python 57 | >>> 20 % 17 58 | 3 59 | ``` 60 | 61 | Wszystkie te operacje możemy dowolnie łączyć: 62 | 63 | ```python 64 | >>> 20 / 2 + 17 * 3 65 | 61 66 | ``` 67 | 68 | Jeżeli chcemy mieć większą kontrolę na kolejnością wykonywania działań, możemy 69 | posłużyć się nawiasami okrągłymi: 70 | 71 | ```python 72 | >>> (20 * (2 + 17)) / 3 73 | 126 74 | ``` 75 | 76 | :snake: Oblicz następujące wartości: 77 | 78 | * suma dzisiejszego dnia, numeru miesiąca i roku, 79 | * wynik dzielenia roku Twojego urodzenia przez sumę dnia i miesiąca, 80 | w których się urodziłaś. 81 | 82 | 83 | ## Liczby rzeczywiste 84 | 85 | Wszystkie powyższe operacje możemy wykonywać również na liczbach rzeczywistych 86 | (**float**, zmiennoprzecinkowych): 87 | 88 | ```python 89 | >>> 2.5 * 2.0 90 | 5.0 91 | >>> 7 / 2.0 92 | 3.5 93 | >>> 6.7 + 0.3 - 2.5 94 | 4.5 95 | >>> 1.0 / 3 96 | 0.3333333333333333 97 | ``` 98 | 99 | :snake: Czy wiesz kiedy Python zwróci *float* a kiedy *integer*? Upewnij się, 100 | sprawdź różne kombinacje liczb i działań. 101 | 102 | 103 | ## Operatory i ich kolejność 104 | 105 | Znaki, których używamy do wykonywania działań (`+`, `*` itd.) nazywamy **operatorami**. 106 | Każdy operator ma swój priorytet, co oznacza, że jeżeli w jednym działaniu użytych 107 | jest kilka różnych operatorów (np. `2 + 1 * 3`), to Python najpierw obliczy te, które 108 | mają wyższy priorytet. 109 | 110 | Przykładowo, w takim działaniu: 111 | 112 | ```python 113 | >>> 4 + 10 * 6 114 | ``` 115 | 116 | najpierw zostanie wykonane mnożenie, a dopiero potem dodawanie, ponieważ 117 | operator `*` ma wyższy priorytet niż `+`, czyli rezultatem będzie `64`. 118 | 119 | Poniższa tabelka prezentuje operatory oraz ich znaczenie. Kolejność wierszy odpowiada 120 | priorytetowi, czyli na samej górze są operatory z najwyższym priorytetem, a na dole 121 | z najniższym. 122 | 123 | Operatory | Znaczenie 124 | --------- | --------- 125 | `**` | Potęgowanie 126 | `*`, `/`, `//`, `%` | Mnożenie, dzielenie, dzielenie całkowite, modulo 127 | `+`, `-` | Dodawanie, odejmowanie 128 | 129 | ## :pushpin: Podsumowanie 130 | 131 | W tym rozdziale: 132 | 133 | * dowiedzieliśmy się, jak definiować liczby całkowite (**integer**) 134 | i zmiennoprzecinkowe (**float**), 135 | * poznaliśmy najważniejsze **operatory** matematyczne i ich priorytety. 136 | 137 | --- 138 | 139 | :checkered_flag: Następny rozdział: [Błędy](./05_bledy.md) :checkered_flag: 140 | -------------------------------------------------------------------------------- /05_bledy.md: -------------------------------------------------------------------------------- 1 | # Rozdział 5. Błędy 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się, czym są **wyjątki**, 6 | * nauczysz się czytać komunikaty o błędach. 7 | 8 | ## Wyjątki 9 | 10 | Tworząc programy nigdy nie jesteśmy w stanie przewidzieć wszystkich 11 | sytuacji, jakie mogą się wydarzyć. Czasami użytkownik poda dane, których 12 | nasz program nie jest w stanie przetworzyć: na przykład spodziewaliśmy 13 | się liczby, a dostaliśmy tekst. Innym razem pomylimy się i wywołamy 14 | na jakimś obiekcie metodę, która nie istnieje. Na każdą tego typu sytuację 15 | Python zareaguje zgłaszając błąd. 16 | 17 | Kiedy to się zdarzy, działanie programu zostanie przerwane i wyświetlony 18 | zostanie komunikat, dzięki któremu dowiemy się, na czym polegała nasza 19 | pomyłka, co pozwoli nam poprawić kod programu, żeby uniknąć tego samego 20 | problemu w przyszłości. 21 | 22 | Słowa "błąd" czy "problem" są bardzo ogólne, ponieważ mogą dotyczyć również 23 | rzeczy, na które jako programiści nie mamy wpływu. Dlatego posługujemy się 24 | terminem **wyjątek**, który określa tylko te wypadki, jakie język 25 | programowania może obsłużyć - czyli takie, na jakie nasze programy mogą 26 | zareagować. 27 | 28 | W praktyce wyjątek to sytuacja, w której Python zatrzymał wykonywanie 29 | programu, ponieważ napotkał *wyjątkową* sytuację, której sam nie potrafił 30 | obsłużyć. Mówi się, że program **rzucił wyjątek**. Kiedy tak się stanie, 31 | rolą programisty jest dostosowanie programu w taki sposób, aby 32 | w przyszłości podobna sytuacja nie skutkowała zatrzymaniem. 33 | 34 | Czym są wyjątkowe sytuacje o których wspomnieliśmy? Może to być próba 35 | wykonania operacji, której Python nie potrafi zrealizować, na przykład 36 | dodanie liczby do tekstu. Albo błąd "za mało miejsca na dysku twardym" 37 | podczas zapisywania jakiegoś pliku. Nie sposób wymienić wszystkie takie 38 | możliwości - z czasem poznasz zestaw najczęściej występujących wyjątków 39 | i nauczysz się przewidywać, jakie operacje mogły je spowodować. 40 | 41 | ## Jak czytać komunikaty o błędach i wyjątkach 42 | 43 | Spróbujmy wywołać błąd i zobaczyć, jak zachowa się nasz program. 44 | Pamiętasz, jak informowaliśmy o tym, że stringi wstawiamy w pojedynczy lub 45 | podwójny cudzysłów, ale musisz pamiętać, żeby cudzysłów zamykający był taki 46 | sam jak otwierający? Zróbmy eksperyment i sprawdźmy, co się stanie, kiedy 47 | złamiemy tę zasadę. 48 | 49 | ```python 50 | >>> 'ala ma kota" 51 | File "", line 1 52 | 'ala ma kota" 53 | ^ 54 | SyntaxError: unterminated string literal (detected at line 1) 55 | ``` 56 | 57 | Jak widzisz, zamiast wyświetlić tę frazę, Python zgłosił błąd. 58 | Przeczytajmy go linijka po linijce. 59 | 60 | * Na samym początku widzimy zawsze wiadomość 61 | `Traceback (most recent call last):`. Słowem "traceback" określa się listę 62 | operacji, których wykonanie spowodowało błąd. W tym przypadku wykonana 63 | została tylko jedna operacja (zwrócenie wpisanej frazy), ale w przyszłości 64 | spotkasz się z sytuacjami, w których wyjątek czy błąd został rzucony wskutek 65 | wykonania całego ciągu poleceń. Python zawsze pokazuje cały traceback, aby 66 | programista mógł zrozumieć, co poszło nie tak. Tekst `most recent call last` 67 | informuje, że ostatnia operacja na liście została wykonana najpóźniej 68 | spośród wszystkich. 69 | * `File "python", line 1` to właśnie traceback. W naszym 70 | przypadku jest to tylko jedna linijka. Widzimy tutaj opis miejsca, 71 | w którym wystąpił błąd. 72 | * Ostatnia linijka zawiera najważniejszą informację, czyli bezpośrednią 73 | przyczynę błędu. Zaczyna się od typu wyjątku. W tym przypadku to 74 | `SyntaxError` - błąd składni. Typ błędu można rozumieć jako kategorię: nie 75 | mówi on, czego dokładnie dotyczył błąd, ale pozwala zaklasyfikować różne 76 | wyjątki, aby łatwiej było je zrozumieć. `SyntaxError` oznacza błąd w składni 77 | ciągu znaków, które powinny po sobie następować zgodnie ze składnią języka. 78 | Rozszyfrujmy jeszcze skrót EOL - end of line, koniec linii. Po takim 79 | komunikacie wiemy trochę więcej na temat tego, któremu fragmentowi naszego kodu się 80 | dokładnie przyjrzeć. Odkrycie powodu, dlaczego nasz kod nie działa, wciąż może 81 | być niełatwą zagadką. 82 | 83 | Tworząc bardziej zaawansowane programy spotkasz się z jeszcze dłuższymi 84 | komunikatami o błędach. Nie zniechęcaj się tym: każdy wyjątek sprowadza 85 | się do tylko jednej niepoprawnej operacji, a traceback, nieważne jak długi, 86 | pomoże Ci zlokalizować przyczynę niepowodzenia. Jeżeli mimo wszystko nie 87 | będziesz w stanie zrozumieć, dlaczego Twój program przestał działać, wklej 88 | ostatnią linijkę komunikatu do wyszukiwarki internetowej. Jest bardzo 89 | możliwe, że ktoś już kiedyś spotkał się z takim problemem i znalazł 90 | rozwiązanie. 91 | 92 | Często, wyjątki są sposobem komunikacji pomiędzy programem, który piszesz a 93 | użytkownikiem, który go uruchamia. Dzięki nim użytkownik dowiaduje się, co 94 | poszło nie tak. Poniżej możemy zobaczyć jak pomiędzy wersjami Pythona zmienił się 95 | komunikat o tym samym błędzie. 96 | W wersji 3.7 Python zwracał błąd `SyntaxError: EOL while scanning string literal`, 97 | i bez wiedzy co w żargonie programistycznym oznacza EOL, trudno byłoby zrozumieć 98 | co jest problemem w przekazanym stringu. 99 | W wersji 3.12 Python zwraca błąd 100 | `SyntaxError: unterminated string literal (detected at line 1)`, 101 | co jest bardziej zrozumiałe, bo informuje nas, że po prostu przekazany string nie został 102 | zamknięty. 103 | 104 | ```python 105 | # Python w wersji 3.7 106 | >>> 'ala ma kota" 107 | Traceback (most recent call last): 108 | File "python", line 1 109 | 'ala ma kota" 110 | ^ 111 | SyntaxError: EOL while scanning string literal 112 | 113 | # Python w wersji 3.12 114 | >>> 'ala ma kota" 115 | File "python", line 1 116 | 'ala ma kota" 117 | ^ 118 | SyntaxError: unterminated string literal (detected at line 1) 119 | ``` 120 | 121 | :snake: Wywołaj błędy i przeczytaj ze zrozumieniem wyjątki spowodowane 122 | następującymi operacjami: dzielenie przez zero; wywołanie metody lower() na 123 | dowolnej cyfrze; wywołanie na dowolnym stringu metody, która nie istnieje; 124 | wykonanie kodu, który nie ma sensu (możesz wpisać losowy ciąg znaków). 125 | 126 | ## :pushpin: Podsumowanie 127 | 128 | W tym rozdziale: 129 | 130 | * dowiedzieliśmy się, czym jest **wyjątek** i jak czytać jego treść. 131 | 132 | --- 133 | 134 | :checkered_flag: Następny rozdział: [Zmienne](./06_zmienne.md) :checkered_flag: 135 | -------------------------------------------------------------------------------- /06_zmienne.md: -------------------------------------------------------------------------------- 1 | # Rozdział 6. Zmienne 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się czym jest **zmienna**, jak ją zdefiniować i jak jej używać. 6 | 7 | 8 | ## Zmienna 9 | 10 | W poprzednich rozdziałach wykonywaliśmy różne operacje: definiowaliśmy 11 | stringi, mnożyliśmy liczby itd. Każda z tych operacji zwracała jakiś 12 | wynik, który od razu był wypisywany na ekran. Tekst i liczby, które 13 | w ten sposób tworzyliśmy, trafiały do pamięci komputera tylko na chwilę 14 | i zaraz po wyświetleniu były z niej usuwane. W związku z tym w kolejnych 15 | operacjach nie mogliśmy wykorzystać wyników z operacji poprzednich. 16 | 17 | Aby poradzić sobie z problemem przechowania wyniku operacji, używamy 18 | **zmiennych**. Zamiast tłumaczyć jak działają zmienne, najlepiej popatrzeć 19 | na przykład: 20 | 21 | ```python 22 | >>> x = 7 23 | >>> x 24 | 7 25 | >>> 5 + x 26 | 12 27 | ``` 28 | 29 | Przeanalizujmy co wydarzyło się w powyższym przykładzie. Na początku 30 | **zdefiniowaliśmy zmienną**, czyli przypisaliśmy wynik jakiejś operacji 31 | do nazwy. W tym przypadku operacją jest po prostu definicja liczby `7`, 32 | natomiast nazwą jest `x`. Od tego momentu mogliśmy używać **zmiennej** 33 | `x` w kolejnych operacjach. Jeżeli po prostu wpiszemy jej nazwę, wtedy 34 | otrzymamy jej **wartość**. Możemy też posłużyć się nią w innej operacji, 35 | na przykład dodając ją do innej liczby. 36 | 37 | Definiując zmienne możemy posługiwać się innymi zmiennymi: 38 | 39 | ```python 40 | >>> a = 10 41 | >>> b = 5 42 | >>> c = a + b 43 | >>> c 44 | 15 45 | ``` 46 | 47 | Oczywiście w realnym przypadku zmienne nazywamy w taki sposób, aby 48 | mówiły nam co oznaczają: 49 | 50 | ```python 51 | >>> cena_netto = 120 52 | >>> podatek_vat = cena_netto * 0.23 53 | >>> cena_brutto = cena_netto + podatek_vat 54 | >>> cena_brutto 55 | 147.6 56 | ``` 57 | 58 | 59 | ## Przypisanie 60 | 61 | Operację `zmienna = wartość` nazywamy **przypisaniem**. W wyniku 62 | przypisania Python tworzy *zmienną*, która otrzymuje *wartość*. Jeżeli 63 | wartość jest operacją (np. dodawaniem), to najpierw jest obliczany jej 64 | rezultat, a następnie zostaje on przypisany do zmiennej. 65 | 66 | 67 | ## Nazwy zmiennych 68 | 69 | Tworząc zmienną musimy najpierw wymyślić dla niej nazwę. Przede wszystkim 70 | powinna ona wprost mówić jakie jest znaczenie zmiennej. Dzięki temu, tak 71 | jak w powyższym przykładzie, będziemy mogli z łatwością zrozumieć kod 72 | programu. 73 | 74 | Poza tym Python narzuca kilka ograniczeń na znaki, jakich możemy użyć 75 | w nazwie zmiennej. Dozwolone znaki to: 76 | 77 | * litery od `a` do `z` (małe) oraz od `A` do `Z` (wielkie), 78 | * cyfry, 79 | * znak `_` (podkreślenie). 80 | 81 | Wszystkie pozostałe znaki są niedozwolone. Co istotne, nazwa nie może 82 | zaczynać się od cyfry! 83 | 84 | :snake: Utwórz zmienne `imie` oraz `nazwisko`, przypisz do nich swoje imię 85 | i nazwisko. Następnie na ich podstawie utwórz zmienną `imie_nazwisko`, 86 | która będzie zawierała imię i nazwisko oddzielone spacją. 87 | 88 | :snake: Zobacz co się stanie, kiedy spróbujesz stworzyć zmienną, której 89 | nazwa zaczyna się od cyfry. 90 | 91 | 92 | ## Zmiana wartości zmiennej 93 | 94 | W każdej chwili możemy zmienić wartość zmiennej: 95 | 96 | ```python 97 | >>> x = 'Ala ma kota' 98 | >>> x 99 | 'ala ma kota' 100 | >>> x = 'kot ma Alę' 101 | >>> x 102 | 'kot ma Alę' 103 | >>> x = x + '.' 104 | >>> x 105 | 'kot ma Alę.' 106 | ``` 107 | 108 | ## Zmienne i metody 109 | 110 | W poprzednich rozdziałach wywoływaliśmy różne metody, np. `find` lub 111 | `title`. Zwróć uwagę, że metody, które możesz wykonać bezpośrednio 112 | na obiekcie, możesz też wykonać na zmiennej: 113 | 114 | ```python 115 | >>> imie_nazwisko = 'jan kowalski' 116 | >>> imie_nazwisko 117 | 'jan kowalski' 118 | >>> imie_nazwisko.title() 119 | 'Jan Kowalski' 120 | >>> imie_nazwisko 121 | 'jan kowalski' 122 | >>> imie_nazwisko = imie_nazwisko.title() 123 | >>> imie_nazwisko 124 | 'Jan Kowalski' 125 | ``` 126 | 127 | 128 | ## :pushpin: Podsumowanie 129 | 130 | W tym rozdziale: 131 | 132 | * dowiedzieliśmy się czym jest zmienna, jak ją definiować i jak jej używać. 133 | 134 | --- 135 | 136 | :checkered_flag: Następny rozdział: [Funkcje](./07_funkcje.md) :checkered_flag: 137 | -------------------------------------------------------------------------------- /07_funkcje.md: -------------------------------------------------------------------------------- 1 | # Rozdział 7. Funkcje 2 | 3 | W tym rozdziale: 4 | 5 | * nauczysz się definiować **funkcje**. 6 | 7 | 8 | ## Czym jest funkcja 9 | 10 | Dotychczas dowiedzieliśmy się czym jest *string*, *integer* i *float*, oraz 11 | jak używać zmiennych do przechowywania wartości pomiędzy operacjami. 12 | Dzięki temu możemy napisać program, który wykona jakieś operacje na danych, 13 | na przykład przetworzy tekst, lub coś obliczy, a następnie wypisze wynik 14 | na ekran. Im bardziej zaawansowane problemy będziemy chcieli rozwiązać 15 | naszym programem, tym bardziej skomplikowany będzie jego kod. 16 | 17 | Jednym ze sposobów na pisanie bardziej zrozumiałego kodu jest definiowanie 18 | funkcji. **Funkcja** to wydzielony zbiór instrukcji, który możemy 19 | wielokrotnie wykonać w programie. **Definicja funkcji** to sposób w jaki 20 | opisujemy, które operacje mają być zawarte w funkcji. 21 | 22 | Przykładowo, poniższa funkcja zwraca liczbę podniesioną do kwadratu: 23 | 24 | ```python 25 | def kwadrat(liczba): 26 | wynik = liczba ** 2 27 | return wynik 28 | ``` 29 | 30 | Linijka zaczynająca się od słowa `def` to **nagłówek funkcji**. Składa się 31 | z następujących elementów: 32 | 33 | * słowo `def`, 34 | * **nazwa** funkcji (w tym przykładzie to `kwadrat`), 35 | * **lista argumentów** ujęta w nawiasy okrągłe (tutaj mamy jeden argument 36 | `liczba`, ale możemy ich podać wiele, oddzielając je przecinkami), 37 | * dwukropek. 38 | 39 | Zwróć uwagę na spacje! W całym nagłówku odstęp jest tylko między słowem 40 | `def` a nazwą funkcji. Gdyby funkcja miała wiele argumentów oddzielonych 41 | przecinkami, to moglibyśmy wstawić spacje obok przecinków, aby poprawić 42 | czytelność kodu. Poza tymi dwoma przypadkami, w nagłówku nie powinno więcej 43 | spacji. 44 | 45 | W kolejnych linijkach po nagłówku mamy **ciało funkcji**. Są to po prostu 46 | instrukcje, które zostaną wykonane kiedy użyjemy funkcji. W powyższym 47 | przykładzie ciało zawiera dwie operacje: podniesienie do kwadratu wartości 48 | zmiennej `liczba` i przypisanie jej do zmiennej `wynik`, oraz zwrócenie 49 | wartości zmiennej `wynik`. **Zwrócenie** to określenie jaka wartość ma 50 | być wynikiem danej funkcji. Służy do tego słowo `return`. Jeżeli wpiszemy 51 | po nim nazwę zmiennej, to jej wartość będzie wynikiem. Możemy także 52 | zwrócić rezultat nie przypisując do wcześniej do zmiennej: 53 | 54 | ```python 55 | def kwadrat(liczba): 56 | return liczba ** 2 57 | ``` 58 | 59 | 60 | ## Praca z edytorem 61 | 62 | Zanim zdefiniujesz swoją pierwszą funkcję, zatrzymajmy się na chwilę. Jak 63 | dotąd wszystkie operacje wykonywaliśmy w trybie interaktywnym, gdzie 64 | wpisywaliśmy kod, wciskaliśmy Enter i dostawaliśmy wynik. Gdy zaczniemy 65 | pracować z funkcjami takie podejście może okazać się uciążliwe. Dużo 66 | wygodniej będzie teraz przejść do **edytora**. 67 | 68 | Od tej pory każdy przykład, który nie będzie zaczynał się od `>>>` należy 69 | rozumieć jako kod wpisany w edytorze i uruchomiony przyciskiem "run". 70 | 71 | 72 | ## Definicja i wywołanie funkcji 73 | 74 | Przepisz teraz do edytora kod funkcji zapisany poniżej. Zwróć szczególną 75 | uwagę na **wcięcia**. Każda linijka ciała funkcji musi zaczynać się od 76 | wcięcia. Co istotne, wszystkie te wcięcia **muszą mieć taką samą 77 | szerokość**. Oznacza to, że jeżeli w pierwszej linijce zrobisz wcięcie 78 | na dwie spacje, to wszystkie pozostałe linijki aż do końca funkcji też 79 | muszą mieć wcięcie na dwie spacje. Jak zauważysz, edytor sam zrobi 80 | wcięcie kiedy po wpisaniu nagłówka wciśniesz Enter. Jeżeli by tego nie 81 | zrobił, wtedy najłatwiej jest robić wcięcia klawiszem Tab. 82 | 83 | ```python 84 | def kwadrat(liczba): 85 | wynik = liczba ** 2 86 | return wynik 87 | ``` 88 | 89 | Wciśnij teraz przycisk "run". Jeżeli w oknie trybu interaktywnego nie 90 | zauważysz żadnego błędu, będzie to oznaczało, że funkcja została prawidłowo 91 | zdefiniowana. Teraz możemy ja wywołać w trybie interaktywnym: 92 | 93 | ```python 94 | >>> kwadrat(5) 95 | 25 96 | >>> kwadrat(3) + kwadrat(1) 97 | 10 98 | ``` 99 | 100 | Jak widzisz, aby wywołać funkcję, wystarczy wpisać jej nazwę, po czym 101 | w nawiasach wpisać wartość argumentu. Jeżeli argumentów jest wiele, to 102 | należy je oddzielić przecinkami. 103 | 104 | :snake: Zdefiniuj funkcję o nazwie `pole_kola`, która przyjmuje argument 105 | `promien` i zwraca wartość równania `3.14 * (promien ** 2)`. Wywołaj ją 106 | w oknie trybu interaktywnego. 107 | 108 | :snake: Wywołaj funkcję `pole_kola` bez argumentu: `pole_kola()`. Czy 109 | rozumiesz treść wyjątku jaki został rzucony? 110 | 111 | :snake: Wywołaj funkcję `pole_kola` z dwoma argumentami: `pole_kola(2, 3)`. 112 | Porównaj treść wyjątku do błędu z poprzedniego zadania. 113 | 114 | 115 | ## Argumenty 116 | 117 | Funkcja nie musi posiadać żadnych argumentów, w takim wypadku nawiasy 118 | w nagłówku zostawiamy puste: 119 | 120 | ```python 121 | def funkcja_bez_argumentow(): 122 | return 123 123 | ``` 124 | 125 | Jak już wspomnieliśmy, funkcje mogą przyjmować więcej niż jeden argument: 126 | 127 | ```python 128 | def suma(a, b): 129 | return a + b 130 | 131 | 132 | def osoba(imie, nazwisko, tytul): 133 | imie_nazwisko = imie + ' ' + nazwisko 134 | return tytul + ' ' + imie_nazwisko.title() 135 | ``` 136 | 137 | Takie funkcje wywołujemy podobnie jak te z jednym argumentem: 138 | 139 | ```python 140 | >>> funkcja_bez_argumentow() 141 | 123 142 | >>> suma(100, 45) 143 | 145 144 | >>> suma(100, -20) 145 | 80 146 | >>> osoba('jan', 'KOWALSKI', 'doktor') 147 | 'doktor Jan Kowalski' 148 | ``` 149 | 150 | :snake: Napisz funkcję `cena_brutto`, która przyjmuje argumenty 151 | `cena_netto` oraz `vat` i zwraca wartość brutto obliczoną według wzoru 152 | `netto * (1 + vat)`. 153 | 154 | :snake: Napisz funkcję `imie_nazwisko`, która przyjmuje argumenty `imie` 155 | oraz `nazwisko` i zwraca stringa z imieniem i nazwiskiem oddzielonymi 156 | spacją. Upewnij się, że każde słowo w stringu zaczyna się od wielkiej 157 | litery (użyj metody `title`). Następnie napisz funkcję `lubi`, 158 | z argumentami `imie`, `nazwisko` oraz `co` i wywołana w ten sposób: 159 | `lubi('jan', 'kowalski', 'KALAFIORY')` zwróci stringa 160 | `'Jan Kowalski lubi kalafiory'`. Pisząc funkcję `lubi` użyj funkcji 161 | `imie_nazwisko`. 162 | 163 | 164 | ## Funkcje wbudowane 165 | 166 | Poza funkcjami, które sami możemy zdefiniować, istnieją funkcje, które 167 | zawsze są dostępne w interpreterze Pythona. Nazywamy je **funkcjami 168 | wbudowanymi**. Przykładem jest funkcja `len`, o której mówiliśmy w jednym 169 | z poprzednich rozdziałów: 170 | 171 | ```python 172 | >>> len('python') 173 | 6 174 | ``` 175 | 176 | Poza tym mamy jeszcze [67 innych funkcji wbudowanych](https://docs.python.org/3/library/functions.html). 177 | Część z nich poznasz w kolejnych rozdziałach, a kilka innych opisaliśmy 178 | poniżej. 179 | 180 | ### `str` 181 | 182 | Przyjmuje jako argument dowolny obiekt i zwraca jego reprezentację jako 183 | string: 184 | 185 | ```python 186 | >>> str(2017) 187 | '2017' 188 | ``` 189 | 190 | :snake: Zamień na string liczbę ujemną. 191 | 192 | :snake: Zobacz co się stanie, jeżeli jako argument przekażesz do `str` 193 | tekst. 194 | 195 | 196 | ### `int` 197 | 198 | Przyjmuje jako argument dowolny obiekt i zamienia go na integer: 199 | 200 | ```python 201 | >>> int(' 123 ') 202 | 123 203 | ``` 204 | 205 | :snake: Zobacz co się stanie, gdy przekażesz do funkcji `int` liczbę 206 | z częścią ułamkową (float), np. `3.14`. 207 | 208 | :snake: Zobacz co się stanie, jeśli przekażesz do `int` stringa, w którym 209 | nie ma żadnej liczby. 210 | 211 | :snake: Zobacz co się stanie, kiedy przekażesz do `int` stringa, w którym 212 | są zarówno litery jak i cyfry, np. `Ala ma 2 koty`. 213 | 214 | 215 | ### `float` 216 | 217 | Przyjmuje jako argument dowolny obiekt i zamienia go na float: 218 | 219 | ```python 220 | >>> float('3.14') 221 | 3.14 222 | ``` 223 | 224 | :snake: Zobacz jak zachowa się funkcja `float`, gdy wywołasz ją z: 225 | integerem, stringiem z samymi literami, stringiem z samymi cyframi. 226 | 227 | 228 | ## :pushpin: Podsumowanie 229 | 230 | W tym rozdziale: 231 | 232 | * dowiedzieliśmy się czym jest funkcja, jak ją definiować i wywoływać, 233 | * poznaliśmy funkcje wbudowane `str`, `int` oraz `float`. 234 | 235 | --- 236 | 237 | :checkered_flag: Następny rozdział: [Funkcja `print`](./08_funkcja_print.md) :checkered_flag: 238 | -------------------------------------------------------------------------------- /08_funkcja_print.md: -------------------------------------------------------------------------------- 1 | # Rozdział 8. Funkcja `print` 2 | 3 | W tym rozdziale: 4 | 5 | * poznasz funkcję wbudowaną `print`. 6 | 7 | 8 | ## Wypisywanie tekstu na ekran 9 | 10 | Gdy korzystaliśmy z trybu interaktywnego i chcieliśmy wypisać coś na ekran, 11 | wystarczyło wpisać jakieś wyrażenie i wcisnąć Enter: 12 | 13 | ```python 14 | >>> 2 + 2 15 | 4 16 | >>> x = 'PyLadies' 17 | >>> x 18 | 'PyLadies' 19 | ``` 20 | 21 | Mogliśmy tak robić, ponieważ w ten sposób działa tryb interaktywny: 22 | wykonuje operację i wyświetla jej wynik. Jednak zazwyczaj programy 23 | w Pythonie są bardziej złożone i często zdarza się, że chcemy zobaczyć 24 | więcej niż tylko wynik ostatniej operacji. Na przykład gdy piszemy program, 25 | który przetwarza plik tekstowy i chcemy, żeby dla każdej linijki tekstu 26 | wypisał coś na ekran. W takim wypadku z pomocą przychodzi funkcja 27 | wbudowana `print`. 28 | 29 | 30 | ## `print` 31 | 32 | Funkcja ta przyjmuje dowolną liczbę argumentów i wypisuje wszystkie na 33 | ekran, oddzielając je spacjami: 34 | 35 | ```python 36 | >>> print(2017) 37 | 2017 38 | >>> print('PyCon PL', 2017) 39 | PyCon PL 2017 40 | ``` 41 | 42 | Do `print` można przekazywać również zmienne: 43 | 44 | ```python 45 | >>> temperatura = 24 46 | >>> print('Temperatura:', temperatura, 'stopnie Celsjusza') 47 | Temperatura: 24 stopnie Celsjusza 48 | ``` 49 | 50 | :snake: Napisz funkcję, która przyjmuje argument `rok_urodzenia`, wypisuje 51 | tekst `Masz X lat`, gdzie `X` to wiek w roku 2017, oraz zwraca ten wiek. 52 | 53 | 54 | ## Formatowanie stringów 55 | 56 | W tym miejscu warto wrócić do stringów i opowiedzieć o jeszcze jednej, 57 | bardzo przydatnej metodzie: `format`. Służy ona do **formatowania 58 | stringów**, czyli "wstawiania" do nich wartości zmiennych. Spójrz na 59 | poniższy przykład: 60 | 61 | ```python 62 | >>> 'ala {} kota'.format('ma') 63 | 'ala ma kota' 64 | ``` 65 | 66 | Jak widzisz, wywołanie metody `format` spowodowało, że para znaków `{}` 67 | została zastąpiona argumentami funkcji. W podobny sposób możemy wstawić 68 | dowolną liczbę i typ obiektów: 69 | 70 | ```python 71 | >>> szerokosc = 110 72 | >>> wysokosc = 50.5 73 | >>> jednostka = 'mm' 74 | >>> '{}x{} {}'.format(szerokosc, wysokosc, jednostka) 75 | '110x50.5 mm' 76 | ``` 77 | 78 | Możliwości metody `format` nie kończą się na zwykłym wstawianiu wartości 79 | do stringa. [Dokumentacja Pythona](https://docs.python.org/3.12/library/string.html#formatspec) 80 | w szczegółach opisuje tę funkcję. Warto przyjrzeć się choćby przykładom, 81 | które tam zamieszczono. 82 | 83 | :snake: Zobacz co się stanie, jeżeli liczba argumentów metody `format` 84 | będzie __mniejsza__ niż liczba wystąpień `{}` w stringu. 85 | 86 | 87 | ## :pushpin: Podsumowanie 88 | 89 | W tym rozdziale: 90 | 91 | * poznaliśmy funkcję `print` oraz metodę `format`. 92 | 93 | --- 94 | 95 | :checkered_flag: Następny rozdział: [Listy](./09_listy.md) :checkered_flag: 96 | 97 | -------------------------------------------------------------------------------- /09_listy.md: -------------------------------------------------------------------------------- 1 | # Rozdział 9. Listy 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się czym są **listy**, 6 | * poznasz metody `append`, `pop`, `count`, `remove` i `index`, 7 | * poznasz funkcje wbudowane `sum`, `max`, `min` oraz `sorted`. 8 | 9 | ## Lista 10 | 11 | Listy towarzyszą nam na co dzień. Kiedy chcemy posłuchać muzyki, 12 | odtwarzamy playlistę. W sklepie spoglądamy na listę zakupów. Szukając 13 | czegoś w internecie, przeglądamy listę wyników. 14 | 15 | Jeśli pomyślimy o tym dłużej, zauważymy, że w formie listy można 16 | zaprezentować wiele innych zjawisk i rzeczy: zbiór książek w bibliotece, 17 | wydarzenia z jakiegoś okresu, zadania do wykonania, kolejka samochodów 18 | na stacji benzynowej itd. Lista to w programowaniu bardzo ważne pojęcie, 19 | bo pozwala w prosty sposób opisać zbiór obiektów, które są ułożone w jakimś 20 | porządku: alfabetycznym, chronologicznym, losowym etc. Listy w Pythonie 21 | to potężne, a równocześnie proste narzędzie, którego używa się niemal na 22 | każdym kroku. 23 | 24 | Aby zdefiniować listę, należy wypisać obiekty (stringi, integery) 25 | oddzielone przecinkami w nawiasach kwadratowych: 26 | 27 | ```python 28 | >>> kolory = ['niebieski', 'czerwony', 'zielony', 'czarny'] 29 | >>> print(kolory) 30 | ['niebieski', 'czerwony', 'zielony', 'czarny'] 31 | ``` 32 | 33 | W taki sposób definiujemy pustą listę: 34 | 35 | ```python 36 | >>> lista = [] 37 | >>> print(lista) 38 | [] 39 | ``` 40 | 41 | Możemy odwołać się do poszczególnych elementów listy wpisując jej nazwę 42 | po czym, w nawiasach kwadratowych, numer elementu (**indeks**). Pamiętaj, 43 | że numeracja zaczyna się od zera! 44 | 45 | ```python 46 | >>> print(kolory[0]) 47 | niebieski 48 | >>> print(kolory[2]) 49 | zielony 50 | ``` 51 | 52 | Chcąc otrzymać ostatni element na liście, możemy użyć indeksu `-1`: 53 | 54 | ```python 55 | >>> print(kolory[-1]) 56 | czarny 57 | ``` 58 | 59 | **Indeksy ujemne** to sposób na dostęp do elementów listy "od końca": 60 | 61 | ```python 62 | >>> print(kolory[-2]) 63 | zielony 64 | >>> print(kolory[-3]) 65 | czerwony 66 | ``` 67 | 68 | Możemy dowolnie mieszać typy elementów na liście: 69 | 70 | ```python 71 | >>> liczby = ['jeden', 2, 'trzy', 4, 5] 72 | ``` 73 | 74 | Lista może zawierać w sobie również inne listy: 75 | 76 | ```python 77 | >>> odcienie_czerwieni = ['karmazynowy', 'czerwony', 'bordowy'] 78 | >>> kolory = ['zielony', odcienie_czerwieni, 'niebieski'] 79 | >>> print(kolory) 80 | ['zielony', ['karmazynowy', 'czerwony', 'bordowy'], 'niebieski'] 81 | ``` 82 | 83 | :snake: Napisz funkcję `element`, która przyjmuje dwa argumenty, listę oraz 84 | numer indeksu (integer) i zwraca element listy znajdujący się pod podanym 85 | indeksem. 86 | 87 | :snake: Napisz funkcję `ostatni_element`, która jako argument przyjmuje 88 | listę i zwraca jej ostatni element. Użyj w niej funkcji `element`. 89 | 90 | 91 | ## Metody listy 92 | 93 | Listy, podobnie jak stringi, mają wiele metod. Poniżej 94 | znajdziesz opis kilku najbardziej przydatnych z nich. 95 | 96 | 97 | ### `append` 98 | 99 | Ta metoda służy do dodawania elementu do listy: 100 | 101 | ```python 102 | >>> liczby = [1, 3] 103 | >>> print(liczby) 104 | [1, 3] 105 | >>> liczby.append(5) 106 | >>> print(liczby) 107 | [1, 3, 5] 108 | >>> liczby.append(7) 109 | >>> print(liczby) 110 | [1, 3, 5, 7] 111 | ``` 112 | 113 | :snake: Napisz funkcję, która jako argument przyjmuje listę i dodaje na 114 | jej końcu taki sam element jaki jest na samym jej początku. 115 | 116 | 117 | ### `pop` 118 | 119 | Metoda `pop` może nie przyjmować żadnych argumentów - zwraca wtedy ostatni element 120 | listy, jednocześnie usuwając go z niej. 121 | 122 | * Może też przyjmować argumenty, sprawdzisz to za pomocą funkcji help, chociaż nie jest to teraz potrzebne. W niektórych zadaniach dla uproszczenia możemy pomijać tego typu komentarze 123 | 124 | ```python 125 | >>> litery = ['a', 'b', 'c', 'd'] 126 | >>> print(litery) 127 | ['a', 'b', 'c', 'd'] 128 | >>> litery.pop() 129 | 'd' 130 | >>> print(litery) 131 | ['a', 'b', 'c'] 132 | >>> litery.pop() 133 | 'c' 134 | >>> litery.pop() 135 | 'b' 136 | >>> print(litery) 137 | ['a'] 138 | ``` 139 | 140 | :snake: Napisz funkcję, która usuwa z listy dwa ostatnie elementy, po czym 141 | dodaje do niej ten element, który na samym początku był ostatni. 142 | 143 | 144 | ### `count` 145 | 146 | `count` przyjmuje jako argument jeden dowolny obiekt i zwraca liczbę 147 | wystąpień tego obiektu na liście: 148 | 149 | ```python 150 | >>> oceny = [4, 3, 3, 5, 2, 3, 5, 4, 2, 4, 5, 4, 3, 3] 151 | >>> oceny.count(3) 152 | 5 153 | >>> oceny.count(4) 154 | 4 155 | >>> oceny.count(2) 156 | 2 157 | ``` 158 | 159 | ### `remove` 160 | 161 | Metoda `remove` przyjmuje jako argument dowolny obiekt i usuwa go z listy. 162 | Jeżeli obiekt występuje na liście wielokrotnie, to tylko jego pierwsze 163 | wystąpienie jest usuwane: 164 | 165 | ```python 166 | >>> liczby = [10, 20, 25, 20, 10, 15] 167 | >>> liczby.remove(20) 168 | >>> print(liczby) 169 | [10, 25, 20, 10, 15] 170 | >>> liczby.remove(20) 171 | >>> print(liczby) 172 | [10, 25, 10, 15] 173 | >>> liczby.remove(10) 174 | >>> print(liczby) 175 | [25, 10, 15] 176 | ``` 177 | 178 | :snake: Sprawdź co się stanie jeżeli spróbujemy usunąć element, którego 179 | nie ma na liście. 180 | 181 | :snake: Napisz funkcję, która przyjmuje dwa argumenty: listę oraz dowolny 182 | inny obiekt. Funkcja powinna usunąć z listy pierwsze wystąpienie tego 183 | obiektu, a następnie dodać go na końcu listy. Funkcja powinna zwrócić 184 | liczbę wystąpień tego elementu na liście. 185 | 186 | 187 | ### `index` 188 | 189 | `index` przyjmuje jeden obiekt jako argument i zwraca numer pozycji na 190 | jakiej ten obiekt znajduje się na liście: 191 | 192 | ```python 193 | >>> litery = ['r', 't', 'b', 'w', 'h'] 194 | >>> litery.index('t') 195 | 1 196 | >>> litery.index('h') 197 | 4 198 | ``` 199 | 200 | :snake: Sprawdź co się stanie jeżeli spróbujemy pobrać indeks elementu, 201 | którego nie ma na liście. 202 | 203 | 204 | ## Listy i funkcja `len` 205 | 206 | Podobnie jak w przypadku stringów, długość listy możemy sprawdzić funkcją 207 | wbudowaną `len` : 208 | 209 | ```python 210 | >>> litery_nazwiska = ['K', 'o', 'w', 'a', 'l', 's', 'k', 'i'] 211 | >>> print(len(litery_nazwiska)) 212 | 8 213 | ``` 214 | 215 | 216 | ## Funkcje wbudowane `sum`, `min`, `max` i `sorted` 217 | 218 | Istnieje kilka funkcji wbudowanych, które pomagają nam w pracy z listami. 219 | Tutaj opiszemy część z nich. 220 | 221 | Pierwsze trzy są najbardziej pomocne gdy operujemy na listach, których 222 | wszystkie elementy są liczbami. `sum` zwraca sumę wszystkich elementów, 223 | `min` zwraca element o najmniejszej wartości, a `max` ten o największej 224 | wartości: 225 | 226 | ```python 227 | >>> pomiary = [2, 4.25, 5.30, 3] 228 | >>> sum(pomiary) 229 | 14.55 230 | >>> min(pomiary) 231 | 2 232 | >>> max(pomiary) 233 | 5.3 234 | ``` 235 | 236 | :snake: Napisz funkcję, która jako argument przyjmuje listę i wypisuje na 237 | ekran element o największej wartości oraz liczbę wystąpień tego elementu 238 | na liście. 239 | 240 | Kolejna funkcja to `sorted`, która przyjmuje listę, a zwraca posortowaną 241 | kopię tej listy: 242 | 243 | ```python 244 | >>> wyniki = [45.5, 47.2, 35.8, 41.0, 33.3] 245 | >>> posortowane_wyniki = sorted(wyniki) 246 | >>> print(posortowane_wyniki) 247 | [33.3, 35.8, 41.0, 45.5, 47.2] 248 | >>> print(wyniki) 249 | [45.5, 47.2, 35.8, 41.0, 33.3] 250 | ``` 251 | 252 | :snake: Napisz funkcję, która jako argument przyjmie listę, posortuje ją, 253 | a następnie zwróci jej ostatni element. (W ten sposób otrzymamy własną 254 | wersję funkcji `max`!) 255 | 256 | 257 | ## Wycinki list 258 | 259 | Czasami operując na liście chcielibyśmy używać tylko jej fragmentu, np. 260 | 10 pierwszych elementów, albo elementy od drugiego do piątego. Python 261 | jest przygotowany na taką sytuację: umożliwia utworzenie *wycinka* 262 | listy (ang. *slice*). Aby stworzyć wycinek należy wpisać nazwę listy, 263 | a następnie w nawiasach kwadratowych indeksy pierwszego i ostatniego 264 | wycinka elementu oddzielone dwukropkiem. 265 | 266 | Przykładowo, zwrócenie fragmentu listy od drugiego do czwartego elementu 267 | będzie wyglądało tak: 268 | 269 | ```python 270 | >>> lista = [1, 2, 3, 4, 5, 6, 7] 271 | >>> lista[1:4] 272 | [2, 3, 4] 273 | ``` 274 | 275 | Pamiętaj, że indeksy listy zaczynając się od zera, a element o indeksie 276 | końcowym (w tym wypadku: `5`) nie zostanie dołączony do wycinka. 277 | 278 | Możemy też pominąć indeks początkowy. W takim wypadku Python zwróci 279 | wszystkie elementy od początku: 280 | 281 | ```python 282 | >>> lista[:5] 283 | [1, 2, 3, 4, 5] 284 | ``` 285 | 286 | Jeżeli pominiemy indeks końcowy, dostaniemy wszystkie elementy do końca 287 | listy: 288 | 289 | ```python 290 | >>> lista[2:] 291 | [3, 4, 5, 6, 7] 292 | ``` 293 | 294 | Jeżeli indeks końcowy będzie liczbą ujemną, to pozycja ostatniego elementu 295 | wycinka będzie liczona od końca listy: 296 | 297 | ```python 298 | >>> lista[:-1] 299 | [1, 2, 3, 4, 5, 6] 300 | >>> lista[:-2] 301 | [1, 2, 3, 4, 5] 302 | ``` 303 | 304 | Co ciekawe, wycinki możemy tworzyć również ze stringów: 305 | 306 | ```python 307 | >>> tekst = 'ala ma kota' 308 | >>> tekst[2:8] 309 | 'a ma k' 310 | ``` 311 | 312 | :snake: Zobacz co się stanie, jeżeli indeks początkowy będzie liczbą 313 | ujemną, lub jeżeli indeks końcowy będzie większy niż długość listy. 314 | 315 | 316 | ## :pushpin: Podsumowanie 317 | 318 | W tym rozdziale: 319 | 320 | * dowiedzieliśmy się czym są listy, jak je definiować i jak odnosić się 321 | do poszczególnych elementów listy, 322 | * poznaliśmy najważniejsze metody list, 323 | * dowiedzieliśmy się, w jaki sposób używać na listach funkcji wbudowanych 324 | `len`, `sum`, `max`, `min` oraz `sorted`. 325 | 326 | 327 | --- 328 | 329 | :checkered_flag: Następny rozdział: [Pętla `for`](./10_for.md) :checkered_flag: 330 | 331 | -------------------------------------------------------------------------------- /10_for.md: -------------------------------------------------------------------------------- 1 | # Rozdział 10. Pętla `for` 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się czym jest **iteracja** i **pętla**, 6 | * poznasz pętlę `for`. 7 | 8 | 9 | ## Iteracja 10 | 11 | Kiedy operujemy na liście, bardzo często chcemy "przejść" po wszystkich 12 | jej elementach po kolei i na każdym z nich wykonać jakąś operację. Takie 13 | "przejście" nazywamy **iteracją**. W Pythonie aby otrzymać każdy element 14 | listy po kolei możemy oczywiście użyć indeksów: 15 | 16 | ```python 17 | >>> daty = ['15/07/2017', '16/07/2017', '17/07/2017'] 18 | >>> print(daty[0]) 19 | 15/07/2017 20 | >>> print(daty[1]) 21 | 16/07/2017 22 | >>> print(daty[2]) 23 | 17/07/2017 24 | ``` 25 | 26 | Jednak takie podejście jest niewygodne kiedy lista jest bardzo długa. 27 | A co gdy w ogóle nie wiemy na jak długiej liście działamy? Te problemy 28 | można rozwiązać za pomocą **pętli**, czyli instrukcji, która wykonuje 29 | podane operacje dopóki jakiś warunek nie zostanie spełniony. Z użyciem 30 | pętli możemy na przykład iterować, czyli wykonywać operacje na kolejnych 31 | elementach listy, dopóki nie dojdziemy do jej końca. 32 | 33 | ## Pętla `for` 34 | 35 | Pętle mają wiele zastosowań, ale iteracja jest jednym z najczęściej 36 | spotykanych. Dlatego Python posiada pętlę `for`, która służy właśnie do 37 | tego. Spójrzmy na taki przykład: 38 | 39 | ```python 40 | godziny_odjazdu = ['7:30', '13:45', '16:10'] 41 | for godzina in godziny_odjazdu: 42 | print(godzina) 43 | ``` 44 | 45 | Przepisz do edytora powyższy kod i wykonaj go. W oknie trybu 46 | interaktywnego zobaczysz, że funkcja `print` została wykonana dla każdego 47 | elementu na liście, wypisując go na ekran. Stało się tak, ponieważ Python 48 | przeszedł po wszystkich elementach listy `godziny_odjazdu` i dla każdego 49 | z nich przypisał jego wartość do zmiennej `godzina` i wykonał operację 50 | `print`. 51 | 52 | Definicja pętli zaczyna się od słowa `for`, następnie należy podać nazwę 53 | zmiennej, do której będą przypisywane wartości kolejnych elementów, dalej 54 | wpisujemy słowo `in`, nazwę listy oraz dwukropek. W kolejnych linijkach 55 | znajdują się operacje, które zostaną wykonane dla każdego elementu. 56 | Pamiętaj, że przed każdą operacją musi się znaleźć jednakowe wcięcie 57 | w kodzie. Ich szerokość nie ma znaczenia, ważne żeby były takie same. 58 | 59 | Jeżeli pętla znajduje się wewnątrz funkcji, to wcięcie wewnątrz `for` 60 | należy powiększyć o szerokość wcięcia funkcji: 61 | 62 | ```python 63 | def wypisz_elementy(lista): 64 | for element in lista: 65 | print(element) 66 | ``` 67 | 68 | :snake: Napisz funkcję, która jako argument przyjmie listę liczb i wpisze 69 | na ekran wartość każdej z nich podniesioną do kwadratu. 70 | 71 | :snake: Napisz funkcję, który przyjmie listę stringów i zwróci nową listę, 72 | na której znajdą się wszystkie te stringi pisane wielkimi literami 73 | (użyj metody `upper`). 74 | 75 | 76 | ## `for` i stringi 77 | 78 | Pętla `for` jest bardzo elastyczna: możesz jej użyć również na stringu. 79 | W takim wypadku jej elementami będą poszczególne litery: 80 | 81 | ```python 82 | for litera in 'ala ma kota': 83 | print(litera) 84 | ``` 85 | 86 | :snake: Napisz funkcję, która jako argument przyjmie string i wypisze każdą 87 | jego literę wraz z liczbą wystąpień tej litery w stringu (użyj metody 88 | `count`). 89 | 90 | 91 | ### Metoda `split` 92 | 93 | Możemy również iterować po słowach. Służy do tego metoda `split`: 94 | 95 | ```python 96 | for slowo in 'ala ma kota'.split(): 97 | print(slowo) 98 | ``` 99 | 100 | Tak naprawdę metoda `split` ma dużo szersze zastosowanie. Jeżeli 101 | podamy jej jako argument jakiś znak, wtedy string zostanie podzielony 102 | w miejscach występowania tego znaku: 103 | 104 | ```python 105 | >>> tekst = '2015,2016,2017' 106 | >>> tekst.split(',') 107 | ['2015', '2016', '2017'] 108 | ``` 109 | 110 | Jeżeli nie przekażemy żadnego argumentu, to string zostanie rozdzielony 111 | w miejscach spacji: 112 | 113 | ```python 114 | >>> 'ala ma kota'.split() 115 | ['ala', 'ma', 'kota'] 116 | ``` 117 | 118 | :snake: Napisz funkcję, która jako argument przyjmuje string i wypisuje 119 | wszystkie jego słowa, każde w osobnej linijce. 120 | 121 | 122 | ## `range` 123 | 124 | W tym miejscu warto wspomnieć o funkcji wbudowanej `range`. Przyjmuje 125 | ona jako argumenty dwa integery: początek i koniec przedziału liczbowego, 126 | który zwraca. Możemy następnie iterować po takim przedziale i wówczas 127 | elementami będą kolejne liczby całkowite: 128 | 129 | ```python 130 | for liczba in range(10, 20): 131 | print(liczba) 132 | ``` 133 | 134 | W powyższym przykładzie wypisujemy liczby całkowite od 10 do 19. Liczba, 135 | którą podaliśmy jako koniec przedziału, nie jest w nim uwzględniona. 136 | 137 | Co ciekawe, możemy podać tylko jeden argument, który wtedy jest traktowany 138 | jako koniec przedziału, zaś za początek przyjmuje się liczbę 0. Kolejny 139 | przykład pokazuje jak wypisać liczby od 0 do 99: 140 | 141 | ```python 142 | for liczba in range(100): 143 | print(liczba) 144 | ``` 145 | 146 | :snake: Napisz funkcję, która przyjmie jeden argument o nazwie `limit` 147 | i zwróci listę wartości od 0 do `limit` podniesionych do kwadratu. 148 | 149 | 150 | ## :pushpin: Podsumowanie 151 | 152 | W tym rozdziale: 153 | 154 | * poznaliśmy pojęcia *iteracja* oraz *pętla*, 155 | * nauczyliśmy się korzystać w pętli `for`, 156 | * dowiedzieliśmy się, że pętla `for` działa także na stringach, oraz że 157 | stringi posiadają metodę `split`, 158 | * poznaliśmy funkcję wbudowaną `range`. 159 | 160 | 161 | --- 162 | 163 | :checkered_flag: Następny rozdział: [Krotki](./11_krotki.md) :checkered_flag: 164 | -------------------------------------------------------------------------------- /11_krotki.md: -------------------------------------------------------------------------------- 1 | # Rozdział 11. Krotki 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się czym jest **krotka**. 6 | 7 | 8 | ## Krotka 9 | 10 | Czytając kod programów napisanych w Pythonie bardzo szybko natkniesz się 11 | na coś z pozoru bardzo podobnego do listy: 12 | 13 | ```python 14 | waluty = ('EUR', 'PLN', 'USD') 15 | ``` 16 | 17 | Powyższy przykład to definicja **krotki**. Na pierwszy rzut oka różni się 18 | ona od listy tylko tym, że zamiast nawiasów kwadratowych ma okrągłe. 19 | Jednak krotka posiada jedną istotną cechę, która odróżnia ją od listy: 20 | nie można jej modyfikować. Oznacza to, że do raz utworzonej krotki nie 21 | można dodawać elementów, usuwać ich, ani nawet zmieniać. Dlatego też nie 22 | znajdziemy w krotce metod `append` ani `remove`. Za to z powodzeniem 23 | możemy odnosić się do poszczególnych elementów używając ich indeksów: 24 | 25 | ```python 26 | >>> waluty[1] 27 | 'PLN' 28 | ``` 29 | 30 | Oznacza to, że możemy również iterować po krotce pętlą `for`. Jeśli zaś 31 | przekażemy krotkę do funkcji `len`, to dostaniemy liczbę jej elementów. 32 | 33 | :snake: Napisz funkcję, która jako argument przyjmie krotkę i zwraca 34 | listę, która zawiera dokładnie takie same elementy. 35 | 36 | 37 | ## Zastosowanie krotek 38 | 39 | Z pozoru krotka może się wydawać czymś zupełnie zbędnym. Po co nam taka 40 | lista, której nie można modyfikować? Otóż w wielu przypadkach potrzebujemy 41 | dokładnie czegoś takiego. Dobrym przykładem jest właśnie zbiór nazw walut. 42 | Wyobraźmy sobie, że piszemy program do przeliczania wartości pieniężnych 43 | między różnymi walutami. W naszym programie będą zmieniały się kursy, 44 | ale same waluty będą cały czas takie same. Dlatego możemy je zdefiniować 45 | w krotce, tym samym chroniąc się przed modyfikacją zbioru walut, co byłoby 46 | niepożądane. Nawet jeżeli w przyszłości będziemy chcieli dodać kolejną 47 | walutę, łatwiej będzie wydać nową wersję programu niż ryzykować modyfikację 48 | zbioru, który powinien pozostać niezmieniony. 49 | 50 | Podobnych przykładów jest więcej i czytając kod różnych programów szybko 51 | przekonasz się, że krotki przydają się częściej niż mogło by się wydawać. 52 | 53 | 54 | ## :pushpin: Podsumowanie 55 | 56 | W tym rozdziale: 57 | 58 | * dowiedzieliśmy się czym jest krotka i jakie operacje możemy na niej 59 | wykonywać. 60 | 61 | 62 | --- 63 | 64 | :checkered_flag: Następny rozdział: [Prawda i fałsz](./12_prawda_i_falsz.md) :checkered_flag: 65 | -------------------------------------------------------------------------------- /12_prawda_i_falsz.md: -------------------------------------------------------------------------------- 1 | # Rozdział 12. Prawda i fałsz 2 | 3 | W tym rozdziale: 4 | 5 | * poznasz pojęcia "prawda" i "fałsz" oraz ich reprezentację w Pythonie: 6 | `True` i `False`, 7 | * poznasz **instrukcję warunkową** `if`, która pozwala zmienić przebieg 8 | programu, jeżeli określony warunek zostanie spełniony. 9 | 10 | 11 | ## Prawda, fałsz i warunek 12 | 13 | Programy jakie dotąd pisaliśmy składały się z operacji, które Python 14 | wykonywał jedna po drugiej. Gdy jedna instrukcja została pomyślnie 15 | zrealizowana, program przechodził do wykonania kolejnej. 16 | Pisząc kolejne programy szybko przekonasz się, że taki scenariusz nie 17 | zawsze będzie Ci odpowiadał, ponieważ często chcemy, żeby jakieś operacje 18 | zostały wykonane tylko gdy zostanie spełniony pewien warunek. 19 | 20 | Na przykład: mamy listę liczb i chcemy przejść po jej elementach, wypisując 21 | tylko te nieparzyste. W takim przypadku warunkiem wypisania liczby na 22 | ekran jest "liczba jest nieparzysta". 23 | 24 | Języki programowania pozwalają definiować takie warunki i sprawdzać je. 25 | Wynikiem takiego sprawdzenia jest **prawda** lub **fałsz**. Prawda oznacza 26 | sytuację w której warunek został spełniony. Przeciwieństwem jest fałsz. 27 | Przykładowo wynikiem warunku "żyrafa to ptak" jest fałsz, a wynikiem dla 28 | "Ziemia nie jest płaska" jest prawda. 29 | 30 | Oczywiście w programach nie tworzy się tak abstrakcyjnych warunków. 31 | Zamiast tego będziemy porównywali wartości zmiennych, sprawdzali czy wynik 32 | jakiejś funkcji ma określoną wartość itd. W tym rozdziale dowiesz się 33 | jak wykonywać takie operacje oraz jak pisać programy, które realizują 34 | różne instrukcje w zależności do tego czy jakiś warunek został spełniony. 35 | 36 | 37 | ## Warunki w Pythonie, `True` i `False` 38 | 39 | W Pythonie mamy do dyspozycji szereg operatorów, które pozwalają nam 40 | sprawdzać prawdziwość wyrażeń. Możemy na przykład porównywać wartości. 41 | Służy do tego operator `==`: 42 | 43 | ```python 44 | >>> 1 == 2 45 | False 46 | >>> (2 + 2) == (2 * 2) 47 | True 48 | ``` 49 | 50 | Odwrotnością operatora `==` jest `!=`: 51 | 52 | ```python 53 | >>> 'ala' != 'Ala' 54 | True 55 | >>> [1, 2] != [1, 2] 56 | False 57 | ``` 58 | 59 | Możemy również sprawdzać czy jedna wartość jest większa lub mniejsza od 60 | drugiej: 61 | 62 | ```python 63 | >>> 100 > 70 64 | True 65 | >>> 70 > 100 66 | False 67 | ``` 68 | 69 | Operatory `>` i `<` można łączyć z `=`, w ten sposób tworząc warunek 70 | "większy lub równy" i "mniejszy lub równy": 71 | 72 | ```python 73 | >>> 3 >= 2 74 | True 75 | >>> 2 >= 2 76 | True 77 | >>> 1 >= 2 78 | False 79 | ``` 80 | 81 | Zwróć uwagę, że w jednym wyrażeniu można użyć wielu operatorów: 82 | 83 | ```python 84 | >>> 1 <= 2 < 3 <= 3 < 4 85 | True 86 | ``` 87 | 88 | Ponadto możemy zaprzeczyć całemu wyrażeniu pisząc na początku `not`: 89 | 90 | ```python 91 | >>> not 1 == 1 92 | False 93 | >>> not 1 == 2 94 | True 95 | ``` 96 | 97 | Oczywiście w każdym przypadku wartości wpisane wprost możemy zastąpić 98 | zmiennymi, a wynik wyrażenia zachować. 99 | 100 | ```python 101 | >>> temperatura = 26 102 | >>> jest_zimno = temperatura < 10 103 | >>> print(jest_zimno) 104 | False 105 | ``` 106 | 107 | 108 | ## Porównywanie stringów 109 | 110 | Porównywanie liczb wydaje się zrozumiałe, ale w jaki sposób porównywane 111 | są stringi? Odpowiedź jest prostsza niż mogło by się wydawać: 112 | alfabetycznie. Litery znajdujące się dalej w alfabecie są "większe" 113 | od tych wcześniejszych. Poza tym litery małe są "większe" od wielkich. 114 | 115 | ```python 116 | >>> 'A' < 'B' < 'a' < 'b' 117 | True 118 | ``` 119 | 120 | Co ze stringami, które mają więcej niż jeden znak? Są one porównywane 121 | znak po znaku, dopóki któryś z nich nie będzie się różnił, albo dopóki 122 | jeden ze stringów nie będzie dłuższy. W tym drugim przypadku większy 123 | będzie ten string który ma więcej znaków. 124 | 125 | ```python 126 | >>> 'a' < 'ala' 127 | True 128 | >>> 'ala' == 'ala' 129 | True 130 | >>> 'ala' < 'ala ma kota' 131 | True 132 | ``` 133 | 134 | 135 | ## Operator `in` 136 | 137 | Poza dotychczas omówionymi operatorami, jest jeszcze jeden, przydatny 138 | szczególnie kiedy pracujemy z listami. Operator `in` zwraca `True` jeżeli 139 | dany element znajduje się na liście: 140 | 141 | ```python 142 | >>> 'Basia' in ['Tomek', 'Magda', 'Karol', 'Basia'] 143 | True 144 | >>> 12 in [10, 20, 30, 40] 145 | False 146 | ``` 147 | 148 | 149 | ## Instrukcja warunkowa `if` 150 | 151 | Sprawdzanie czy jakieś wyrażenie jest prawdziwe nie miałoby większego sensu 152 | gdybyśmy nie mogli w jakiś sposób na tej podstawie podjąć decyzji 153 | o dalszym przebiegu naszego programu. W tym celu używamy **instrukcji 154 | warunkowej** `if`: 155 | 156 | ```python 157 | if temperatura > 30.0: 158 | print('Uf jak gorąco!') 159 | ``` 160 | 161 | Struktura tej instrukcji jest bardzo prosta: po słowie `if` wpisujemy 162 | warunek, następnie dwukropek i w kolejnych liniach, po wcięciu, instrukcje, 163 | które zostaną wykonane jeżeli warunek będzie prawdziwy (mówimy: jeżeli 164 | warunek zostanie spełniony). 165 | 166 | :snake: Napisz funkcję, która przyjmuje argumenty `element` i `lista` 167 | i jeżeli dany element znajduje się na liście, to zwraca jego pozycję 168 | (użyj metody `index`), w przeciwnym wypadku zwraca `-1`. 169 | 170 | :snake: Napisz funkcję `iloraz`, która przyjmuje argumenty `dzielna` 171 | i `dzielnik`. Jeżeli dzielnik jest różny od zera, funkcja powinna zwrócić 172 | wynik dzielenia. W przeciwnym wypadku powinna wypisać komunikat o błędzie. 173 | 174 | 175 | ## `if ... else` oraz `elif` 176 | 177 | Do instrukcji `if` możemy dopisać drugą część, która zostanie wykonana 178 | tylko jeżeli warunek nie będzie spełniony: 179 | 180 | ```python 181 | if godzina <= godzina_odjazdu: 182 | print('Godzina odjazdu:', godzina_odjazdu) 183 | else: 184 | print('Przepraszamy za opóźnienie') 185 | ``` 186 | 187 | Zwróć uwagę na wcięcia w kodzie: `if` oraz `else` są na tym samym 188 | "poziomie". 189 | 190 | Jeżeli chcemy, możemy w ramach jednej instrukcji `if` sprawdzić kilka 191 | alternatywnych warunków, jeżeli poprzednie okażą się nieprawdziwe: 192 | 193 | ```python 194 | if 5 <= godzina < 12: 195 | print('rano') 196 | elif godzina == 12: 197 | print('południe') 198 | elif 12 < godzina < 17: 199 | print('popołudnie') 200 | elif 17 < godzina < 20: 201 | print('wieczór') 202 | else: 203 | print('noc') 204 | ``` 205 | 206 | :snake: Napisz funkcję, która porównuje dwie liczby. Jako argumenty 207 | powinna przyjmować liczby `a` i `b`. Jeżeli `a` jest większe od `b` 208 | powinna zwrócić 1, jeżeli liczby są równe `0`, a jeżeli `a` jest mniejsze 209 | od `b`, `-1`. Dodatkowo, w zależności od wyniku porównania, funkcja 210 | powinna wypisać jeden z komunikatów: `a < b`, `a == b` lub `a > b`. 211 | 212 | 213 | ## Łączenie warunków 214 | 215 | Czasami będziemy chcieli wykonać jakieś operacje tylko jeżeli spełnionych 216 | zostanie kilka warunków jednocześnie. W takim wypadku możemy użyć 217 | operatora `and`: 218 | 219 | ```python 220 | if substancja == 'woda' and temperatura > 100: 221 | stan_skupienia = 'para wodna' 222 | ``` 223 | 224 | Gdybyśmy chcieli, żeby operacja została wykonana jeżeli przynajmniej jeden 225 | z kilku warunków zostanie spełniony, to należy użyć operatora `or`: 226 | 227 | ```python 228 | if produkt == 'sok' or produkt == 'herbata': 229 | cena = 4.50 230 | ``` 231 | 232 | Operatory `or` i `and` można łączyć w jednym wyrażeniu. 233 | 234 | 235 | ## Prawdziwość obiektów, funkcja `bool` 236 | 237 | Warunek nie musi być porównaniem. Każdy typ obiektu w jakiś sposób 238 | definiuje prawdziwość. Na przykład pusta lista to fałsz, a lista z co 239 | najmniej jednym jednym elementem to prawda. 240 | 241 | Aby przekonać się jaką wartość w rozumieniu logiki reprezentuje dany 242 | obiekt, możemy posłużyć się funkcją wbudowaną `bool`. Przyjmuje ona jeden 243 | argument - dowolny obiekt - i zwraca jego wartość logiczną: `True` lub 244 | `False`. 245 | 246 | ```python 247 | >>> bool([]) 248 | False 249 | >>> bool([1, 2, 3]) 250 | True 251 | ``` 252 | 253 | :snake: Dla każdego z następujących typów odszukaj wartość, dla której 254 | funkcja `bool` zwróci `True` i taką dla której zwróci `False`: string, 255 | krotka, integer, float. 256 | 257 | Ponieważ każdy obiekt można rozważać w kategorii "prawdziwości", każdym 258 | obiektem możemy posłużyć się w instrukcji `if`: 259 | 260 | ```python 261 | if imie and nazwisko and len(haslo) > 5: 262 | print('Podano prawidłowe dane') 263 | ``` 264 | 265 | :snake: Napisz funkcję, która jako argument przyjmie listę i zwróci `True` 266 | jeżeli wszystkie elementy na tej liście są prawdziwe, albo `False` jeżeli 267 | przynajmniej jeden element nie jest prawdziwy. 268 | 269 | 270 | ## :pushpin: Podsumowanie 271 | 272 | W tym rozdziale: 273 | 274 | * nauczyliśmy się sprawdzać prawdziwość wyrażeń, 275 | * poznaliśmy instrukcję `if`, która może zmienić przebieg programu gdy 276 | określone wyrażenie jest prawdziwe. 277 | 278 | 279 | --- 280 | 281 | :checkered_flag: Następny rozdział: [Słowniki](./13_slowniki.md) :checkered_flag: 282 | 283 | -------------------------------------------------------------------------------- /13_slowniki.md: -------------------------------------------------------------------------------- 1 | # Rozdział 13. Słowniki 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się czym jest **słownik**, **klucz** oraz **wartość**, 6 | * nauczysz się definiować słowniki oraz wykonywać na nich operacje, 7 | * poznasz najczęściej spotykane zastosowania słowników. 8 | 9 | 10 | ## Czym jest słownik 11 | 12 | Wiele sytuacji z jakimi spotkasz się pisząc programy będzie można opisać 13 | jako zbiór kluczy i wartości im odpowiadających. Przykładem z codziennego 14 | życia jest encyklopedia, gdzie kluczami są różne hasła, a wartościami 15 | są definicje tłumaczące te hasła. Można pójść dalej i powiedzieć, że 16 | internet to zbiór adresów (np. `pl.pycon.org`) oraz stron WWW, które się 17 | pod nimi kryją. 18 | 19 | Takie spojrzenie na otaczającą nas rzeczywistość jest bardzo wygodne, 20 | bo pozwala opisać złożone zjawiska w systematyczny, łatwy do zrozumienia 21 | sposób. Dlatego też wiele języków programowania oferuje narzędzia do 22 | tworzenia tego typu struktur danych. W przypadku Pythona 23 | są to **słowniki**. 24 | 25 | Słownik (*dictionary*, w skrócie *dict*), to zbiór **kluczy** oraz 26 | odpowiadających im **wartości**. Nazwa "słownik" nie jest przypadkowa, 27 | nawiązuje do formuły w której zbiorowi słów przypisujemy ich definicje. 28 | 29 | 30 | ## Definicja słownika 31 | 32 | Słownik definiujemy poprzez wypisanie par klucz-wartość, oddzielonych 33 | przecinkami, ujmując całość w nawiasy klamrowe. Każda para to dwie 34 | wartości oddzielone dwukropkiem. 35 | 36 | ```python 37 | wiek = {'Marcin': 23, 'Agata': 17, 'Marta': 46} 38 | ``` 39 | 40 | Aby stworzyć pusty słownik wystarczą puste nawiasy klamrowe: 41 | 42 | ```python 43 | d = {} 44 | ``` 45 | 46 | Wartości w słowniku nie muszą być tego samego typu, jedna może być liczbą, 47 | kolejna stringiem itd.: 48 | 49 | ```python 50 | d = {'liczba': 123, 'inna liczba': 12.34, 'lista': ['Ala ma kota']} 51 | ``` 52 | 53 | Klucze mogą być również liczbami: 54 | 55 | ```python 56 | d = {15: 'Ala ma kota', 'Kot ma alę': 3.14} 57 | ``` 58 | 59 | Słownik może też być elementem listy: 60 | 61 | ```python 62 | l = [{'a': 1, 'b': 2}, 3, 4] 63 | ``` 64 | 65 | Kiedy wypiszemy słownik na ekran, zobaczymy całą jego zawartość: 66 | 67 | ```python 68 | >>> d = {'a': ['x', 9, 'z'], 'b': 2, 'c': 'Ala ma kota'} 69 | >>> print(d) 70 | {'a': ['x', 9, 'z'], 'b': 2, 'c': 'Ala ma kota'} 71 | ``` 72 | 73 | 74 | ## Operacje na słownikach 75 | 76 | Kiedy zdefiniujemy słownik, możemy na nim wykonać szereg operacji. 77 | 78 | 79 | ### Pobieranie wartości elementu 80 | 81 | Aby otrzymać wartość dla danego klucza należy wpisać nazwę słownika, 82 | a następnie, w nawiasach kwadratowych, nazwę klucza: 83 | 84 | ```python 85 | >>> d = {'a': 1, 'b': 2} 86 | >>> print(d['a']) 87 | 1 88 | >>> print(d['a'] + d['b']) 89 | 3 90 | ``` 91 | 92 | :snake: Zobacz co się stanie jeżeli pobierzesz wartość dla klucza, który 93 | nie istnieje w słowniku. 94 | 95 | :snake: Napisz funkcję, która przyjmie dwa argumenty, listę słowników 96 | oraz klucz i zwróci listę wartości znajdujących się pod tym kluczem 97 | z każdego słownika na liście. 98 | 99 | 100 | ### Definiowanie elementu 101 | 102 | W każdej chwili możemy zdefiniować wartość klucza w słowniku. Żeby to 103 | zrobić należy odwołać się do danego klucza i przypisać do niego wartość: 104 | 105 | ```python 106 | >>> d = {'a': 1} 107 | >>> d['b'] = 2 108 | >>> d[5] = ['lista', 'elementów'] 109 | >>> print(d) 110 | {'a': 1, 'b': 2, 5: ['lista', 'elementów']} 111 | >>> print(d[5]) 112 | ['lista', 'elementów'] 113 | ``` 114 | 115 | Jeżeli dany klucz już istnieje, jego wartość zostanie nadpisana: 116 | 117 | ```python 118 | >>> d = {'a': 1} 119 | >>> print(d['a']) 120 | 1 121 | >>> d['a'] = 2 122 | >>> print(d['a']) 123 | 2 124 | ``` 125 | 126 | 127 | ### Usuwanie elementu 128 | 129 | Możemy usunąć dowolny klucz słownika posługując się instrukcją `del`: 130 | 131 | ```python 132 | >>> d = {'a': 1, 'b': 2} 133 | >>> del d['a'] 134 | >>> print(d) 135 | {'b': 2} 136 | ``` 137 | 138 | :snake: Zobacz co się stanie jeżeli spróbujesz usunąć klucz, który nie 139 | istnieje w słowniku. 140 | 141 | 142 | ### Iterowanie po kluczach i wartościach 143 | 144 | W jednym z poprzednich rozdziałów mówiliśmy o iteracji w kontekście listy, 145 | czyli o "przechodzeniu" po jej elementach. Używaliśmy w tym celu pętli 146 | `for`. Jeżeli wykonamy tę samą operację na słowniku, to przejdziemy po 147 | jego kluczach: 148 | 149 | ```python 150 | for klucz in slownik: 151 | print(klucz) 152 | ``` 153 | 154 | :snake: Napisz funkcję, która przyjmuje jako argument słownik i przechodzi 155 | po jego kluczach, wypisując każdy z nich. 156 | 157 | W podobny sposób możemy iterować po samych wartościach słownika. Służy 158 | do tego metoda `values`: 159 | 160 | ```python 161 | lista_startowa = {1: 'Puchatek', 2: 'Prosiaczek', 3: 'Tygrysek'} 162 | for zawodnik in lista_startowa.values(): 163 | print(zawodnik) 164 | ``` 165 | 166 | :snake: Napisz funkcję, która przyjmuje jako argument słownik i zwraca 167 | sumę wszystkich wartości słownika. Zakładamy, że wartości zawsze są 168 | liczbami. 169 | 170 | Słownik posiada również metodę `items`, dzięki której możemy iterować 171 | jednocześnie po kluczach i wartościach słownika: 172 | 173 | ```python 174 | lista_startowa = {1: 'Puchatek', 2: 'Prosiaczek', 3: 'Tygrysek'} 175 | for numer_startowy, zawodnik in lista_startowa.items(): 176 | print(numer_startowy, ':', zawodnik) 177 | ``` 178 | 179 | Zwróć uwagę, że tym razem w pętli `for` zdefiniowaliśmy dwie zmienne: 180 | `numer_startowy` i `zawodnik`. Nie jest to nic specyficznego dla słownika, 181 | ale kolejna właściwość tej pętli. Jeżeli pętla przechodzi po liście, 182 | której wszystkie elementy są sekwencjami (czyli listami lub krotkami), 183 | to możemy od razu **rozpakować** wszystkie elementy tych sekwencji do 184 | zmiennych: 185 | 186 | ```python 187 | lista = [['a', 'Arbuz', 'Anglia'], ['b', 'Banan', 'Brazylia']] 188 | for litera, owoc, panstwo in lista: 189 | print(owoc) 190 | ``` 191 | 192 | Wracając do słowników, w naszym przypadku pierwszym elementem każdej 193 | sekwencji jest klucz, a drugim wartość dla tego klucza. 194 | 195 | :snake: Napisz funkcję, która przyjmie dwa argumenty, słownik oraz wartość 196 | i zwróci nazwę klucza, którego wartość jest równa wartości z argumentu. 197 | 198 | 199 | ## Zagnieżdżanie słowników 200 | 201 | Wartością w słowniku może być dowolny obiekt, również inny słownik. 202 | Dzięki temu możemy w prosty sposób tworzyć złożone struktury danych: 203 | 204 | ```python 205 | >>> auto = {} 206 | >>> auto['kolor'] = 'czerwony' 207 | >>> auto['silnik'] = {'pojemność': 1600, 'moc': 130} 208 | >>> print(auto) 209 | {'kolor': 'czerwony', 'silnik': {'pojemność': 1600, 'moc': 130}} 210 | ``` 211 | 212 | 213 | ## "Długość" słownika 214 | 215 | Kiedy po raz pierwszy wspomnieliśmy o funkcji `len`, powiedzieliśmy, że 216 | służy ona do sprawdzania długości obiektów. Każdy typ obiektu (string, 217 | lista, etc.) może inaczej rozumieć pojęcie długości. W przypadku stringów 218 | chodzi o liczbę znaków, w przypadku list o liczbę elementów itd. 219 | Słowniki również mają swoją "długość": jest ona równa liczbie kluczy. 220 | 221 | ```python 222 | >>> print(auto) 223 | {'kolor': 'czerwony', 'silnik': {'pojemność': 1600, 'moc': 130}} 224 | >>> len(auto) 225 | 2 226 | ``` 227 | 228 | 229 | ## Do czego możemy wykorzystać słowniki 230 | 231 | Słownik jest bardzo uniwersalną strukturą danych, przez co ma wiele 232 | zastosowań: 233 | 234 | * reprezentacja obiektów i ich atrybutów (jak w powyższym przykładzie), 235 | * mapowanie jednych wartości na inne (jak w prawdziwym słowniku, gdzie 236 | mapujemy słowa z jednego języka na drugi), 237 | * przechowywanie wielu powiązanych ze sobą wartości w jednym miejscu 238 | (np. klucze to tytuły filmów, a wartości to ich reżyserowie). 239 | 240 | :snake: Wybierz jedno z powyższych zastosowań słownika. Napisz funkcję 241 | `ustaw`, która przyjmuje trzy argumenty, słownik, klucz oraz wartość i 242 | ustawia w słowniku daną wartość pod danym kluczem. Napisz funkcję 243 | `pobierz`, która przyjmuje dwa argumenty, słownik oraz klucz i zwraca 244 | wartość słownika pod danym kluczem. Stosując te funkcje wypełnij słownik 245 | danymi adekwatnymi dla wybranego zastosowania i pobierz te dane. 246 | 247 | 248 | ## :pushpin: Podsumowanie 249 | 250 | W tym rozdziale: 251 | 252 | * nauczyliśmy się tworzyć słowniki i wykonywać na nich operacje, między 253 | innymi iterowanie, 254 | * dowiedzieliśmy się, że funkcja `len` zwraca liczbę kluczy w słowniku, 255 | * poznaliśmy najczęściej spotykane zastosowania słowników. 256 | 257 | 258 | --- 259 | 260 | :checkered_flag: Następny rozdział: [`None`](./14_none.md) :checkered_flag: 261 | 262 | -------------------------------------------------------------------------------- /14_none.md: -------------------------------------------------------------------------------- 1 | # Rozdział 14. `None` 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się czym jest **`None`**. 6 | 7 | 8 | ## `None` 9 | 10 | W Pythonie istnieje jedna szczególna wartość, która nie reprezentuje 11 | żadnego dotąd poznanego typu: **`None`**. Nie jest to liczba, string, ani 12 | nic innego co poznasz ucząc się tego języka. `None` to unikalna wartość, 13 | która reprezentuje osobny typ. Powstała po to, żeby programista mógł 14 | zdefiniować "nic". Po co? Okazuje się, że są sytuacje, w których chcesz 15 | wprost zaznaczyć, że dana operacja nie zwróciła żadnej istotnej informacji. 16 | W takich sytuacjach możesz użyć wartości `None`. Zwróć uwagę, że sam fakt 17 | posłużenia się tą wartością jest na tyle wyjątkowy, że sugeruje, że 18 | zaistniały jakieś szczególne okoliczności. 19 | 20 | Przykładem użycia `None` może być dzielenie przez 0. Jak wiemy, taka 21 | operacja matematyczna jest niedozwolona. Teraz wyobraźmy sobie, że piszemy 22 | funkcję, która przyjmuje jako argumenty dwie liczby i zwraca wynik 23 | dzielenia jednej przez drugą. 24 | 25 | ```python 26 | def podziel(dzielna, dzielnik): 27 | return dzielna / dzielnik 28 | ``` 29 | 30 | Co się stanie gdy argument `dzielnik` będzie równy `0`? Otrzymamy błąd: 31 | 32 | ```python 33 | >>> podziel(3, 0) 34 | Traceback (most recent call last): 35 | File "", line 1, in 36 | File "", line 2, in podziel 37 | ZeroDivisionError: division by zero 38 | ``` 39 | 40 | Aby temu zapobiec, możemy przed wykonaniem dzielenia sprawdzić wartość 41 | argumentu i w razie potrzeby zwrócić `None`, sygnalizując, że nie możemy 42 | obliczyć wyniku: 43 | 44 | ```python 45 | def podziel(dzielna, dzielnik): 46 | if dzielnik == 0: 47 | return None 48 | return dzielna / dzielnik 49 | ``` 50 | 51 | Teraz z łatwością możemy rozpoznać kiedy funkcja napotkała niestandardowe 52 | wywołanie: 53 | 54 | ```python 55 | >>> wynik = podziel(4, 2) 56 | >>> print(wynik) 57 | 2.0 58 | >>> wynik = podziel(5, 0) 59 | >>> print(wynik) 60 | None 61 | ``` 62 | 63 | 64 | ## Domyślna wartość funkcji 65 | 66 | Napiszmy prostą funkcję, która przyjmuje argument i wypisuje go na ekran: 67 | 68 | ```python 69 | def wypisz(obiekt): 70 | print(obiekt) 71 | ``` 72 | 73 | Wywołanie funkcji spowoduje oczekiwane skutki: 74 | 75 | ```python 76 | >>> wypisz(123) 77 | 123 78 | >>> wypisz('ala ma kota') 79 | ala ma kota 80 | ``` 81 | 82 | Widzimy, że ciało funkcji zostało wykonane, jednak jaka wartość została 83 | zwrócona? Innymi słowy: co się dzieje, jeżeli nie użyjemy instrukcji 84 | `return`? Odpowiedź brzmi: funkcja zwróci `None`. 85 | 86 | ```python 87 | >>> rezultat = wypisz('abc') 88 | abc 89 | >>> print(rezultat) 90 | None 91 | ``` 92 | 93 | Tak samo dzieje się, jeżeli użyjemy instrukcji `return` nie podając jej 94 | żadnej wartości: 95 | 96 | ```python 97 | def wypisz(obiekt): 98 | print(obiekt) 99 | return 100 | ``` 101 | 102 | Efekt będzie taki sam jak wtedy gdy nie użyjemy `return`: 103 | 104 | ```python 105 | >>> rezultat = wypisz(3.14) 106 | 3.14 107 | >>> print(rezultat) 108 | None 109 | ``` 110 | 111 | Za takim zachowaniem nie kryje się żadna magia: po prostu twórcy Pythona 112 | przyjęli, że domyślnie funkcja zwraca "nic", a wartość taka będzie 113 | reprezentowana przez `None`. 114 | 115 | 116 | ## Operator `is` 117 | 118 | Skoro wiemy, że funkcje mogą zwracać `None`, to w jaki sposób z tego 119 | skorzystać? Możemy na przykład sprawdzić zwróconą wartość w instrukcji 120 | `if`: 121 | 122 | ```python 123 | def imie_nazwisko(imie, nazwisko): 124 | if imie != '' and nazwisko != '': 125 | return imie + ' ' + nazwisko 126 | 127 | def nazwa_uzytkownika(imie, nazwisko, email): 128 | pelne_nazwisko = imie_nazwisko(imie, nazwisko) 129 | if pelne_nazwisko == None: 130 | return email 131 | else: 132 | return pelne_nazwisko 133 | ``` 134 | 135 | W powyższym przykładzie funkcja `nazwa_uzytkownika` zwraca pełną nazwę 136 | użytkownika na podstawie jego imienia, nazwiska i adresu email. Jeżeli 137 | imię i nazwisko są dane, to zwracane jest pełne nazwisko, w przeciwnym 138 | wypadku zwrócony zostanie tylko adres email. Sprawdzenie czy pełne 139 | nazwisko jest podane zostało zapisane w instrukcji 140 | `if pelne_nazwisko == None`. 141 | 142 | Instrukcja `if zmienna == None` jest poprawna, jednak w ogólnym przypadku 143 | może nie zawsze działać. Dzieje się tak, ponieważ tworząc bardziej 144 | zaawansowane struktury danych w Pythonie (co nie będzie omówione podczas 145 | tych warsztatów), możemy zmienić zachowanie porównania, w efekcie wpływając 146 | na wynik zwracany przez operator `==`. Jeżeli zrobimy to nieostrożnie, 147 | może się okazać, że jakaś operacja `if` działa inaczej niż się tego 148 | spodziewamy. Możemy wybrnąć z tej sytuacji stosując zamiast 149 | tego **operator `is`**: 150 | 151 | ```python 152 | if pelne_nazwisko is None: 153 | return email 154 | ``` 155 | 156 | W ten sposób nasz kod będzie niewrażliwy na modyfikacje zachowania 157 | operatora `==`. 158 | 159 | Kiedy zatem używać `is`? Używaj tego operatora zawsze kiedy porównujesz 160 | wartość do `None`. Póki co nie będzie to robiło różnicy, ale dzięki temu 161 | nabędziesz dobrego nawyku, który w przyszłości okaże się przydatny. 162 | 163 | :snake: Napisz funkcję, która jako argument przyjmuje listę i zwróci 164 | również listę, na której znajdą się wszystkie elementy z argumentu, 165 | z wyjątkiem wartości równych `None`. 166 | 167 | 168 | ## :pushpin: Podsumowanie 169 | 170 | W tym rozdziale: 171 | 172 | * poznaliśmy `None`, 173 | * dowiedzieliśmy się, że porównując wartości do `None` należy stosować 174 | operator `is`. 175 | 176 | 177 | --- 178 | 179 | :checkered_flag: Następny rozdział: [Pętla `while`](./15_petla_while.md) :checkered_flag: 180 | 181 | -------------------------------------------------------------------------------- /15_petla_while.md: -------------------------------------------------------------------------------- 1 | # Rozdział 15. Pętla `while` 2 | 3 | W tym rozdziale: 4 | 5 | * nauczysz posługiwać się pętlą `while`. 6 | 7 | 8 | ## Pętla `while` 9 | 10 | Wiesz już czym jest pętla oraz znasz jedną z nich: `for`. Teraz poznasz 11 | drugą, jednocześnie ostatnią jaka istnieje w Pythonie: `while`. Jej 12 | struktura jest jeszcze prostsza od poprzedniej: 13 | 14 | ```python 15 | licznik = 1 16 | while licznik < 10: 17 | print(licznik) 18 | licznik = licznik + 1 19 | ``` 20 | 21 | Definicję pętli zaczynamy słowem `while`, następnie definiujemy warunek 22 | (tak jak w instrukcji `if`), a po dwukropku, w kolejnych linijkach 23 | i po wcięciu, wypisujemy instrukcje, które będą wykonywane tak długo 24 | jak warunek będzie prawdziwy. 25 | 26 | Zwróć uwagę, że jeżeli zdefiniujemy warunek, który zawsze będzie prawdziwy, 27 | wtedy pętla będzie wykonywana w nieskończoność: 28 | 29 | ```python 30 | while 1 == 1: 31 | print('.') 32 | ``` 33 | 34 | :snake: Napisz funkcję, która przyjmie listę jako argument i wypisze 35 | wszystkie jej elementy przy użyciu pętli `while`. 36 | 37 | ## :pushpin: Podsumowanie 38 | 39 | W tym rozdziale: 40 | 41 | * poznaliśmy pętlę `while`. 42 | 43 | 44 | --- 45 | 46 | :checkered_flag: Następny rozdział: [Biblioteka standardowa](./16_biblioteka_standardowa.md) :checkered_flag: 47 | -------------------------------------------------------------------------------- /16_biblioteka_standardowa.md: -------------------------------------------------------------------------------- 1 | # Rozdział 16. Biblioteka standardowa 2 | 3 | W tym rozdziale: 4 | 5 | * dowiesz się czym jest **biblioteka standardowa**, 6 | * poznasz najważniejsze **moduły** biblioteki standardowej. 7 | 8 | 9 | ## Biblioteka 10 | 11 | W programowaniu posługujemy się pojęciem **biblioteka**, które oznacza 12 | zbiór programów i narzędzi do ich budowania, które możemy wykorzystać 13 | pisząc własne programy. Przykładem biblioteki może być zbiór funkcji 14 | matematycznych (np. trygonometrycznych), do których możemy odwołać się 15 | w naszym kodzie zamiast definiować je samodzielnie. 16 | 17 | 18 | ## Moduły 19 | 20 | W Pythonie biblioteki programistyczne są dostępne poprzez **moduły**. 21 | Moduł to po prostu kod umieszczony na dysku, w miejscu w którym 22 | Python może go odnaleźć. Może to być kod napisany w Pythonie, ale 23 | są sposoby na pisanie modułów w innych językach programowania. Python 24 | znajdzie taki kod jeżeli zostanie on umieszczony w jednym z określonych 25 | z góry katalogów. 26 | 27 | Każdy może napisać własny moduł do Pythona. W internecie znajdziemy 28 | tysiące modułów, które różne osoby i firmy udostępniają. Możemy je pobrać 29 | i używać ich do pisania programów. Możemy też tworzyć własne moduły 30 | i dzielić się nimi z innymi użytkownikami. 31 | 32 | Aby skorzystać z modułu w kodzie naszego programu musimy **zaimportować** 33 | jego nazwę. Robimy to instrukcją `import`. Gdy moduł jest już 34 | zaimportowany, możemy używać funkcji i zmiennych, które zostały w nim 35 | zdefiniowane. Robimy to wpisując nazwę modułu, a następnie, po kropce, 36 | nazwę obiektu. 37 | 38 | W poniższym przykładzie importujemy moduł o nazwie `math` i wywołujemy 39 | funkcję `sqrt`, która zwraca pierwiastek kwadratowy z podanej liczby: 40 | 41 | ```python 42 | import math 43 | print(math.sqrt(9)) 44 | ``` 45 | 46 | ## Biblioteka standardowa Pythona 47 | 48 | Poza modułami, które użytkownicy sami mogą pisać, istnieje zbiór modułów, 49 | który zawsze jest dostępny w Pythonie. Ten zbiór nazywamy **biblioteką 50 | standardową**. Znajdziemy w nim dziesiątki modułów, a w nich narzędzia 51 | do komunikacji sieciowej, obsługi różnych formatów plików, obliczeń 52 | matematycznych etc. 53 | 54 | Biblioteka standardowa jest obszernie udokumentowana na [oficjalnej 55 | stronie Pythona](https://docs.python.org/3/library/index.html). 56 | 57 | 58 | ## Najważniejsze moduły 59 | 60 | Omówienie całej biblioteki standardowej to zadanie na co najmniej kilka 61 | tygodni, dlatego podczas tych warsztatów wspomnimy tylko o kilku 62 | najbardziej popularnych modułach. 63 | 64 | 65 | ### [`math`](https://docs.python.org/3/library/math.html) 66 | 67 | Moduł `math` zawiera kilkadziesiąt funkcji matematycznych, które mogą 68 | okazać się pomocne przy prostych obliczeniach. Poniżej opisaliśmy kilka 69 | z nich. 70 | 71 | Funkcje `ceil` i `floor` zwracają wartości zaokrąglone odpowiednio 72 | w dół i w górę: 73 | 74 | ```python 75 | >>> math.ceil(3.5) 76 | 4 77 | >>> math.floor(3.5) 78 | 3 79 | ``` 80 | 81 | Funkcja `sqrt` zwraca pierwiastek kwadratowy z danej liczby: 82 | 83 | ```python 84 | >>> math.sqrt(25) 85 | 5.0 86 | ``` 87 | 88 | `pi` oraz `e` reprezentują wartości stałych matematycznych: 89 | 90 | ```python 91 | >>> math.pi 92 | 3.141592653589793 93 | >>> math.e 94 | 2.718281828459045 95 | ``` 96 | 97 | :snake: Napisz funkcję, która zwróci wartość pola powierzchni koła 98 | o zadanym promieniu (według wzoru `PI * r^2`, gdzie `r` to promień). 99 | 100 | 101 | ### [`datetime`](https://docs.python.org/3/library/datetime.html) 102 | 103 | Moduł `datetime` to podstawowe narzędzie do pracy z datami i czasem. 104 | Zawiera obiekty `date`, `datetime` oraz `timedelta`, które reprezentują 105 | odpowiednio datę, datę i czas oraz różnicę w czasie. 106 | 107 | Aby otrzymać dzisiejszą datę należy wywołać metodę `today` na obiekcie 108 | `date`: 109 | 110 | ```python 111 | >>> datetime.date.today() 112 | datetime.date(2017, 8, 13) 113 | ``` 114 | 115 | Otrzymany w ten sposób obiekt zawiera trzy **atrybuty**: `year`, `month` 116 | oraz `day`, czyli odpowiednio rok, miesiąc i dzień. 117 | 118 | ```python 119 | >>> dzisiaj = datetime.date.today() 120 | >>> dzisiaj.year 121 | 2017 122 | >>> dzisiaj.month 123 | 8 124 | >>> dzisiaj.day 125 | 13 126 | ``` 127 | 128 | Metoda `now` na obiekcie `datetime` zwróci nam datę i godzinę, którą mamy 129 | w tej chwili. Poza atrybutami `year`, `month` oraz `day` posiada także 130 | `hour`, `minute`, `second` i `microsecond`, czyli godzinę, minutę, sekundę 131 | i mikrosekundę. 132 | 133 | ```python 134 | >>> teraz = datetime.datetime.now() 135 | >>> teraz 136 | datetime.datetime(2017, 8, 13, 18, 53, 13, 366193) 137 | >>> teraz.hour 138 | 18 139 | >>> teraz.minute 140 | 53 141 | >>> teraz.second 142 | 13 143 | >>> teraz.microsecond 144 | 366193 145 | ``` 146 | 147 | Oba typy obiektów możemy wypisać na ekran w czytelnym formacie: 148 | 149 | ```python 150 | >>> print(dzisiaj) 151 | 2017-08-13 152 | >>> print(teraz) 153 | 2017-08-13 18:53:13.366193 154 | ``` 155 | 156 | Chcąc utworzyć reprezentację dowolnego momentu w czasie, wystarczy 157 | wywołać `date` lub `datetime` i podać kolejno `year`, `month`, `day`, 158 | `hour`, `minute`, `second`, `microsecond`: 159 | 160 | ```python 161 | >>> print(datetime.date(2010, 5, 10)) 162 | 2010-05-10 163 | >>> print(datetime.datetime(2020, 11, 23, 15, 7, 30)) 164 | 2020-11-23 15:07:30 165 | ``` 166 | 167 | :snake: Zobacz co się stanie jeżeli spróbujesz utworzyć obiekt `date` 168 | z miesiącem spoza zakresu od 1 do 12 lub datę, która nie istnieje, np. 169 | 31 kwietnia. 170 | 171 | :snake: Zobacz co się stanie jeżeli spróbujesz utworzyć obiekt `datetime` 172 | z godziną, minutą lub sekundą o wartości spoza dopuszczalnego zakresu 173 | (np. godzina 26). 174 | 175 | Jeżeli chcemy zobaczyć różnicę w czasie między dwoma obiektami typu 176 | `datetime`, możemy je po prostu odjąć od siebie: 177 | 178 | ```python 179 | >>> a = datetime.datetime(2017, 8, 16, 17, 00) 180 | >>> b = datetime.datetime(2017, 8, 16, 19, 00) 181 | >>> roznica = b - a 182 | >>> roznica 183 | datetime.timedelta(0, 7200) 184 | >>> roznica.seconds 185 | 7200 186 | ``` 187 | 188 | W powyższym przykładzie otrzymaliśmy obiekt `timedelta`, który posiada 189 | atrybut `seconds` o wartości równej liczbie sekund pomiędzy `a` i `b`. 190 | 191 | Jeżeli różnica jest większa niż jedna doba, to zostanie ona podzielona 192 | na dwie wartości: `seconds` i `days`, czyli sekundy i dni. 193 | 194 | ```python 195 | >>> c = datetime.datetime(2017, 8, 16, 17, 00) 196 | >>> d = datetime.datetime(2017, 8, 18, 15, 00) 197 | >>> roznica = d - c 198 | >>> roznica.seconds 199 | 79200 200 | >>> roznica.days 201 | 1 202 | ``` 203 | 204 | Jeżeli do daty `c` dodamy jeden dzień i 79200 sekund, to otrzymamy `d`. 205 | 206 | :snake: Napisz funkcję, która przyjmuje dwie daty jako argumenty. 207 | Jeżeli druga data jest mniejsza od pierwszej, funkcja powinna zwrócić 208 | `None`. W przeciwnym wypadku funkcja powinna zwrócić liczbę sekund 209 | dzielącą obie daty. Zwróć uwagę, że różnica może być większa niż jedna 210 | doba. W takim wypadku liczbę dni należy zamienić na sekundy. 211 | 212 | 213 | ### [`random`](https://docs.python.org/3/library/random.html) 214 | 215 | Moduł `random` służy do wykonywania operacji, których wynik jest losowy: 216 | generowania liczb losowych, losowego wybierania obiektów z danego zakresu, 217 | itd. 218 | 219 | Funkcja `randint` przyjmuje dwa integery jako argumenty i zwraca losowo 220 | wybraną liczbę całkowitą, której wartość znajduje się pomiędzy argumentami. 221 | 222 | ```python 223 | >>> random.randint(1, 100) 224 | 9 225 | >>> random.randint(1, 100) 226 | 44 227 | ``` 228 | 229 | Funkcja `choice` przyjmuje jako argument dowolną sekwencję (listę, krotkę, 230 | string) i zwraca losowo wybrany element: 231 | 232 | ```python 233 | >>> random.choice('ala ma kota') 234 | 'm' 235 | >>> random.choice([9, 7, 5, 3]) 236 | 7 237 | >>> random.choice(('pycon', 'pl', '2017')) 238 | 'pl' 239 | ``` 240 | 241 | :snake: Napisz funkcję, która przyjmie jako argument dowolną sekwencję 242 | i zwróci *krotkę* z trzema losowo wybranymi z niej elementami. 243 | 244 | 245 | ### [`json`](https://docs.python.org/3/library/json.html) 246 | 247 | Moduł `json` pozwala zapisywać obiekty Pythona (słowniki i listy) jako 248 | string w formacie JSON (*JavaScript Object Notation*), który jest 249 | powszechnie używany np. w serwisach internetowych do wymiany danych między 250 | przeglądarką a serwerem. 251 | 252 | Żeby zapisać obiekt do stringa należy wywołać funkcję `dumps`: 253 | 254 | ```python 255 | >>> json.dumps({'miejsce': 'Ossa', 'data': '2017-08-16'}) 256 | '{"miejsce": "Ossa", "data": "2017-08-16"}' 257 | >>> json.dumps([2017, 8, 16]) 258 | '[2017, 8, 16]' 259 | ``` 260 | 261 | Do zamiany stringa na słownik lub listę służy funkcja `loads`: 262 | 263 | ```python 264 | >>> json.loads('{"miejsce": "Ossa", "data": "2017-08-16"}') 265 | {'miejsce': 'Ossa', 'data': '2017-08-16'} 266 | >>> json.loads('[2017, 8, 16]') 267 | [2017, 8, 16] 268 | ``` 269 | 270 | ## Co dalej? 271 | 272 | Wyżej wymieniliśmy tylko kilka najbardziej popularnych modułów, więc 273 | zachęcamy do zapoznania się z resztą biblioteki standardowej. Warto 274 | zacząć od oficjalnej dokumentacji, ale w internecie znajdziemy mnóstwo 275 | artykułów poświęconych stosowaniu biblioteki standardowej na co dzień. 276 | Oczywiście nie trzeba znać jej w całości żeby swobodnie programować 277 | w Pythonie. Wiele z tych modułów ma bardzo specyficzne zastosowania 278 | i większość programistów nigdy z nich nie korzysta. Warto natomiast 279 | pamiętać, że jeżeli trafisz na jakiś nowy problem, to dobrze jest najpierw 280 | przejrzeć bibliotekę standardową w poszukiwaniu modułu, który może okazać 281 | się pomocny. 282 | 283 | 284 | ## :pushpin: Podsumowanie 285 | 286 | W tym rozdziale: 287 | 288 | * dowiedzieliśmy się czym jest **biblioteka standardowa** i jak z niej 289 | korzystać, 290 | * poznaliśmy moduły `math`, `datetime`, `random` i `json`. 291 | 292 | 293 | --- 294 | 295 | :checkered_flag: Następny rozdział: [Podsumowanie](./17_podsumowanie.md) :checkered_flag: 296 | 297 | -------------------------------------------------------------------------------- /17_podsumowanie.md: -------------------------------------------------------------------------------- 1 | # Podsumowanie 2 | 3 | Dobiegamy do końca kursu, ale to jeszcze nie koniec warsztatów! Czekają 4 | na Ciebie jeszcze dodatkowe rozdziały - znajdziesz je w sekcji "Dodatki" 5 | pod spisem treści. Poza tym mentorzy mają dla Ciebie jeszcze garść zadań. 6 | Możesz też skorzystać z okazji i zadać mentorom tyle pytań na ile tylko 7 | starczy czasu - między innymi dlatego zorganizowaliśmy te warsztaty! 8 | 9 | 10 | ## O czym nie powiedzieliśmy 11 | 12 | Niestety czas na warsztaty jest ograniczony, więc i zakres tematów, jakie 13 | poruszyliśmy, nie jest wyczerpujący. Znasz już podstawy Pythona. Możesz 14 | już samodzielnie pisać własne programy, a czytanie cudzych nie będzie już 15 | takie trudne. Jednak na tym etapie często trafisz na kod, którego nie 16 | zrozumiesz. A może już teraz wiesz o tematach, które wydają się 17 | interesujące, ale nie wiesz jak zacząć. Dlatego przygotowaliśmy dla Ciebie 18 | listę zagadnień, którą możesz potraktować jako kontynuację tych warsztatów. 19 | Lista ta nie jest wyczerpująca, ale na pewno pomoże Ci jeszcze 20 | lepiej poznać Pythona. W każdym punkcie umieściliśmy odnośnik do strony, 21 | która wyjaśnia dany temat. 22 | 23 | * [Jeszcze więcej o wyjątkach i obsługiwaniu ich](https://docs.python.org/3.12/tutorial/errors.html) 24 | * [Klasy, czyli programowanie zorientowane obiektowo](https://docs.python.org/3.12/tutorial/classes.html) 25 | * [Dekoratory](https://docs.python.org/3/glossary.html#term-decorator) 26 | * [Generatory](https://docs.python.org/3/glossary.html#index-17) 27 | * [Listy składane](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) 28 | * [Zbiory](https://docs.python.org/3/tutorial/datastructures.html#sets) 29 | 30 | 31 | ## Na koniec... `dir` 32 | 33 | Kończąc pokażemy Ci jeszcze jedną, bardzo przydatną funkcję wbudowaną. 34 | Nazywa się `dir`, przyjmuje jako argument dowolny obiekt i zwraca listę 35 | nazw wszystkich metod i atrybutów tego obiektu: 36 | 37 | ```python 38 | >>> d = {'a': 1} 39 | >>> dir(d) 40 | ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] 41 | ``` 42 | 43 | W powyższym przykładzie rozpoznasz na pewno kilka znajomych nazw, np. 44 | `items` czy `values`, ale jak widzisz słowniki oferują znacznie więcej. 45 | Zwróć uwagę na nazwy zaczynające i kończące się podwójnym znakiem 46 | podkreślenia. W taki sposób są nazywane atrybuty i metody, które nie są 47 | przeznaczone dla użytkowników obiektu. Zazwyczaj są to rzeczy używane 48 | tylko wewnątrz danego obiektu. Oczywiście tak czy inaczej można z nich 49 | korzystać - po prostu zazwyczaj nie będą dla nas przydatne, więc warto 50 | zainteresować się pozostałymi nazwami. 51 | 52 | Co teraz zrobić z taką listą? Jeżeli jakaś nazwa wydaje się oczywista, 53 | możemy po prostu spróbować jej użyć - w najgorszym wypadku otrzymamy 54 | komunikat o błędzie wyjaśniający co zrobiliśmy źle. Możemy też - i to 55 | polecamy - użyć funkcji `help`, która wyświetli dokumentację danego 56 | obiektu: 57 | 58 | ```python 59 | help(d.update) 60 | ``` 61 | 62 | 63 | ## :checkered_flag: Koniec 64 | 65 | Dziękujemy za udział w warsztatach! Jeszcze raz zachęcamy do rozmowy 66 | z mentorami - chętnie odpowiedzą na wszystkie pytania i wyjaśnią 67 | niezrozumiałe tematy. 68 | 69 | Jeżeli masz uwagi do tego kursu, podziel się nimi pisząc do autorów, 70 | albo przekaż je mentorom. Twoje zdanie jest dla nas bardzo ważne! 71 | 72 | ![programming is fun again](https://imgs.xkcd.com/comics/python.png) 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Warsztaty PyLadies / PyCon PL 2 | 3 | Witaj na warsztatach PyLadies! Podczas tego kursu nauczysz się programować 4 | w języku **Python** od podstaw. Aby zacząć nie potrzebujesz nic instalować, 5 | nie jest wymagana żadna znajomość programowania czy informatyki. Wystarczy 6 | przeglądarka internetowa i chęć zdobywania wiedzy! 7 | 8 | 9 | ## Czego uczą te warsztaty 10 | 11 | Ten kurs nauczy Cię tworzyć własne programy w Pythonie. Poznasz podstawy 12 | tego języka, oraz dowiesz się jak w przyszłości poszerzyć wiedzę, aby 13 | samodzielnie tworzyć coraz ciekawsze rzeczy. Dzięki tym warsztatom 14 | zrozumiesz Pythona na poziomie, który pozwoli Ci pisać przydatne narzędzia 15 | oraz zgłębiać bardziej zaawansowane aspekty tego języka. 16 | 17 | Podsumowując: Twoja przygoda z programowaniem zaczyna się właśnie tutaj! 18 | 19 | 20 | ## Legenda 21 | 22 | Zanim zaczniemy, zapoznaj się z oznaczeniami, które zostały użyte na 23 | kolejnych stronach kursu. 24 | 25 | :snake: oznacza miejsce, w którym dajemy Ci do wykonania jakieś zadanie. 26 | Jeżeli instrukcje nie są jasne, lub zadanie sprawia Ci kłopoty - poproś 27 | o pomoc mentora. 28 | 29 | :pushpin: to podsumowanie rozdziału. Zanim przejdziesz dalej, upewnij się, 30 | że rozumiesz wszystkie wymienione tam tematy. Jeśli masz jakiekolwiek 31 | wątpliwości - zapytaj mentora. Nie sugeruj się innymi - właśnie po to 32 | robimy podsumowanie, żeby upewnić się, że każdy zrozumiał dany rozdział. 33 | 34 | :checkered_flag: to koniec rozdziału. Kliknij w odnośnik, aby przejść 35 | do kolejnego. 36 | 37 | **Pogrubionym tekstem** wyróżniliśmy istotne słowa i zwroty. Warto je 38 | zapamiętać, aby łatwiej przyswoić kolejne rozdziały. 39 | 40 | `W taki sposób` oznaczyliśmy przykładowy kod programów. 41 | 42 | 43 | ## Mentorzy 44 | 45 | Nasz zespół mentorów jest tutaj dla Ciebie! Jeżeli masz pytania, cokolwiek 46 | jest niejasne albo nie wiesz jak wykonać jakieś zadanie - poproś kogoś 47 | z nas o pomoc. Chętnie odpowiemy, opowiemy i pomożemy Ci zrozumieć każdy 48 | temat. Nie krępuj się: my również kiedyś zadawaliśmy pytania i właśnie 49 | dzięki temu sami możemy teraz na nie odpowiadać. 50 | 51 | 52 | ## Spis treści 53 | 54 | 1. [Tryb interaktywny](./01_tryb_interaktywny.md) 55 | 2. [Tekst](./02_tekst.md) 56 | 3. [Funkcja `help`](./03_help.md) 57 | 4. [Liczby](./04_liczby.md) 58 | 5. [Błędy](./05_bledy.md) 59 | 6. [Zmienne](./06_zmienne.md) 60 | 7. [Funkcje](./07_funkcje.md) 61 | 8. [Funkcja `print`](./08_funkcja_print.md) 62 | 9. [Listy](./09_listy.md) 63 | 10. [Pętla `for`](./10_for.md) 64 | 11. [Krotki](./11_krotki.md) 65 | 12. [Prawda i fałsz](./12_prawda_i_falsz.md) 66 | 13. [Słowniki](./13_slowniki.md) 67 | 14. [`None`](./14_none.md) 68 | 15. [Pętla `while`](./15_petla_while.md) 69 | 16. [Biblioteka standardowa](./16_biblioteka_standardowa.md) 70 | 17. [Podsumowanie](./17_podsumowanie.md) 71 | 72 | 73 | ## Dodatki 74 | 75 | 1. [Instalacja Pythona](./d01_instalacja_pythona.md) 76 | 2. [Opcjonalna instalacja Visual Studio Code'a, (dokument jest po angielsku)](./d01_instalacja_pythona.md) 77 | 78 | Istotne są sekcje: 79 | - [Prerequisites](https://code.visualstudio.com/docs/python/python-tutorial#_prerequisites) 80 | - [Start VS Code in a workspace folder](https://code.visualstudio.com/docs/python/python-tutorial#_start-vs-code-in-a-workspace-folder) 81 | - [Create a virtual environment](https://code.visualstudio.com/docs/python/python-tutorial#_create-a-virtual-environment) 82 | - [Create a Python source code file](https://code.visualstudio.com/docs/python/python-tutorial#_create-a-python-source-code-file) 83 | - [Run Python code](https://code.visualstudio.com/docs/python/python-tutorial#_run-python-code) 84 | 85 | 3. [Moduły](./d02_moduly.md) 86 | 4. [Funkcja `input`](./d03_input.md) 87 | 5. [Operacje na plikach](./d04_pliki.md) 88 | 6. [Zadania](./d05_zadania.md) 89 | 90 | -------------------------------------------------------------------------------- /d01_instalacja_pythona.md: -------------------------------------------------------------------------------- 1 | # Dodatek 1. Instalacja Pythona 2 | 3 | Praca na stronie repl.it jest wygodna podczas nauki, jednak aby w pełni 4 | korzystać z Pythona, warto go zainstalować na własnym komputerze. Poniżej 5 | znajdziesz instrukcję instalacji Pythona na systemie Windows. Jeżeli 6 | używasz innego systemu operacyjnego - poproś o pomoc mentora. 7 | 8 | 9 | ## Krok 1: pobierz program instalacyjny 10 | 11 | Wejdź na stronę [https://www.python.org/downloads/](https://www.python.org/downloads/) 12 | i odszukaj w niej przycisk "Download Python 3.12.5" 13 | (liczby na przycisku oznaczają wersję Pythona i mogą wskazywać również wyższą wersję). 14 | Kliknij w niego. W ten sposób pobierzesz program instalacyjny Pythona. 15 | 16 | ![krok 1](./obrazy/d01/krok_1.png) 17 | 18 | 19 | ## Krok 2: uruchom program instalacyjny 20 | 21 | Odszukaj na dysku program instalacyjny i uruchom go. Zobaczysz okno 22 | zatytułowane "Install Python 3.12.5". Upewnij się, że opcja "Add python.exe to PATH" 23 | jest zaznaczona, a następnie kliknij przycisk "Install Now". 24 | 25 | > Jeśli będziesz mieć problem z instalacją Python z użyciem praw administratora - odznacz 26 | > opcję "Use admin privileges when installing py.exe" i spróbuj ponownie. 27 | 28 | ![krok 2](./obrazy/d01/krok_2.png) 29 | 30 | 31 | ## Krok 3: czekaj aż instalacja dobiegnie końca 32 | 33 | Instalacja Pythona może potrwać nawet kilkanaście minut. 34 | 35 | ![krok 3](./obrazy/d01/krok_3.png) 36 | 37 | 38 | ## Krok 4: upewnij się, że instalacja przebiegła prawidłowo 39 | 40 | Jeżeli instalacja powiedzie się, w oknie programu instalacyjnego pojawi 41 | się napis "Setup was successful". Gdyby tak się nie stało, poproś o pomoc 42 | mentora. 43 | 44 | ![krok 4](./obrazy/d01/krok_4.png) 45 | 46 | 47 | ## Krok 5: uruchom program IDLE 48 | 49 | Wraz z Pythonem został zainstalowany program IDLE, w którym możesz edytować 50 | pliki z kodem. Jest tam też dostępny tryb interaktywny. IDLE to kompletne 51 | środowisko programistyczne, w którym możesz tworzyć nawet zaawansowane 52 | programy. 53 | 54 | Odszukaj IDLE wśród programów zainstalowanych na Twoim komputerze i uruchom 55 | go. 56 | 57 | ![krok 5](./obrazy/d01/krok_5.jpg) 58 | 59 | 60 | ## Krok 6: tryb interaktywny 61 | 62 | Po pierwszym uruchomieniu domyślnie otworzy się tryb interaktywny. 63 | Spróbuj wpisać kilka znanych Ci poleceń. 64 | 65 | ![krok 6](./obrazy/d01/krok_6.jpg) 66 | 67 | 68 | ## Krok 7: napisz i uruchom swój pierwszy program 69 | 70 | Kliknij opcję "File" w pasku u góry okna, a następnie wybierz "New File". 71 | Pojawi się okno edytora. Wpisz w nim kod jakiegoś programu, np. 72 | `print('PyLadies')`. Zapisz plik wybierając "File", a następnie "Save". 73 | Aby uruchomić program kliknij w "Run" i "Run Module" (albo wciśnij klawisz 74 | F5). Program zostanie uruchomiony. Jeżeli wypisze jakiś tekst na ekran, 75 | to zobaczysz go w oknie trybu interaktywnego. 76 | 77 | ![krok 7](./obrazy/d01/krok_7.jpg) 78 | 79 | To wszystko. Masz już na swoim komputerze środowisko do programowania 80 | w Pythonie. Możesz pisać kod programów, zapisywać go w plikach, otwierać 81 | je i uruchamiać. Możesz również pracować w trybie interaktywnym. 82 | 83 | -------------------------------------------------------------------------------- /d02_moduly.md: -------------------------------------------------------------------------------- 1 | # Dodatek 2. Moduły 2 | 3 | Jak wspomnieliśmy w rozdziale ["Biblioteka standardowa"](./16_biblioteka_standardowa.md), 4 | każdy może utworzyć własny moduł (bibliotekę) do Pythona i udostępniać 5 | go innym, lub po prostu używać go w różnych projektach. Poniżej 6 | przeczytasz jak tworzyć moduły i w jaki sposób z nich korzystać. 7 | 8 | 9 | ## Pisanie modułu 10 | 11 | Jeżeli masz na swoim komputerze [program IDLE](./d01_instalacja_pythona.md'), 12 | to pewnie wiesz już, że kod programów napisanych w Pythonie jest zapisywany 13 | w plikach z rozszerzeniem `.py`. Jest to konwencja, która pozwala w łatwy 14 | sposób odróżnić kod Pythona od innych plików, które go nie zawierają. 15 | 16 | Każdy plik z rozszerzeniem `.py` jest jednocześnie programem, który możemy 17 | uruchomić w Pythonie. Innymi słowy: jeżeli uruchomimy Pythona i otworzymy 18 | w nim plik z rozszerzeniem `.py`, to kod zawarty w tym pliku zostanie 19 | wykonany. 20 | 21 | Równocześnie każdy plik z rozszerzeniem `.py` jest też modułem. Oznacza 22 | to, że możemy go zaimportować w innym pliku instrukcją `import` i w ten 23 | sposób uzyskać dostęp do wszystkich obiektów w nim zdefiniowanych: funkcji, 24 | zmiennych itd. 25 | 26 | Podsumowując: aby napisać moduł wystarczy umieścić dowolny kod w pliku 27 | z rozszerzeniem `.py`. Każdy taki plik może być potencjalnie wykorzystany 28 | jako moduł. 29 | 30 | 31 | ## Importowanie modułów 32 | 33 | Gotowy moduł możemy wykorzystać w dowolnym innym programie lub module, 34 | importując go tam. Ważne jest, aby oba pliki znajdowały się **w tym 35 | samym katalogu**, w przeciwnym wypadku Python rzuci wyjątek `ImportError`. 36 | 37 | Moduł importujemy instrukcją `import`, w której podajemy jego nazwę, która 38 | jest taka sama jak nazwa pliku w którym go zapisaliśmy, ale bez 39 | rozszerzenia `.py`. 40 | 41 | Załóżmy, że utworzyliśmy plik o nazwie `funkcje.py` i zapisaliśmy w nim 42 | taki kod: 43 | 44 | ```python 45 | def suma(a, b): 46 | return a + b 47 | ``` 48 | 49 | Teraz w tym samym katalogu możemy utworzyć plik `obliczenia.py` i wpisać 50 | w nim następujący kod: 51 | 52 | ```python 53 | import funkcje 54 | 55 | print(funkcje.suma(2000, 17)) 56 | ``` 57 | 58 | Jeżeli uruchomimy program `obliczenia.py`, to na ekran zostanie wypisana 59 | liczba `2017`. 60 | 61 | 62 | ## Zastosowanie modułów 63 | 64 | Moduły to jeden z najpotężniejszych mechanizmów w Pythonie. Pozwalają 65 | podzielić programy na logicznie odseparowane fragmenty. Przykładowo, 66 | w jednym module możemy umieścić wszystkie funkcje odpowiedzialne za 67 | obliczenia matematyczne, w drugim funkcje wypisujące dane na ekran, 68 | a w trzecim połączyć wszystko w całość korzystając z dwóch pozostałych 69 | modułów. 70 | 71 | Pisząc programy zawsze miej na uwadze, że podział na moduły zwiększa 72 | czytelność Twojego kodu. Również Tobie łatwiej będzie wrócić do programu, 73 | którego kod został w taki sposób uporządkowany. 74 | 75 | -------------------------------------------------------------------------------- /d03_input.md: -------------------------------------------------------------------------------- 1 | # Dodatek 3. Funkcja `input` 2 | 3 | Pisząc program bardzo często oczekujemy, że jego użytkownik poda nam jakieś 4 | dane: swoje imię i nazwisko, parametry liczbowe, czy inne wartości, które 5 | wpłyną na przebieg programu. Najprostszą metodą na pozyskanie takich 6 | danych jest funkcja wbudowana `input`, która po wywołaniu zatrzymuje 7 | działanie programu, czeka aż użytkownik wpisze coś i wciśnie enter, po 8 | czym zwraca wpisany tekst w postaci stringa: 9 | 10 | ```python 11 | print('Podaj swój wiek:') 12 | wiek = input() 13 | print('Masz {} lat'.format(wiek)) 14 | ``` 15 | 16 | W powyższym przykładzie wypisujemy na ekran komunikat - prośbę o podanie 17 | wieku - następnie pobieramy tę wartość od użytkownika i wypisujemy ją 18 | w kolejnym komunikacie. 19 | 20 | Pamiętaj, że tak otrzymana wartość zawsze będzie stringiem. Jeżeli chcesz 21 | zamienić ją na liczbę, możesz posłużyć się funkcją wbudowaną [`int`](https://docs.python.org/3/library/functions.html#int). 22 | 23 | -------------------------------------------------------------------------------- /d04_pliki.md: -------------------------------------------------------------------------------- 1 | # Dodatek 4. Operacje na plikach 2 | 3 | Często źródłem danych w programach są pliki. Jeżeli plik zawiera tekst, 4 | czyli znaki, które możemy wyświetlić na ekranie, to nazywamy go **plikiem 5 | tekstowym**. Taki plik możemy odczytać w edytorze tekstu, na przykład 6 | w Notatniku. Istnieją również pliki, których treści nie interpretujemy 7 | jako tekst, na przykład obrazy. Nazywamy je **plikami binarnymi**. 8 | 9 | Oba rodzaje plików możemy odczytywać i zapisywać w Pythonie, jednak 10 | w tym artykule skupimy się na plikach tekstowych. Kiedy nauczysz się 11 | pracować z nimi, operacje na plikach binarnych nie będą już dla Ciebie 12 | stanowiły żadnego problemu. 13 | 14 | 15 | ## Ścieżka pliku 16 | 17 | Najważniejszym atrybutem pliku jest jego **ścieżka**, która mówi w jakim 18 | miejscu w strukturze katalogów i pod jaką nazwą się znajduje. Przykładowo, 19 | jeżeli w systemie Windows zalogujesz się jako użytkownik "Ala" i utworzysz 20 | plik "kot.txt" w katalogu "Moje Dokumenty", to ścieżka tego pliku będzie 21 | najprawdopodobniej wyglądała tak: `C:\Users\Ala\Documents\kot.txt`. 22 | 23 | Ścieżki w Pythonie trzymamy w stringach, na przykład: 24 | 25 | ```python 26 | >>> sciezka_pliku_kot = 'C:\Users\Ala\Documents\kot.txt' 27 | >>> print(sciezka_pliku_kot) 28 | C:\Users\Ala\Documents\kot.txt 29 | ``` 30 | 31 | W powyższym przykładzie zdefiniowaliśmy **ścieżkę bezwzględną**, czyli 32 | taką, która dokładnie określa katalog w jakim znajduje się plik 33 | (`C:\Users\Ala\Documents`). Jeżeli odnosimy się do pliku względem 34 | katalogu, w którym znajduje się nasz program, możemy zdefiniować **ścieżkę 35 | względną**. Na przykład możemy podać tylko nazwę pliku: `kot.txt`. Wtedy 36 | Python uzna, że szukamy pliku w tym samym katalogu co program. Możemy też 37 | powiedzieć, że plik znajduje się w katalogu "wyżej": `..\kot.txt`. 38 | 39 | Niezależnie od wybranej metody, aby operować na pliku będziemy potrzebowali 40 | jego ścieżki. 41 | 42 | 43 | ## Czytanie pliku 44 | 45 | Dostęp do pliku daje nam funkcja wbudowana `open`, która jako argument 46 | przyjmuje ścieżkę: 47 | 48 | ```python 49 | >>> plik = open(sciezka) 50 | ``` 51 | 52 | Gdy zdefiniujemy sobie plik, możemy odczytać całą jego treść wywołując 53 | metodę `read`: 54 | 55 | ```python 56 | >>> dane = plik.read() 57 | >>> print(dane) 58 | zawartość pliku 59 | ``` 60 | 61 | Możemy również iterować po pliku, linijka po linijce: 62 | 63 | ```python 64 | for linia in plik: 65 | print(linia) 66 | ``` 67 | 68 | Gdy odczytamy plik, ponowna próba odczytu zwróci nam pusty string. Dzieje 69 | się tak, ponieważ Python trzyma informację o miejscu w którym skończyliśmy 70 | odczyt pliku i kolejne odczyty zaczyna od tego miejsca. Jeżeli ta pozycja 71 | to koniec pliku, ponowna próba odczytu nic nie zwróci. Chcąc przeczytać 72 | plik od nowa musimy wywołać metodę `seek` z argumentem `0`, co przestawi 73 | pozycję odczytu na sam początek: 74 | 75 | ```python 76 | >>> plik = open('kot.txt') 77 | >>> plik.read() 78 | 'ala ma kota' 79 | >>> plik.read() 80 | '' 81 | >>> plik.seek(0) 82 | >>> plik.read() 83 | 'ala ma kota' 84 | >>> plik.read() 85 | '' 86 | ``` 87 | 88 | 89 | ## Pisanie do pliku 90 | 91 | Otwierając plik funkcją `open` możemy zdecydować, czy będziemy wykonywali 92 | na nim odczyt czy zapis. Domyślnie Python zakłada odczyt. Jeżeli chcemy 93 | wprost określić **tryb** (*mode*) pracy z plikiem, musimy przekazać drugi 94 | argument, który powinien być stringiem. Jeżeli wybierzemy `'r'` (*read*), 95 | to plik będziemy mogli tylko odczytywać. Jeżeli `'w'` (*write*), 96 | to możliwy będzie tylko zapis. Dostępnych trybów jest więcej, o wszystkich 97 | przeczytasz w [dokumentacji metody `open`](https://docs.python.org/3/library/functions.html#open). 98 | 99 | Po otwarciu pliku w trybie zapisu, możemy wpisać do pliku tekst metodą 100 | `write`: 101 | 102 | ```python 103 | >>> plik = open('kot.txt', 'w') 104 | >>> plik.write('ala ma kota') 105 | ``` 106 | 107 | Jeżeli przed otwarciem pliku znajdował się w nim jakiś tekst, to po 108 | wywołaniu metody `write` zostanie on **nadpisany**. Jednak kolejne zapisy 109 | na już otwartym pliku spowodują, że tekst będzie dopisywany na końcu. 110 | 111 | ```python 112 | >>> sciezka = 'kot.txt' 113 | >>> open(sciezka).read() 114 | 'na początku był taki tekst' 115 | >>> plik = open(sciezka, 'w') 116 | >>> plik.write('teraz nadpiszemy') 117 | >>> plik.write(' tamten tekst') 118 | >>> plik.close() 119 | >>> open(sciezka).read() 120 | 'teraz nadpiszemy tamten tekst' 121 | ``` 122 | 123 | Zwróć uwagę, że w powyższym przykładzie po zapisaniu tekstu wywołaliśmy 124 | metodę `close`. W ten sposób zamknęliśmy plik, powodując zachowanie danych 125 | na dysku. Gdybyśmy tego nie zrobili, wywołanie metody `read` zwróciłoby 126 | pierwotną zawartość pliku. Metodę `close` należy stosować jeżeli po 127 | zapisie chcemy ponownie odczytać ten sam plik. W przeciwnym wypadku Python 128 | sam zadba o zamknięcie pliku: zrobi to jeżeli zakończy się funkcja, 129 | w której otworzyliśmy plik albo gdy program zakończy swoje działanie. 130 | 131 | 132 | ## Znak nowej linii 133 | 134 | Operując na plikach tekstowych natkniemy się na **znak nowej linii**, 135 | który w Pythonie jest reprezentowany jako string o treści `\n` (ukośnik 136 | i litera "n"). Oznacza on miejsce, w którym kończy się linia tekstu. 137 | Sam znak nie ma w sobie nic szczególnego, jest po prostu znakiem jak `a` 138 | czy `7`. Natomiast przyjmuje się, że znak nowej linii ma specjalne 139 | znaczenie, aby umożliwić podział tekstu na osobne linie. Dlatego też 140 | jest on traktowany inaczej niż inne znaki, np. funkcja `print` zastąpi 141 | go przejściem do nowej linii. Co istotne, znak ten nie jest bezpośrednio 142 | związany z plikami - może być częścią dowolnego stringa. 143 | 144 | ```python 145 | >>> s = 'pierwsza linia\ndruga linia' 146 | >>> print(s) 147 | pierwsza linia 148 | druga linia 149 | ``` 150 | 151 | -------------------------------------------------------------------------------- /d05_zadania.md: -------------------------------------------------------------------------------- 1 | # Dodatek 5. Zadania 2 | 3 | Ten dodatek zawiera zbiór zadań, które pomogą Ci utrwalić wiedzę zdobytą 4 | podczas kursu. Nauczą Cię też dobierać odpowiednie typy danych i operacje 5 | w zależności od problemu przed jakim stajesz. 6 | 7 | Rozwiązując zadania skup się przede wszystkim na napisaniu działającego 8 | programu. Nie myśl o jego "jakości": tym jak szybko działa, albo jak 9 | ładnie wygląda kod. Zacznij od rozwiązania problemu, a dopiero potem 10 | oceń czy trzeba cokolwiek poprawić. 11 | 12 | 13 | --- 14 | 15 | 16 | ## 1. Funkcja `title` 17 | 18 | Napisz funkcję o nazwie `title`, która będzie działała tak jak metoda 19 | `title` na stringu, ale nie używaj tej metody. 20 | 21 | Przykład: 22 | 23 | ```python 24 | >>> title('ala MA kOTA') 25 | 'Ala Ma Kota' 26 | ``` 27 | 28 | 29 | ## 2. Grupowanie słowników 30 | 31 | Napisz funkcję `grupuj`, która będzie grupowała słowniki według wartości 32 | dla wybranego klucza. 33 | 34 | Przykład: 35 | 36 | ```python 37 | >>> owoce = [ 38 | ... {'nazwa': 'jabłko', 'kolor': 'czerwony'}, 39 | ... {'nazwa': 'banan', 'kolor': 'żółty'}, 40 | ... {'nazwa': 'cytryna', 'kolor': 'żółty'}, 41 | ... {'nazwa': 'gruszka', 'kolor': 'zielony'}, 42 | ... {'nazwa': 'truskawka', 'kolor': 'czerwony'} 43 | ... ] 44 | >>> grupy = grupuj(owoce, 'kolor') 45 | >>> for kolor, lista_owocow in grupy.items(): 46 | ... print(kolor, lista_owocow) 47 | ... 48 | czerwony [{'nazwa': 'jabłko', 'kolor': 'czerwony'}, {'nazwa': 'truskawka', 'kolor': 'czerwony'}] 49 | żółty [{'nazwa': 'banan', 'kolor': 'żółty'}, {'nazwa': 'cytryna', 'kolor': 'żółty'}] 50 | zielony [{'nazwa': 'gruszka', 'kolor': 'zielony'}] 51 | ``` 52 | 53 | Funkcja powinna przyjmować dwa argumenty: listę słowników oraz nazwę 54 | klucza. Wynikiem funkcji powinien być słownik, gdzie kluczami będą nazwy 55 | grup, a wartościami listy słowników znajdujących się w tych grupach. 56 | 57 | 58 | ## 3. Algorytm "delta compression" 59 | 60 | Napisz funkcję `delta_compression`, która jako argument przyjmuje 61 | **posortowaną** listę liczb całkowitych i zwróci tę samą listę 62 | skompresowaną następującym algorytmem: 63 | 64 | 1. Pierwszy element listy wyjściowej jest taki sam jak pierwszy 65 | element listy wejściowej. 66 | 2. Każdy następny element listy wyjściowej jest równy różnicy między 67 | odpowiadającym mu elementem listy wejściowej a elementem 68 | poprzedzającym go, czyli `WY[i] = WE[i] - WE[i-1]`. 69 | 70 | Przykład: 71 | 72 | ```python 73 | >>> we = [5, 7, 11, 21, 28, 39] 74 | >>> delta_compression(we) 75 | [5, 2, 4, 10, 7, 11] 76 | ``` 77 | 78 | 79 | ## 4. Grupuj i licz 80 | 81 | Napisz funkcję `grupuj_i_licz`, która jako argument przyjmie listę 82 | dwuelementowych krotek, gdzie pierwszy element to data (instancja 83 | `datetime.date`), a drugi to liczba całkowita, i obliczy sumy tych liczb 84 | dla każdego miesiąca jaki występuje wśród tych dat. Funkcja powinna zwrócić 85 | słownik, gdzie kluczami będą krotki `(rok, miesiąc)`, a wartościami sumy 86 | liczb. 87 | 88 | Przykład: 89 | 90 | ```python 91 | >>> x = grupuj_i_licz([ 92 | ... (datetime.date(2015, 1, 29), 10), 93 | ... (datetime.date(2015, 1, 30), 12), 94 | ... (datetime.date(2015, 1, 31), 10), 95 | ... (datetime.date(2015, 2, 1), 9), 96 | ... (datetime.date(2015, 2, 2), 9) 97 | ... ]) 98 | >>> print(x) 99 | {(2015, 1): 32, (2015, 2): 18} 100 | ``` 101 | 102 | 103 | ## 5. Cięcie stringa 104 | 105 | Napisz funkcję `tnij`, która przyjmie dwa argumenty: tekst oraz liczbę. 106 | Funkcja powinna zwrócić tekst pocięty na fragmenty (listę), każdy 107 | o długości takiej jak liczba podana w argumencie. Ostatni fragment może 108 | być krótszy niż wymagana długość. 109 | 110 | Przykład: 111 | 112 | ```python 113 | >>> tnij('12345678', 3) 114 | ['123', '456', '78'] 115 | >>> tnij('12345678', 5) 116 | ['12345', '678'] 117 | >>> tnij('123', 4) 118 | ['123'] 119 | ``` 120 | 121 | 122 | ## 6. Liczenie słów 123 | 124 | Napisz funkcję, która jako argument przyjmie dowolny tekst i zwróci 125 | słownik, którego kluczami będą wszystkie słowa z tego tekstu, a wartościami 126 | będą liczby wystąpień tych słów w tekście. Funkcja powinna być obojętna 127 | na wielkość liter (czyli 'Kot' i 'kot' mają być traktowane jako jedno 128 | słowo) i powinna ignorować znaki interpunkcyjne. 129 | 130 | Przykład: 131 | 132 | ```python 133 | >>> tekst = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer sollicitudin ultricies eros, vitae eleifend ipsum sodales ut. Pellentesque libero ipsum, euismod eget volutpat nec, hendrerit vel turpis." 134 | >>> licz_slowa(tekst) 135 | {'sollicitudin': 1, 'elit': 1, 'vel': 1, 'eleifend': 1, 'sodales': 1, 'eros': 1, 'sit': 1, 'nec': 1, 'consectetur': 1, 'pellentesque': 1, 'vitae': 1, 'eget': 1, 'hendrerit': 1, 'dolor': 1, 'turpis': 1, 'euismod': 1, 'integer': 1, 'lorem': 1, 'amet': 1, 'ipsum': 3, 'ut': 1, 'ultricies': 1, 'libero': 1, 'adipiscing': 1, 'volutpat': 1} 136 | ``` 137 | -------------------------------------------------------------------------------- /d06_replit.md: -------------------------------------------------------------------------------- 1 | # Dodatek 6. Założenie konta i obsługa replit.com 2 | 3 | Ten dodatek zawiera informację o tym jak korzystać z platformy `replit.com`, 4 | 5 | ## 1. Założenie konta 6 | 7 | Przejdż do strony zakładania konta na [replit.com](https://replit.com/languages/python3?authModal=language-page%3Ahero). 8 | 9 | ![Zakładanie konta na repl.it](obrazy/d06/krok_1.png) 10 | 11 | Po założeniu konta, zaloguj się na nie. 12 | 13 | ## 2. Wybór planu 14 | 15 | Wybierz plan "Starter" klikając przycisk "Continue with Starter". 16 | ![Wybór planu](obrazy/d06/krok_2.png) 17 | 18 | ## 3. Przetestowanie działania platformy 19 | 20 | W otwartym pliku "main.py" wpisz kod: 21 | 22 | ```python 23 | print("Hello, PyLadies!") 24 | ``` 25 | 26 | Następnie kliknij przycisk "Run" w górnej części ekranu. 27 | 28 | ![Pierwszy program](obrazy/d06/krok_3.png) 29 | 30 | Zobaczysz wynik jego działania w oknie po prawej stronie. 31 | -------------------------------------------------------------------------------- /english/01_interactive_mode.md: -------------------------------------------------------------------------------- 1 | # Chapter 1. Interactive mode 2 | 3 | We will start the workshop by explaining how we will be programming in Python. 4 | 5 | ## Let's begin! 6 | 7 | ### Handling interactive mode on replit.com 8 | 9 | If you have a Python interpreter installed locally, you can skip this section. 10 | 11 | If you don't have a Python interpreter installed locally, open 12 | [this link](https://replit.com/languages/python3) in a separate browser tab. 13 | 14 | If you don't have an account on `replit.com`, you'll need to create one. 15 | 16 | Go to [this guide to create an account](d06_replit.md). 17 | 18 | The page you're looking at is divided into two parts: 19 | 20 | * On the left side, with a white background, is the **text editor**, 21 | * On the right side, you can see the console (**Console**) and the shell (**Shell**). 22 | 23 | ![Console and shell](../obrazy/d06/krok_4.png) 24 | 25 | The editor allows you to create the entire program code and then run it by 26 | pressing the "Run" button (or using the Ctrl + Enter keyboard shortcut). 27 | If the program prints any text, we'll see it in the console. 28 | 29 | You can activate interactive mode by going to the **Shell** tab and running 30 | the `python` command. You will then see the prompt `>>>`, which indicates that 31 | you can enter Python commands. 32 | 33 | ### Interactive mode on your own computer 34 | 35 | You can activate interactive mode by running the `python` command in the terminal. 36 | You will then see the prompt `>>>`, which indicates that 37 | you can enter Python commands. 38 | 39 | ## Interactive mode - how does it work? 40 | 41 | When you enter a command and press Enter, the interactive mode executes it and 42 | displays its result. This way, you can program and immediately see the results. 43 | 44 | Working with the interactive mode is convenient when you want to test the 45 | functionality of a single operation or when you are unsure which operations 46 | you want to perform. If you already know what program you want to write, then 47 | it is easier to use an editor. 48 | 49 | There is one more important difference between interactive mode and an editor: 50 | interactive mode always prints the result of an operation after it is executed. 51 | The editor will only do so if we give it such a command (using the `print` 52 | statement, which we will discuss later). 53 | 54 | For now, we will be using the **interactive mode** as we will be learning 55 | individual instructions and observing their results. Do not be afraid to 56 | experiment with different variations of these commands. In the worst case scenario, 57 | Python will inform you that the entered code cannot be executed. 58 | 59 | ## Prompt sign 60 | 61 | In the code examples that you will find in the following chapters, you will 62 | often see the character string `>>>`. This is the **prompt character**. 63 | We use it to distinguish text that should be entered in interactive mode 64 | from text that the Python interpreter prints out itself. If you see a prompt 65 | character in a line of an example, it means that everything that follows the 66 | character - until the end of the line - should be entered in interactive mode, 67 | and then the Enter key should be pressed. We do not enter the prompt character itself! 68 | 69 | ## :pushpin: Summary 70 | 71 | In this chapter: 72 | 73 | We opened the `repl.it` website, where we can program in either the **editor** or 74 | **interactive mode** of Python. We learned what the **prompt character** looks like 75 | and that it shows us the code to enter in interactive mode. 76 | 77 | The next step is to analyze the data and identify patterns or trends. This will 78 | help us better understand the information and draw meaningful conclusions. 79 | 80 | Once the data has been analyzed and patterns and trends have been identified, we 81 | can gain a deeper understanding of the information and draw significant conclusions. 82 | 83 | :checkered_flag: Next chapter: [Text](./02_text.md) 84 | :checkered_flag: 85 | -------------------------------------------------------------------------------- /english/02_text.md: -------------------------------------------------------------------------------- 1 | # Chapter 2. Text 2 | 3 | In this chapter: 4 | 5 | You will learn what a `string` is and what can be done with it, 6 | you will learn how to write programs that display text. 7 | 8 | ## String 9 | 10 | Almost every program generates some text. Smartphone applications display messages about received messages. Web applications return the content of web pages. Servers save information on their disk about how they are functioning. Text is the basis of communication between a computer and a human. That is why we will start learning programming with operations on text, or, as we say in programming jargon, on **strings**. 11 | 12 | String, or a string of characters, is simply a sequence of letters, numbers, dots, 13 | commas, etc. To define a string in Python, simply enclose some text between the characters `'` (single apostrophe): 14 | 15 | ```python 16 | >>> 'PyLadies 2024' 17 | ``` 18 | 19 | In the above string, there are uppercase and lowercase letters, spaces, and numbers. There are [thousands of characters](https://en.wikipedia.org/wiki/Unicode) that you can use. 20 | 21 | :snake: Before you continue, try to create strings on your own with the following information: Your first and last name, name of the town where you come from, title of your favorite movie or book. 22 | 23 | 24 | ## Apostrophes 25 | 26 | The example we used a moment ago shows a string enclosed in single quotation marks, which is `'`. If you want, you can use the character `"`. For Python, this does not matter. What is important, however, is that the same apostrophe is found on both sides of the string: if you start with a double one, you must end with a double one. The same goes for single ones. 27 | 28 | 29 | ## String operations 30 | 31 | Now, when you know how to define a string, let's try to perform an operation on it. By "operation" we mean transforming one string into another string, for example: 32 | 33 | ```python 34 | >>> 'Winnie the Pooh'.lower() 35 | 'winnie the pooh' 36 | ``` 37 | 38 | (Note the lack of spaces around the period!) 39 | 40 | In this example, we performed two operations: we defined a string `'Kubuś Puchatek'` and **called the method** `lower`. A method is simply an operation that can be performed on an object. In this case, our object is a string and the method is `lower`, which created a new string where all capital letters were changed to lowercase. 41 | 42 | In Python, strings have many other methods, for example: 43 | 44 | * `upper` - opposite of `lower`, 45 | * `title` - changes the first letter of each word from lowercase to uppercase, 46 | * `strip` - removes spaces from the left and right side of the string (if they exist). 47 | 48 | :snake: Now try out these methods in such a way that you can see the effects of their operation. Test them on the strings that we created in the previous exercise. 49 | 50 | 51 | ## What are string operations used for? 52 | 53 | When writing programs, we often have to deal with strings that come from sources over which we have no control. For example, information from a form filled out by a user, or data read from a file. In all of these cases, we process strings whose structure we know nothing about. Operations help us transform strings into the desired format, or search for information within them. 54 | 55 | A good example is a first and last name. Imagine that you are creating a program that asks the user for their first and last name. You want to save this data in the format `First Name Last Name`, so that each word starts with a capital letter. However, the user may enter `jan kowalski` or `JAN KOWALSKI` in the form. In both cases, you will get strings in a different format than you expect. You can handle this by using the `title` method, which will convert both values to `Jan Kowalski`. 56 | 57 | 58 | ## Operations with arguments 59 | 60 | Some operations require additional options to be provided. For example: 61 | 62 | ```python 63 | >>> 'Winnie the Pooh'.find('ni') 64 | 3 65 | ``` 66 | 67 | The `find` method searches for the given string in a string and returns the index of the character in which the string begins. Note that the characters are numbered starting from zero. 68 | 69 | ``` 70 | W i n n i e t h e ... 71 | 0 1 2 3 4 5 6 7 8 9 ... 72 | ``` 73 | 74 | We called the `find` method, giving it the string `'Pu'`. This string is located inside the string `'Winnie the Pooh'` and starts at character number 6, which is why we saw this number on the screen. 75 | 76 | The values that we have to provide when calling a method (e.g. `'Pu'` from the example) are called **arguments**. Some methods do not take any arguments, but there are also those that require one or more to be given. If a method takes multiple arguments, they must be separated by commas. 77 | 78 | 79 | ## `find`, `replace`, `count` 80 | 81 | We will not go through all the methods that the string has right now, but there are three worth knowing from the very beginning, as they are often used. 82 | 83 | ### `find` 84 | 85 | We just learned about `find`: it takes a string as an argument and searches for it in the string on which we performed the operation. If the substring is found, we receive the index of the first character. Otherwise, we receive `-1`. 86 | 87 | This method is useful when we are looking for a specific phrase and want to check if a given string contains it. For example, when we want to find out if our user's name is "Nowak". 88 | 89 | ```python 90 | >>> 'Anna Nowak'.find('Nowak') 91 | 5 92 | >>> 'Jan Kowalski'.find('Nowak') 93 | -1 94 | >>> 'Tomasz Nowak'.find('Nowak') 95 | 7 96 | ``` 97 | 98 | In the above example, if the value returned by `find` is different than `-1`, it means that the user's last name matches. 99 | 100 | Note that capitalization matters: 101 | 102 | ```python 103 | >>> 'Piglet'.find('Pig') 104 | 0 105 | >>> 'Piglet'.find('pig') 106 | -1 107 | >>> 'piglet'.find('Pig') 108 | -1 109 | ``` 110 | 111 | This method is also useful when we are certain that a given string contains the desired character string, but we need to check at which exact position. 112 | 113 | For example, we can find out which letter of the alphabet is the letter `r`. 114 | 115 | ```python 116 | >>> 'aąbcćdeęfghijklłmnńoópqrsśtuvwxyzźż'.find('r') 117 | 23 118 | ``` 119 | 120 | Note that the letter `a` is at position `0`, so the letter `r` is not actually the twenty-third, but the twenty-fourth letter of the alphabet. This example shows how important it is to correctly interpret the information returned by programs. 121 | 122 | :snake: Choose a few paragraphs (2 or more) from this page and for each of them: copy its content and use it to define a string, then call the `find` method on it to check if it contains the string `and`. 123 | 124 | ### `replace` 125 | 126 | The `replace` method takes two arguments: strings `a` and `b`. When we call this method on a certain string, all occurrences of string `a` in that string will be replaced with string `b`. 127 | 128 | For example, you can replace all spaces with a `-` character. 129 | 130 | ```python 131 | >>> 'Ala has a cat'.replace(' ', '-') 132 | 'Ala-has-a-cat' 133 | ``` 134 | 135 | Or replace entire words: 136 | 137 | ```python 138 | >>> Ala has a cat'.replace('cat', 'dog') 139 | 'Ala has a dog' 140 | ``` 141 | 142 | Another example of using this method is removing a character from a string. You can do this by passing an empty string as the second argument: 143 | 144 | ```python 145 | >>> 'Jan Kowalski'.replace('Kowalski', '') 146 | 'Jan ' 147 | ``` 148 | 149 | :snake: Enter your first and last name in interactive mode, and then use the `replace` method to change your name to the name of one of the workshop participants sitting next to you. 150 | 151 | ### `count` 152 | 153 | `count` takes one string as an argument and returns the number of occurrences of that string in the string on which we performed the operation. 154 | 155 | This method is useful when, for example, we want to check if a certain phrase is repeated more than once in a given string: 156 | 157 | ```python 158 | >>> 'Ala has a cat'.count('has') 159 | 1 160 | >>> 'Ala has a cat but Ola has a dog'.count('has') 161 | 2 162 | ``` 163 | 164 | :snake: Copy the content of one of the paragraphs on this page, use it to define a string and use the `count` method on it to check how many times the following character sequences appear in it: `i`, `string`, and `on`. 165 | 166 | 167 | ## String length, `len` function 168 | 169 | One of the most useful operations we can perform on a string is to check its length. For example, we want to check if it is not too long, or we want to compare the length of two strings. Here, the `len` function comes in handy. 170 | 171 | ```python 172 | >>> len('Winnie the Pooh') 173 | 15 174 | ``` 175 | 176 | Note that `len` is not a method, so we do not use the notation `object.method()`. This is because checking the length of an object (in this case: string) is such a popular operation in Python that a separate function was created to perform it. 177 | 178 | :snake: Check the length of your first and last name. See what length an empty string, which is `''`, has. 179 | 180 | ## :pushpin: Summary 181 | 182 | In this chapter: 183 | 184 | * we have learned what a **string** is, 185 | * we have learned the meaning of the words **method** and **argument**, 186 | * we have learned the most important methods that can be called on a string, 187 | * we have learned the `len` function, which returns the length of the string. 188 | 189 | :checkered_flag: Next chapter: [`help` function](./03_help.md) 190 | :checkered_flag: 191 | -------------------------------------------------------------------------------- /english/03_help.md: -------------------------------------------------------------------------------- 1 | # Chapter 3. The `help` function 2 | 3 | In this chapter: 4 | 5 | * you will learn about the `help` function. 6 | 7 | 8 | ## Python Help 9 | 10 | Even the best programmer will never remember all the functions and methods that Python offers. During this training, you will learn many of them, but in a few days you will forget how they work. Don't worry, the creators of Python have thought about it... 11 | 12 | 13 | ## The documentation of method in Python 14 | 15 | Every method defined in Python has **documentation**, which describes its functionality in a few words. To read this documentation, you need to call the `help` function, for example: 16 | 17 | ```python 18 | >>> help('some string'.find) 19 | Help on built-in function find: 20 | 21 | find(...) 22 | S.find(sub [,start [,end]]) -> int 23 | 24 | Return the lowest index in S where substring sub is found, 25 | such that sub is contained within S[start:end]. Optional 26 | arguments start and end are interpreted as in slice notation. 27 | 28 | Return -1 on failure. 29 | ``` 30 | 31 | Documentation is not always written in simple language, but don't be discouraged. It's worth getting familiar with it from the very beginning. Read the above fragment again, and we will explain what each part means. 32 | 33 | The documentation shows all the arguments that a given method takes. 34 | This information is contained in the line "S.find(sub [,start [,end]])". 35 | Furthermore, the documentation informs about the type of result that is returned and briefly explains what this method does. This allows us to quickly remind ourselves about it. 36 | 37 | Note that in this example we did not open parentheses after the method name `find`, and therefore we did not provide any arguments. This way, instead of calling this method, we simply used its name. When we pass such a name to the `help` function, Python will show us the documentation for that method. 38 | 39 | :snake: Use the `help` function and read the documentation for the `replace` and `count` methods as well as the `len` function. 40 | 41 | 42 | ## :pushpin: Summary 43 | 44 | In this chapter: 45 | 46 | * we learned about the `help` function and found out that it's worth using when we don't understand a method or can't remember how it works. 47 | 48 | 49 | --- 50 | 51 | :checkered_flag: Next chapter: [Numbers](./04_numbers.md) :checkered_flag: 52 | -------------------------------------------------------------------------------- /english/04_numbers.md: -------------------------------------------------------------------------------- 1 | # Chapter 4. Numbers 2 | 3 | In this chapter: 4 | 5 | * you will learn what `integer` and `float` are, 6 | * you will learn how to perform arithmetic operations on numbers. 7 | 8 | ## Integers 9 | 10 | To define an integer, simply type it without putting spaces between the digits: 11 | 12 | ```python 13 | >>> 2024 14 | 2024 15 | ``` 16 | 17 | We can add and subtract numbers: 18 | 19 | ```python 20 | >>> 20 + 17 21 | 37 22 | >>> 2 + 0 + 1 + 7 23 | 10 24 | >>> 20 - 17 25 | 3 26 | >>> 20 - 1 - 7 27 | 12 28 | ``` 29 | 30 | ...multiply and divide: 31 | 32 | ```python 33 | >>> 20 * 17 34 | 340 35 | >>> 20 / 17 36 | 1.1764705882352942 37 | ``` 38 | 39 | ...divide completely: 40 | 41 | ```python 42 | >>> 20 // 17 43 | 1 44 | ``` 45 | 46 | ...raising to the power: 47 | 48 | ```python 49 | >>> 201 ** 7 50 | 13254776280841401 51 | ``` 52 | 53 | ...or to check the remainder of division (modulo): 54 | 55 | ```python 56 | >>> 20 % 17 57 | 3 58 | ``` 59 | 60 | We can combine all of these operations in any way we want. 61 | 62 | ```python 63 | >>> 20 / 2 + 17 * 3 64 | 61 65 | ``` 66 | 67 | If we want to have more control over the order of operations, we can use parentheses: 68 | 69 | ```python 70 | >>> (20 * (2 + 17)) / 3 71 | 126 72 | ``` 73 | 74 | :snake: Calculate the following values: 75 | 76 | * the sum of today's day, month number, and year, 77 | *t he result of dividing the year of your birth by the sum of the day and month on which you were born. 78 | 79 | 80 | ## Real numbers 81 | 82 | All of the above operations can also be performed on real numbers (**float**, floating-point): 83 | 84 | ```python 85 | >>> 2.5 * 2.0 86 | 5.0 87 | >>> 7 / 2.0 88 | 3.5 89 | >>> 6.7 + 0.3 - 2.5 90 | 4.5 91 | >>> 1.0 / 3 92 | 0.3333333333333333 93 | ``` 94 | 95 | :snake: Do you know when Python will return a *float* and when an *integer*? Make sure to check different combinations of numbers and operations. 96 | 97 | 98 | ## Operators and their order 99 | 100 | The symbols we use to perform operations (`+`, `*`, etc.) are called **operators**. 101 | Each operator has its own priority, which means that if multiple different operators are used in one operation (e.g. `2 + 1 * 3`), Python will first calculate those with a higher priority. 102 | 103 | For example, in such an operation: 104 | 105 | ```python 106 | >>> 4 + 10 * 6 107 | ``` 108 | 109 | First, multiplication will be performed and only then addition, because the `*` operator has a higher priority than `+`, which means the result will be `64`. 110 | 111 | The table below presents operators and their meanings. The order of rows corresponds to priority, meaning that operators with the highest priority are at the top and those with the lowest are at the bottom. 112 | 113 | Operators | Meaning 114 | --------- | --------- 115 | `**` | Exponentiation 116 | `*`, `/`, `//`, `%` | Multiplication, division, floor division, modulo 117 | `+`, `-` | Addition, subtraction 118 | 119 | ## :pushpin: Summary 120 | 121 | In this chapter: 122 | 123 | * we learned how to define **integers** and floating point numbers (**float**), and we also familiarized ourselves with the most important mathematical **operators** and their priorities. 124 | 125 | --- 126 | 127 | :checkered_flag: Next chapter: [Errors](./05_errors.md) :checkered_flag: 128 | -------------------------------------------------------------------------------- /english/05_errors.md: -------------------------------------------------------------------------------- 1 | # Chapter 5. Errors 2 | 3 | In this chapter: 4 | 5 | * you will learn what **exceptions** are, 6 | * how to read error messages. 7 | 8 | ## Exceptions 9 | 10 | When creating programs, we are never able to predict all the situations that may occur. Sometimes the user will provide data that our program is unable to process: for example, we expected a number but received text instead. Other times, we may make a mistake and call a method on an object that does not exist. In each of these situations, Python will respond by reporting an error. 11 | 12 | When this happens, the program will be interrupted and a message will be displayed, which will allow us to find out what our mistake was, which will allow us to correct the code of the program to avoid the same problem in the future. 13 | 14 | The words "error" or "problem" are very general, because they can also apply to things that as programmers we have no control over. That is why we use the term **exception**, which only refers to those cases that the programming language can handle - meaning those that our programs can react to. 15 | 16 | In practice, an exception is a situation in which Python has stopped executing the program because it encountered an *exceptional* situation that it was unable to handle on its own. It is said that the program **threw an exception**. When this happens, it is the role of the programmer to adjust the program in such a way that a similar situation does not result in a stop in the future. 17 | 18 | What are the unique situations we mentioned? It could be an attempt to perform an operation that Python is unable to execute, such as adding a number to text. Or an error of "not enough space on the hard drive" while saving a file. It is impossible to list all such possibilities - over time you will become familiar with the most common exceptions and learn to anticipate which operations may have caused them. 19 | 20 | ## How to read error messages and exceptions 21 | 22 | Let's try to trigger an error and see how our program behaves. 23 | Do you remember how we mentioned that we insert strings in single or double quotes, but you have to make sure that the closing quote is the same as the opening one? Let's do an experiment and see what happens when we break this rule. 24 | 25 | ```python 26 | >>> 'ala ma kota" 27 | Traceback (most recent call last): 28 | File "python", line 1 29 | 'ala ma kota" 30 | ^ 31 | SyntaxError: EOL while scanning string literal 32 | ``` 33 | 34 | As you can see, instead of displaying this phrase, Python reported an error. 35 | Let's read it line by line. 36 | 37 | * At the very beginning, we always see the message `Traceback (most recent call last):`. The word "traceback" refers to a list of operations that caused an error. In this case, only one operation was performed (returning the entered phrase), but in the future, you may encounter situations where an exception or error was thrown as a result of executing a whole sequence of commands. Python always shows the entire traceback so that the programmer can understand what went wrong. The text `most recent call last` indicates that the last operation on the list was executed most recently compared to all the others. 38 | 39 | * `File "python", line 1` is the traceback. In our case, it is only one line. Here we see a description of the place where the error occurred. 40 | 41 | * The last line contains the most important information, which is the direct cause of the error. It starts with the type of exception. In this case, it is `SyntaxError` - a syntax error. The type of error can be understood as a category: it does not tell us exactly what the error was, but it allows us to classify different exceptions to make them easier to understand. `SyntaxError` means an error in the syntax of the string of characters, which should follow each other according to the language syntax. Let's decipher the abbreviation EOL - end of line. After such a message, we know a little more about which part of our code to look at. Discovering the reason can be not easy. 42 | 43 | When creating more advanced programs, you will encounter even longer error messages. Don't let this discourage you: every exception comes down to just one incorrect operation, and a traceback, no matter how long, will help you locate the cause of the failure. If you still cannot understand why your program stopped working, paste the last line of the message into a search engine. It is very likely that someone has already encountered the same problem and found a solution. 44 | 45 | Exceptions are often a way for the program you're writing to communicate with the user running it. They help inform the user about what went wrong. Below, we can see how the error message for the same issue has changed between Python versions. 46 | 47 | In version 3.7, Python returned the error `SyntaxError: EOL while scanning string literal`, and without knowing what "EOL" means in programming jargon, it would be difficult to understand what the problem is with the provided string. 48 | 49 | In version 3.12, Python returns the error `SyntaxError: unterminated string literal (detected at line 1)`, which is more understandable because it directly informs us that the provided string is simply not closed. 50 | 51 | ```python 52 | # Python version 3.7 53 | >>> 'ala ma kota" 54 | Traceback (most recent call last): 55 | File "python", line 1 56 | 'ala ma kota" 57 | ^ 58 | SyntaxError: EOL while scanning string literal 59 | 60 | # Python version 3.12 61 | >>> 'ala ma kota" 62 | File "python", line 1 63 | 'ala ma kota" 64 | ^ 65 | SyntaxError: unterminated string literal (detected at line 1) 66 | ``` 67 | 68 | :snake: Invoke errors and read exceptions caused by the following operations: division by zero; calling the lower() method on any digit; calling a method on any string that does not exist; executing code that does not make sense (you can enter a random string of characters). 69 | 70 | ## :pushpin: Summary 71 | 72 | In this chapter: 73 | 74 | * we have learned what an **exception** is and how to read its content. 75 | 76 | --- 77 | 78 | :checkered_flag: Next chapter: [Variables](./06_variables.md) :checkered_flag: 79 | -------------------------------------------------------------------------------- /english/06_variables.md: -------------------------------------------------------------------------------- 1 | # Chapter 6. Variables 2 | 3 | In this chapter: 4 | 5 | You will learn what a **variable** is, how to define it, and how to use it. 6 | 7 | ## Variable 8 | 9 | In the previous chapters, we performed various operations: we defined strings, multiplied numbers, etc. Each of these operations returned a result, which was immediately displayed on the screen. The text and numbers that we created in this way were stored in the computer's memory only for a moment and were immediately deleted from it after being displayed. Therefore, in subsequent operations, we could not use the results from previous operations. 10 | 11 | To handle the issue of storing the result of an operation, we use **variables**. Instead of explaining how variables work, it is best to look at an example: 12 | 13 | ```python 14 | >>> x = 7 15 | >>> x 16 | 7 17 | >>> 5 + x 18 | 12 19 | ``` 20 | 21 | Let's analyze what happened in the above example. At the beginning, we **defined a variable**, which means we assigned the result of some operation to a name. In this case, the operation is simply defining the number `7`, while the name is `x`. From this moment on, we could use the **variable** `x` in subsequent operations. If we simply type its name, we will get its **value**. We can also use it in another operation, for example by adding it to another number. 22 | 23 | When defining variables, we can use other variables as well. 24 | 25 | ```python 26 | >>> a = 10 27 | >>> b = 5 28 | >>> c = a + b 29 | >>> c 30 | 15 31 | ``` 32 | 33 | Of course, in a real-life scenario, we name variables in such a way that they tell us what they represent. 34 | 35 | ```python 36 | >>> net_price = 120 37 | >>> vat_tax = net_price * 0.23 38 | >>> gross_price = net_price + vat_tax 39 | >>> gross_price 40 | 147.6 41 | ``` 42 | 43 | ## Assignment 44 | 45 | The operation `variable = value` is called **assignment**. As a result of the assignment, Python creates a *variable* that receives the *value*. If the value is an operation (e.g. addition), its result is first calculated and then assigned to the variable. 46 | 47 | 48 | ## Variable names 49 | 50 | When creating a variable, we must first come up with a name for it. Above all, it should directly indicate the meaning of the variable. Thanks to this, as in the example above, we will be able to easily understand the program code. 51 | 52 | In addition, Python imposes several restrictions on the characters we can use in variable names. Allowed characters include: 53 | 54 | * letters from `a` to `z` (lowercase) and from `A` to `Z` (uppercase), 55 | * numbers, 56 | * symbol `_` (underscore). 57 | 58 | All other characters are not allowed. Importantly, the name cannot start with a number! 59 | 60 | :snake: Create variables `name` and `surname`, assign your name and surname to them. Then, based on them, create a variable `full_name` that will contain your name and surname separated by a space. 61 | 62 | :snake: See what happens when you try to create a variable whose name starts with a number. 63 | 64 | 65 | ## Changing the value of a variable 66 | 67 | At any time, we can change the value of a variable. 68 | 69 | ```python 70 | >>> x = 'Ala ma kota' 71 | >>> x 72 | 'ala ma kota' 73 | >>> x = 'kot ma Alę' 74 | >>> x 75 | 'kot ma Alę' 76 | >>> x = x + '.' 77 | >>> x 78 | 'kot ma Alę.' 79 | ``` 80 | 81 | ## Variables and their methods 82 | 83 | In previous chapters, we called various methods, such as `find` or `title`. Notice that methods that can be performed directly on an object can also be performed on a variable. 84 | 85 | ```python 86 | >>> imie_nazwisko = 'jan kowalski' 87 | >>> imie_nazwisko 88 | 'jan kowalski' 89 | >>> imie_nazwisko.title() 90 | 'Jan Kowalski' 91 | >>> imie_nazwisko 92 | 'jan kowalski' 93 | >>> imie_nazwisko = imie_nazwisko.title() 94 | >>> imie_nazwisko 95 | 'Jan Kowalski' 96 | ``` 97 | 98 | ## :pushpin: Summary 99 | 100 | In this chapter: 101 | 102 | * we have learned what a variable is, how to define it, and how to use it. 103 | 104 | --- 105 | 106 | :checkered_flag: Next chapter: [Functions](./07_functions.md) :checkered_flag: 107 | -------------------------------------------------------------------------------- /english/07_functions.md: -------------------------------------------------------------------------------- 1 | # Chapter 7. Functions 2 | 3 | In this chapter: 4 | 5 | You will learn how to define **functions**. 6 | 7 | 8 | # What is a function 9 | 10 | So far, we have learned what a *string*, *integer*, and *float* are, as well as how to use variables to store values between operations. This allows us to write a program that performs operations on data, for example processing text or performing calculations, and then displays the result on the screen. The more advanced problems we want to solve with our program, the more complex its code will be. 11 | 12 | One way to write more understandable code is by defining functions. **Function** is a separate set of instructions that can be executed multiple times in a program. **Function definition** is a way of describing which operations should be included in the function. 13 | 14 | For example, the following function returns a number squared: 15 | 16 | The following is a function in Python that calculates the square of a number and returns the result. 17 | 18 | ```python 19 | def square(number): 20 | result = number ** 2 21 | return result 22 | ``` 23 | 24 | * the word `def`, 25 | * **name** of the function (in this example it's `square`), 26 | * **list of arguments** enclosed in parentheses (here we have one argument `number`, but we can provide multiple, separating them with commas), 27 | * colon. 28 | 29 | Pay attention to spaces! In the entire header, there is only a space between the word `def` and the function name. If the function had multiple arguments separated by commas, we could insert spaces next to the commas to improve the readability of the code. Apart from these two cases, there should not be any more spaces in the header. 30 | 31 | In the following lines after the header we have the **body of the function**. These are simply instructions that will be executed when we use the function. In the example above, the body contains two operations: squaring the value of the variable `number` and assigning it to the variable `result`, and returning the value of the variable `result`. **Returning** is the specification of what value should be the result of the given function. The word `return` is used for this purpose. If we type the name of the variable after it, its value will be the result. We can also return a result without assigning it to a variable beforehand. 32 | 33 | ```python 34 | def square(number): 35 | return number ** 2 36 | ``` 37 | 38 | ## Working with the editor 39 | 40 | Before defining your first function, let's pause for a moment. So far, all operations have been performed in interactive mode, where we entered the code, pressed Enter and received the result. When we start working with functions, this approach may prove to be cumbersome. It will be much more convenient to switch to an **editor** now. 41 | 42 | From now on, every example that does not start with `>>>` should be understood as code typed in the editor and run by clicking the "run" button. 43 | 44 | 45 | ## Definition and calling a function 46 | 47 | Now copy the code of the function saved below into the editor. Pay special 48 | attention to **indentation**. Each line of the function body must begin with 49 | an indentation. Importantly, all of these indentations **must have the same 50 | width**. This means that if you indent the first line by two spaces, then all 51 | of the remaining lines until the end of the function must also be indented by 52 | two spaces. As you will notice, the editor will automatically indent when you 53 | press Enter after typing the header. If it does not do so, then the easiest 54 | way to indent is by using the Tab key. 55 | 56 | ```python 57 | def square(number): 58 | result = number ** 2 59 | return result 60 | ``` 61 | 62 | Press the "run" button now. If you don't notice any errors in the interactive mode window, it means that the function has been defined correctly. Now we can call it in interactive mode. 63 | 64 | ```python 65 | >>> kwadrat(5) 66 | 25 67 | >>> kwadrat(3) + kwadrat(1) 68 | 10 69 | ``` 70 | 71 | As you can see, to call a function, you just need to enter its name, followed by 72 | the argument value in parentheses. If there are multiple arguments, they should be separated by commas. 73 | 74 | :snake: Define a function named `circle_area` that takes an argument `radius` and returns the value of the equation `3.14 * (radius ** 2)`. Call it in the interactive mode window. 75 | 76 | Call the `circle_area` function without an argument: `circle_area()`. Do you understand the message of the exception that was thrown? 77 | 78 | Call the `circle_area` function with two arguments: `circle_area(2, 3)`. 79 | Compare the exception message to the error from the previous task. 80 | 81 | 82 | ## Arguments 83 | 84 | The function does not have to have any arguments, in this case we leave the parentheses in the header empty. 85 | 86 | ```python 87 | def function_without_arguments(): 88 | return 123 89 | ``` 90 | 91 | As we have mentioned, functions can take more than one argument. 92 | 93 | ```python 94 | def sum(a, b): 95 | return a + b 96 | 97 | 98 | def person(name, surname, title): 99 | name_surname = name + ' ' + surname 100 | return title + ' ' + name_surname.title() 101 | ``` 102 | 103 | We call these functions similarly to those with one argument. 104 | 105 | ```python 106 | >>> function_without_arguments() 107 | 123 108 | >>> sum(100, 45) 109 | 145 110 | >>> sum(100, -20) 111 | 80 112 | >>> person('jan', 'KOWALSKI', 'doctor') 113 | 'doctor Jan Kowalski' 114 | ``` 115 | 116 | :snake: Write a function `gross_price` that takes arguments `net_price` and `vat` and returns the gross value calculated according to the formula `net_price * (1 + vat)`. 117 | 118 | :snake: Write a function `first_last_name` that takes arguments `first_name` and `last_name` and returns a string with the first and last name separated by a space. Make sure that each word in the string starts with a capital letter (use the `title` method). Then write a function `likes`, with arguments `first_name`, `last_name` and `what` and called like this: `likes('jan', 'kowalski', 'CAULIFLOWERS')` will return the string `'Jan Kowalski likes cauliflower'`. When writing the `likes` function, use the `first_last_name` function. 119 | 120 | 121 | ## Built-in functions 122 | 123 | In addition to the functions that we can define ourselves, there are functions that are always available in the Python interpreter. We call them **built-in functions**. An example is the `len` function, which we mentioned in one of the previous chapters: 124 | 125 | ```python 126 | >>> len('python') 127 | 6 128 | ``` 129 | 130 | In addition, we also have [67 other built-in functions](https://docs.python.org/3/library/functions.html). You will learn about some of them in the following chapters, and we have described a few others below. 131 | 132 | ### `str` 133 | 134 | It takes any object as an argument and returns its representation as a string. 135 | 136 | ```python 137 | >>> str(2017) 138 | '2017' 139 | ``` 140 | 141 | :snake: Convert to string a negative number. 142 | 143 | :snake: See what happens when you pass text as an argument to `str`. 144 | 145 | 146 | ### `int` 147 | 148 | It takes any object as an argument and converts it to an integer. 149 | 150 | ```python 151 | >>> int(' 123 ') 152 | 123 153 | ``` 154 | 155 | :snake: See what happens when you pass a number with a decimal part (float) to the `int` function, for example `3.14`. 156 | 157 | :snake: See what happens if you pass a string with no numbers to `int`. 158 | 159 | :snake: See what happens when you pass a string with both letters and numbers to `int`, for example `Ala has 2 cats`. 160 | 161 | 162 | ### `float` 163 | 164 | It takes any object as an argument and converts it to a float. 165 | 166 | ```python 167 | >>> float('3.14') 168 | 3.14 169 | ``` 170 | 171 | :snake: See how the `float` function will behave when called with: 172 | an integer, a string with only letters, a string with only numbers. 173 | 174 | ## :pushpin: Summary 175 | 176 | In this chapter: 177 | 178 | * we have learned what a function is, how to define and call it, 179 | * we have also familiarized ourselves with built-in functions such as `str`, `int`, and `float`. 180 | 181 | --- 182 | 183 | :checkered_flag: Next chapter: [`print` function](./08_print_function.md) :checkered_flag: 184 | -------------------------------------------------------------------------------- /english/08_print_function.md: -------------------------------------------------------------------------------- 1 | # Chapter 8. `print` function 2 | 3 | In this chapter: 4 | 5 | * you will learn about the built-in function `print`. 6 | 7 | 8 | ## Printing text on the screen 9 | 10 | When we were using the interactive mode and wanted to print something on the screen, all we had to do was enter an expression and press Enter. 11 | 12 | ```python 13 | >>> 2 + 2 14 | 4 15 | >>> x = 'PyLadies' 16 | >>> x 17 | 'PyLadies' 18 | ``` 19 | 20 | We were able to do this because interactive mode works in this way: it performs an operation and displays its result. However, Python programs are usually more complex and it often happens that we want to see more than just the result of the last operation. For example, when we write a program that processes a text file and we want it to print something on the screen for each line of text. In such cases, the built-in function `print` comes in handy. 21 | 22 | 23 | ## `print` 24 | 25 | This function takes any number of arguments and prints them all to the screen, separating them with spaces: 26 | 27 | ```python 28 | >>> print(2024) 29 | 2024 30 | >>> print('PyCon PL', 2024) 31 | PyCon PL 2024 32 | ``` 33 | 34 | In addition, variables can also be passed to `print`. 35 | 36 | ```python 37 | >>> temperature = 24 38 | >>> print('Temperature:', temperature, 'degrees') 39 | Temperature: 24 degrees 40 | ``` 41 | 42 | :snake: Write a function that takes an argument `year_of_birth`, prints the text `You are X years old`, where `X` is the age in 2017, and returns that age. 43 | 44 | 45 | ## Formatting strings 46 | 47 | At this point, it's worth going back to strings and talking about one more very useful method: `format`. It is used for **formatting strings**, which means "inserting" variable values into them. Take a look at the example below: 48 | 49 | ```python 50 | >>> 'ala {} a cat'.format('has') 51 | 'ala has a cat' 52 | ``` 53 | 54 | As you can see, calling the `format` method caused the pair of characters `{}` to be replaced with function arguments. In a similar way, we can insert any number and type of objects. 55 | 56 | ```python 57 | >>> width = 110 58 | >>> height = 50.5 59 | >>> unit = 'mm' 60 | >>> '{}x{} {}'.format(width, height, unit) 61 | '110x50.5 mm' 62 | ``` 63 | 64 | The capabilities of the `format` method are not limited to simply inserting values into a string. The [Python documentation](https://docs.python.org/3.12/library/string.html#formatspec) provides a detailed description of this function. It is worth taking a look at the examples provided there. 65 | 66 | :snake: See what happens if the number of arguments of the `format` method is __less__ than the number of occurrences of `{}` in the string. 67 | 68 | 69 | ## :pushpin: Summary 70 | 71 | In this chapter: 72 | 73 | * we have learned about the `print` function and the `format` method. 74 | 75 | --- 76 | 77 | :checkered_flag: Next chapter: [Lists](./09_lists.md) :checkered_flag: 78 | -------------------------------------------------------------------------------- /english/09_lists.md: -------------------------------------------------------------------------------- 1 | # Chapter 8. Lists 2 | 3 | In this chapter: 4 | 5 | * you will learn what **lists** are, 6 | * you will get to know methods `append`, `pop`, `count`, `remove` and `index`, 7 | * you will learn built-in functions `sum`, `max`, `min` and `sorted`. 8 | 9 | ## List 10 | 11 | Lists accompany us every day. When we want to listen to music, we play a playlist. In the store, we look at the shopping list. When searching for something on the internet, we browse the list of results. 12 | 13 | If we think about it further, we will notice that many other phenomena and things can be presented in the form of a list: a collection of books in a library, events from a certain period, tasks to be completed, a line of cars at a gas station, etc. List is a very important concept in programming, as it allows us to easily describe a set of objects that are arranged in a certain order: alphabetical, chronological, random, etc. Lists in Python are a powerful yet simple tool that is used almost every step of the way. 14 | 15 | To define a list, you need to list objects (strings, integers) separated by commas in square brackets: 16 | 17 | ```python 18 | >>> colors = ['blue', 'red', 'green', 'black'] 19 | >>> print(colors) 20 | ['blue', 'red', 'green', 'black'] 21 | ``` 22 | 23 | In this way, we define an empty list: 24 | 25 | ```python 26 | >>> empty_list = [] 27 | >>> print(empty_list) 28 | [] 29 | ``` 30 | 31 | We can refer to individual list elements by entering their name, followed by the index number in square brackets. Remember that the numbering starts at zero! 32 | 33 | ```python 34 | >>> print(colors[0]) 35 | blue 36 | >>> print(colors[2]) 37 | green 38 | ``` 39 | 40 | To obtain the last element on the list, we can use the index `-1`: 41 | 42 | ```python 43 | >>> print(colors[-1]) 44 | black 45 | ``` 46 | 47 | **Negative index** is a way to access elements of a list from the end. 48 | 49 | ```python 50 | >>> print(colors[-2]) 51 | green 52 | >>> print(colors[-3]) 53 | red 54 | ``` 55 | 56 | We can freely mix types of elements on the list. 57 | 58 | ```python 59 | >>> numbers = ['one', 2, 'three', 4, 5] 60 | ``` 61 | 62 | The list may also contain other lists within it: 63 | 64 | ```python 65 | >>> shades_of_red = ['crimson', 'red', 'burgundy'] 66 | >>> colors = ['green', shades_of_red, 'blue'] 67 | >>> print(colors) 68 | ['green', ['crimson', 'red', 'burgundy'], 'blue'] 69 | ``` 70 | 71 | :snake: Write a function `element` that takes two arguments, a list and an index number (integer), and returns the element of the list located at the given index. 72 | 73 | :snake: Write a function `last_element` that takes a list as an argument and returns its last element. Use the `element` function in it. 74 | 75 | 76 | ## List's methods 77 | 78 | Lists, similar to strings, have many methods. Below you will find a description of several of the most useful ones. 79 | 80 | ### `append` 81 | 82 | This method is used to add an element to a list. 83 | 84 | ```python 85 | >>> numbers = [1, 3] 86 | >>> print(numbers) 87 | [1, 3] 88 | >>> numbers.append(5) 89 | >>> print(numbers) 90 | [1, 3, 5] 91 | >>> numbers.append(7) 92 | >>> print(numbers) 93 | [1, 3, 5, 7] 94 | ``` 95 | 96 | :snake: Write a function that takes a list as an argument and adds the same element at the end as it is at the very beginning. 97 | 98 | 99 | ### `pop` 100 | 101 | The `pop` method does not take any arguments and returns the last element of the list, while also removing it from the list. 102 | 103 | ```python 104 | >>> letters = ['a', 'b', 'c', 'd'] 105 | >>> print(letters) 106 | ['a', 'b', 'c', 'd'] 107 | >>> letters.pop() 108 | 'd' 109 | >>> print(letters) 110 | ['a', 'b', 'c'] 111 | >>> letters.pop() 112 | 'c' 113 | >>> letters.pop() 114 | 'b' 115 | >>> print(letters) 116 | ['a'] 117 | ``` 118 | 119 | :snake: Write a function that removes the last two elements from a list, and then adds to it the element that was last at the beginning. 120 | 121 | 122 | ### `count` 123 | 124 | `count` takes one arbitrary object as an argument and returns the number of occurrences of that object in the list. 125 | 126 | ```python 127 | >>> grades = [4, 3, 3, 5, 2, 3, 5, 4, 2, 4, 5, 4, 3, 3] 128 | >>> grades.count(3) 129 | 5 130 | >>> grades.count(4) 131 | 4 132 | >>> grades.count(2) 133 | 2 134 | ``` 135 | 136 | ### `remove` 137 | 138 | The `remove` method takes any object as an argument and removes it from the list. If the object appears multiple times on the list, only its first occurrence is removed. 139 | 140 | ```python 141 | >>> numbers = [10, 20, 25, 20, 10, 15] 142 | >>> numbers.remove(20) 143 | >>> print(numbers) 144 | [10, 25, 20, 10, 15] 145 | >>> numbers.remove(20) 146 | >>> print(numbers) 147 | [10, 25, 10, 15] 148 | >>> numbers.remove(10) 149 | >>> print(numbers) 150 | [25, 10, 15] 151 | ``` 152 | 153 | :snake: Check what happens if we try to remove an element that is not on the list. 154 | 155 | W:snake: rite a function that takes two arguments: a list and any other object. The function should remove the first occurrence of this object from the list and then add it to the end of the list. The function should return the number of occurrences of this element in the list. 156 | 157 | 158 | ### `index` 159 | 160 | The `index` function takes one object as an argument and returns the position number at which this object is located on the list. 161 | 162 | ```python 163 | >>> letters = ['r', 't', 'b', 'w', 'h'] 164 | >>> letters.index('t') 165 | 1 166 | >>> letters.index('h') 167 | 4 168 | ``` 169 | 170 | :snake: Check what happens if we try to retrieve the index of an element that does not exist on the list. 171 | 172 | ## Lists and `len' function 173 | 174 | Similarly to strings, we can check the length of a list using the built-in function `len`: 175 | 176 | ```python 177 | >>> last_name_letters = ['K', 'o', 'w', 'a', 'l', 's', 'k', 'i'] 178 | >>> print(len(last_name_letters)) 179 | 8 180 | ``` 181 | 182 | 183 | ## Built-in functions `sum`, `min`, `max`, and `sorted` 184 | 185 | There are several built-in functions that help us work with lists. Here we will describe some of them. 186 | 187 | The first three are most helpful when we operate on lists where all elements are numbers. `sum` returns the sum of all elements, `min` returns the element with the smallest value, and `max` returns the one with the largest value. 188 | 189 | ```python 190 | >>> measurements = [2, 4.25, 5.30, 3] 191 | >>> sum(measurements) 192 | 14.55 193 | >>> min(measurements) 194 | 2 195 | >>> max(measurements) 196 | 5.3 197 | ``` 198 | 199 | :snake: Write a function that takes a list as an argument and prints to the screen the element with the highest value and the number of occurrences of that element in the list. 200 | 201 | Another function is `sorted`, which takes a list and returns a sorted copy of that list. 202 | 203 | ```python 204 | >>> results = [45.5, 47.2, 35.8, 41.0, 33.3] 205 | >>> sorted_results = sorted(results) 206 | >>> print(sorted_results) 207 | [33.3, 35.8, 41.0, 45.5, 47.2] 208 | >>> print(results) 209 | [45.5, 47.2, 35.8, 41.0, 33.3] 210 | ``` 211 | 212 | :snake: Write a function that takes in a list as an argument, sorts it, and then returns its last element. (This way we will get our own version of the `max` function!) 213 | 214 | 215 | ## List snippets 216 | 217 | Sometimes when operating on a list, we would like to use only a fragment of it, for example the first 10 elements or elements from the second to the fifth. Python is prepared for such a situation: it allows for creating a *slice* of a list. To create a slice, you need to enter the name of the list, followed by square brackets with the indexes of the first and last element of the slice separated by a colon. 218 | 219 | For example, returning a fragment of the list from the second to the fourth element will look like this: 220 | 221 | ```python 222 | >>> list_elements = [1, 2, 3, 4, 5, 6, 7] 223 | >>> list_elements[1:4] 224 | [2, 3, 4] 225 | ``` 226 | 227 | Remember that list indexes start at zero, and the element at the ending index (in this case: `5`) will not be included in the slice. 228 | 229 | We can also omit the starting index. In this case, Python will return all elements from the beginning. 230 | 231 | ```python 232 | >>> list_elements[:5] 233 | [1, 2, 3, 4, 5] 234 | ``` 235 | 236 | If we omit the end index, we will get all elements until the end of the list. 237 | 238 | ```python 239 | >>> list_elements[2:] 240 | [3, 4, 5, 6, 7] 241 | ``` 242 | 243 | If the end index is a negative number, then the position of the last element in the slice will be counted from the end of the list. 244 | 245 | ```python 246 | >>> list_elements[:-1] 247 | [1, 2, 3, 4, 5, 6] 248 | >>> list_elements[:-2] 249 | [1, 2, 3, 4, 5] 250 | ``` 251 | 252 | Interestingly, we can also create fragments from strings: 253 | 254 | ```python 255 | >>> text = 'ala ma kota' 256 | >>> text[2:8] 257 | 'a ma k' 258 | ``` 259 | 260 | :snake: See what happens if the starting index is a negative number, or if the ending index is greater than the length of the list. 261 | 262 | ## :pushpin: Summary 263 | 264 | In this chapter: 265 | 266 | * we learned what lists are, how to define them, and how to refer to individual list elements. 267 | * we also learned the most important list methods. 268 | * we learned how to use built-in functions `len`, `sum`, `max`, `min`, and `sorted` on lists. 269 | 270 | --- 271 | 272 | :checkered_flag: Next chapter: [`for` loop](./10_for.md) :checkered_flag: 273 | 274 | -------------------------------------------------------------------------------- /english/10_for.md: -------------------------------------------------------------------------------- 1 | # Chapter 10. `for` loop 2 | 3 | In this chapter: 4 | 5 | * you will learn what **iteration** and **loop** are, 6 | * you will get to know the `for` loop. 7 | 8 | 9 | ## Iteration 10 | 11 | When we operate on a list, we often want to "iterate" through all of its elements one by one and perform some operation on each of them. This type of "iteration" is called **iteration**. In Python, to get each element of the list in order, we can of course use indexes: 12 | 13 | ```python 14 | >>> dates = ['15/07/2017', '16/07/2017', '17/07/2017'] 15 | >>> print(dates[0]) 16 | 15/07/2017 17 | >>> print(dates[1]) 18 | 16/07/2017 19 | >>> print(dates[2]) 20 | 17/07/2017 21 | ``` 22 | 23 | However, this approach is inconvenient when the list is very long. 24 | But what if we don't even know how long the list is? These problems can be solved using **loops**, which are instructions that execute certain operations until a condition is met. With loops, we can, for example, iterate, meaning perform operations on each element of the list until we reach the end of the list. 25 | 26 | ## For loop 27 | 28 | Loops have many uses, but iteration is one of the most commonly encountered. That is why Python has a `for` loop, which is used precisely for this purpose. Let's look at an example: 29 | 30 | ```python 31 | departure_hours = ['7:30', '13:45', '16:10'] 32 | for hour in departure_hours: 33 | print(hour) 34 | ``` 35 | 36 | Copy and execute the above code in the editor. In the interactive mode window, you will see that the `print` function was executed for each element on the list, displaying it on the screen. This happened because Python went through all the elements on the `departure_hours` list and assigned their values to the `hour` variable, then executed the `print` operation. 37 | 38 | The definition of a loop starts with the word `for`, then the name of the 39 | variable to which the values of each element will be assigned, followed by 40 | the word `in`, the name of the list, and a colon. In the following lines, 41 | there are operations that will be performed for each element. 42 | Remember that each operation must be indented in the code in the same way. 43 | Their width does not matter, it is important that they are the same. 44 | 45 | If the loop is inside a function, then the indentation inside the `for` should be increased by the function's indentation width. 46 | 47 | ```python 48 | def print_elements(list_elements): 49 | for element in list_elements: 50 | print(element) 51 | ``` 52 | 53 | :snake: Write a function that takes a list of numbers as an argument and prints out the squared value of each of them on the screen. 54 | 55 | :snake: Write a function that takes a list of strings and returns a new list, on which all these strings will be written in uppercase (use the `upper` method). 56 | 57 | ## `For` and strings 58 | 59 | The `for` loop is very versatile: you can also use it on a string. In this case, its elements will be individual letters. 60 | 61 | ```python 62 | for letter in 'ala has a cat': 63 | print(letter) 64 | ``` 65 | 66 | :snake: Write a function that takes a string as an argument and prints each letter along with the number of occurrences of that letter in the string (use the `count` method). 67 | 68 | 69 | ### The `split` method 70 | 71 | We can also iterate through words. To do this, we use the `split` method. 72 | 73 | ```python 74 | for word in 'ala has a cat'.split(): 75 | print(slowordwo) 76 | ``` 77 | 78 | In fact, the `split` method has much broader application. If we provide a character as an argument, then the string will be divided at the locations where this character appears. 79 | 80 | ```python 81 | >>> text = '2015,2016,2017' 82 | >>> text.split(',') 83 | ['2015', '2016', '2017'] 84 | ``` 85 | 86 | If no argument is passed, the string will be split at spaces. 87 | 88 | ```python 89 | >>> 'ala has a cat'.split() 90 | ['ala', 'has', 'a', 'cat'] 91 | ``` 92 | 93 | :snake: Write a function that takes a string as an argument and prints all of its words, each on a separate line. 94 | 95 | 96 | ## `range` 97 | 98 | It is worth mentioning the built-in function `range` in this place. It takes two integers as arguments: the beginning and end of a numerical range that it returns. We can then iterate through such a range and the elements will be consecutive integers. 99 | 100 | ```python 101 | for num in range(10, 20): 102 | print(num) 103 | ``` 104 | 105 | In the above example, we print out integers from 10 to 19. The number that we specified as the end of the range is not included in it. 106 | 107 | Interestingly, we can only provide one argument, which is then treated as the end of the range, while 0 is taken as the start. The next example shows how to print numbers from 0 to 99. 108 | 109 | ```python 110 | for num in range(100): 111 | print(num) 112 | ``` 113 | 114 | Write a function that takes one argument named `limit` and returns a list of values from 0 to `limit` squared. 115 | 116 | 117 | ## :pushpin: Summary 118 | 119 | In this chapter: 120 | 121 | * we learned the concepts of *iteration* and *loop*, 122 | * we learned how to use the `for` loop, 123 | * we found out that the `for` loop also works on strings, and that 124 | strings have the `split` method, 125 | * we learned about the built-in function `range`. 126 | 127 | 128 | --- 129 | 130 | :checkered_flag: Next chapter: [Tuples](./11_tuples.md) :checkered_flag: 131 | -------------------------------------------------------------------------------- /english/11_tuples.md: -------------------------------------------------------------------------------- 1 | # Chapter 11. Short description 2 | 3 | In this chapter: 4 | 5 | * you will learn what a **tuple** is. 6 | 7 | 8 | ## Tuple 9 | 10 | When reading code of programs written in Python, you will quickly come across something that may seem very similar to a list: 11 | 12 | ```python 13 | currencies = ('EUR', 'PLN', 'USD') 14 | ``` 15 | 16 | The above example is a definition of a **tuple**. At first glance, it differs from a list only in that it uses round brackets instead of square brackets. However, a tuple has one important characteristic that sets it apart from a list: it cannot be modified. This means that once a tuple is created, elements cannot be added, removed, or changed. Therefore, we will not find methods such as `append` or `remove` in a tuple. However, we can successfully refer to individual elements using their indexes. 17 | 18 | ```python 19 | >>> currencies[1] 20 | 'PLN' 21 | ``` 22 | 23 | This means that we can also iterate through a tuple using a `for` loop. If we pass a tuple to the `len` function, we will get the number of its elements. 24 | 25 | :snake: Write a function that takes a tuple as an argument and returns a list with exactly the same elements. 26 | 27 | 28 | ## Usage of tuples 29 | 30 | At first glance, a tuple may seem completely unnecessary. Why do we need such a list that cannot be modified? However, in many cases, we need exactly something like this. A good example is a set of currency names. Imagine that we are writing a program to convert monetary values between different currencies. In our program, exchange rates will change, but the currencies themselves will remain the same. Therefore, we can define them in a tuple, thus protecting ourselves from modifying the set of currencies, which would be undesirable. Even if we want to add another currency in the future, it will be easier to release a new version of the program than to risk modifying the set, which should remain unchanged. 31 | 32 | There are more similar examples and by reading the code of various programs, you will quickly realize that tuples are more useful than it may seem. 33 | 34 | ## :pushpin: Summary 35 | 36 | In this chapter: 37 | 38 | * we learned what a tuple is and what operations we can perform on it. 39 | 40 | 41 | --- 42 | 43 | :checkered_flag: Next chapter: [True and false](./12_true_and_false.md) :checkered_flag: 44 | -------------------------------------------------------------------------------- /english/12_true_and_false.md: -------------------------------------------------------------------------------- 1 | # Chapter 12. True and False 2 | 3 | In this chapter: 4 | 5 | * you will learn the concepts of "truth" and "false" and their representation in Python: `True` and `False`, 6 | * you will learn the **conditional statement** `if`, which allows you to change the course of the program if a certain condition is met. 7 | 8 | 9 | ## True and False conditions 10 | 11 | The programs we have written so far consisted of operations that Python 12 | executed one after another. When one instruction was successfully 13 | completed, the program moved on to the next one. 14 | When writing more programs, you will quickly realize that this scenario 15 | will not always suit you, because often we want certain operations to be 16 | performed only when a certain condition is met. 17 | 18 | For example, we have a list of numbers and we want to iterate through its elements, printing only the odd ones. In this case, the condition for printing the number on the screen is "the number is odd". 19 | 20 | Programming languages allow us to define such conditions and check them. The result of such a check is **true** or **false**. True indicates a situation in which the condition has been fulfilled. The opposite is false. For example, the result of the condition "a giraffe is a bird" is false, while the result for "the Earth is not flat" is true. 21 | 22 | Of course, in programs, such abstract conditions are not created. Instead, we will compare variable values, check if the result of a function has a specific value, etc. In this chapter, you will learn how to perform such operations and how to write programs that execute different instructions depending on whether a certain condition has been met. 23 | 24 | 25 | ## Conditions in Python, `True` and `False` 26 | 27 | In Python, we have a range of operators at our disposal that allow us to check the truthfulness of expressions. We can, for example, compare values. The operator `==` is used for this purpose. 28 | 29 | ```python 30 | >>> 1 == 2 31 | False 32 | >>> (2 + 2) == (2 * 2) 33 | True 34 | ``` 35 | 36 | The opposite of the `==` operator is `!=`. 37 | 38 | ```python 39 | >>> 'ala' != 'Ala' 40 | True 41 | >>> [1, 2] != [1, 2] 42 | False 43 | ``` 44 | 45 | We can also check if one value is greater or less than the other: 46 | 47 | ```python 48 | >>> 100 > 70 49 | True 50 | >>> 70 > 100 51 | False 52 | ``` 53 | 54 | The operators `>` and `<` can be combined with `=`, creating the conditions "greater than or equal to" and "less than or equal to". 55 | 56 | ```python 57 | >>> 3 >= 2 58 | True 59 | >>> 2 >= 2 60 | True 61 | >>> 1 >= 2 62 | False 63 | ``` 64 | 65 | Note that in one expression, multiple operators can be used. 66 | 67 | ```python 68 | >>> 1 <= 2 < 3 <= 3 < 4 69 | True 70 | ``` 71 | 72 | Furthermore, we can negate the entire expression by writing `not` at the beginning. 73 | 74 | ```python 75 | >>> not 1 == 1 76 | False 77 | >>> not 1 == 2 78 | True 79 | ``` 80 | 81 | Of course, in each case, we can replace the values entered directly with variables and preserve the result of the expression. 82 | 83 | ```python 84 | >>> temperature = 26 85 | >>> is_cold = temperature < 10 86 | >>> print(is_cold) 87 | False 88 | ``` 89 | 90 | 91 | ## Comparing strings 92 | 93 | Comparing numbers seems understandable, but how are strings compared? The answer is simpler than it may seem: alphabetically. Letters that come later in the alphabet are considered "greater" than those that come earlier. Additionally, lowercase letters are considered "greater" than uppercase letters. 94 | 95 | ```python 96 | >>> 'A' < 'B' < 'a' < 'b' 97 | True 98 | ``` 99 | 100 | What about strings that have more than one character? They are compared 101 | character by character until one of them is different, or until one of 102 | the strings is longer. In the latter case, the string with more characters will be greater. 103 | 104 | ```python 105 | >>> 'a' < 'ala' 106 | True 107 | >>> 'ala' == 'ala' 108 | True 109 | >>> 'ala' < 'ala ma kota' 110 | True 111 | ``` 112 | 113 | 114 | ## `in` operator 115 | 116 | In addition to the operators discussed so far, there is one more that is useful, especially when working with lists. The `in` operator returns `True` if a given element is present in the list. 117 | 118 | ```python 119 | >>> 'Basia' in ['Tomek', 'Magda', 'Karol', 'Basia'] 120 | True 121 | >>> 12 in [10, 20, 30, 40] 122 | False 123 | ``` 124 | 125 | ## `if` statement 126 | 127 | Checking if an expression is true would not make much sense if we couldn't use it to make decisions about the further course of our program. For this purpose, we use the **conditional statement** `if`: 128 | 129 | ```python 130 | if temperature > 30.0: 131 | print('It is so so hot!') 132 | ``` 133 | 134 | The structure of this instruction is very simple: after the word `if`, we enter 135 | a condition, then a colon and in the following lines, indented, instructions 136 | that will be executed if the condition is true (we say: if the condition is 137 | fulfilled). 138 | 139 | :snake: Write a function that takes arguments `element` and `list` and if the given element is on the list, returns its position (use the `index` method), otherwise returns `-1`. 140 | 141 | :snake: Write a function `quotient` that takes arguments `dividend` and `divisor`. If the divisor is not equal to zero, the function should return the result of division. Otherwise, it should print an error message. 142 | 143 | ## `if ... else` and `elif` 144 | 145 | We can add a second part to the `if` statement that will be executed only if the condition is not fulfilled. 146 | 147 | ```python 148 | if hour <= departure_time: 149 | print('Departure time:', departure_time) 150 | else: 151 | print('We apologize for the delay') 152 | ``` 153 | 154 | Pay attention to the indentation in the code: `if` and `else` are on the same level. 155 | 156 | If we want, we can check several alternative conditions within one `if` statement, if the previous ones turn out to be false. 157 | 158 | ```python 159 | if 5 <= godzina < 12: 160 | print('morning') 161 | elif godzina == 12: 162 | print('noon') 163 | elif 12 < godzina < 17: 164 | print('afternoon') 165 | elif 17 < godzina < 20: 166 | print('evening') 167 | else: 168 | print('night') 169 | ``` 170 | 171 | :snake: Write a function that compares two numbers. As arguments, it should take numbers `a` and `b`. If `a` is greater than `b`, it should return 1, if the numbers are equal `0`, and if `a` is less than `b`, `-1`. Additionally, depending on the comparison result, the function should print one of the following messages: `a < b`, `a == b` or `a > b`. 172 | 173 | 174 | ## Combining conditions 175 | 176 | Sometimes we will want to perform certain operations only if several conditions are met at the same time. In this case, we can use the `and` operator. 177 | 178 | ```python 179 | if substance == 'water' and temperature > 100: 180 | state = 'water vapor' 181 | ``` 182 | 183 | If we wanted the operation to be performed if at least one of several conditions is met, we should use the `or` operator. 184 | 185 | ```python 186 | if product == 'juice' or product == 'tea': 187 | cena = 4.50 188 | ``` 189 | 190 | Operators `or` and `and` can be combined in one expression. 191 | 192 | 193 | ## Object truthfulness, the `bool` function. 194 | 195 | The condition does not have to be a comparison. Each type of object defines truth in some way. For example, an empty list is false, while a list with at least one element is true. 196 | 197 | To determine the value of a given object in terms of logic, we can use the built-in function `bool`. It takes one argument - any object - and returns its logical value: `True` or `False`. 198 | 199 | ```python 200 | >>> bool([]) 201 | False 202 | >>> bool([1, 2, 3]) 203 | True 204 | ``` 205 | 206 | :snake: For each of the following types, find a value for which the `bool` function will return `True` and one for which it will return `False`: string, tuple, integer, float. 207 | 208 | Since every object can be considered in terms of "truthfulness", we can use any object in an `if` statement. 209 | 210 | ```python 211 | if name and surname and len(password) > 5: 212 | print('Correct data provided') 213 | ``` 214 | 215 | :snake: Write a function that takes a list as an argument and returns `True` if all elements in this list are true, or `False` if at least one element is not true. 216 | 217 | ## :pushpin: Summary 218 | 219 | In this chapter: 220 | 221 | * we have learned how to check the truthfulness of expressions, 222 | * we have learned the `if` statement, which can change the course of the program when a specified expression is true. 223 | 224 | --- 225 | 226 | :checkered_flag: Next chapter: [Dictionaries](./13_dictionaries.md) :checkered_flag: 227 | -------------------------------------------------------------------------------- /english/13_dictionaries.md: -------------------------------------------------------------------------------- 1 | # Chapter 13. Dictionaries 2 | 3 | In this chapter: 4 | 5 | You will learn what a **dictionary**, **key**, and **value** are, 6 | you will learn how to define dictionaries and perform operations on them, 7 | you will discover the most common uses of dictionaries. 8 | 9 | 10 | ## What is a dictionary? 11 | 12 | Many situations you will encounter while writing programs can be described as a set of keys and their corresponding values. An example from everyday life is an encyclopedia, where the keys are different entries and the values are definitions explaining those entries. You can go further and say that the internet is a collection of addresses (e.g. `pl.pycon.org`) and the web pages that are hidden behind them. 13 | 14 | This perspective on the reality surrounding us is very convenient, as it allows us to describe complex phenomena in a systematic, easy-to-understand manner. That is why many programming languages offer tools for creating such data structures. In the case of Python, these are **dictionaries**. 15 | 16 | A dictionary, abbreviated as "dict", is a collection of **keys** and their corresponding **values**. The name "dictionary" is not accidental, as it refers to the formula in which we assign definitions to a set of words. 17 | 18 | 19 | ## Definition of dictionary 20 | 21 | We define a dictionary by listing key-value pairs separated by commas, enclosed in curly braces. Each pair consists of two values separated by a colon. 22 | 23 | ```python 24 | age = {'Marcin': 23, 'Agata': 17, 'Marta': 46} 25 | ``` 26 | 27 | To create an empty dictionary, simply use empty curly brackets: 28 | 29 | ```python 30 | d = {} 31 | ``` 32 | 33 | The values in a dictionary do not have to be of the same type, one can be a number, another a string, etc. 34 | 35 | ```python 36 | d = {'number': 123, 'another number': 12.34, 'list': ['Ala has a cat']} 37 | ``` 38 | 39 | Keys can also be numbers. 40 | 41 | ```python 42 | d = {15: 'Ala ma kota', 'Kot ma alę': 3.14} 43 | ``` 44 | 45 | The dictionary can also be an element of the list. 46 | 47 | ```python 48 | l = [{'a': 1, 'b': 2}, 3, 4] 49 | ``` 50 | 51 | When we print the dictionary on the screen, we will see its entire contents. 52 | 53 | ```python 54 | >>> d = {'a': ['x', 9, 'z'], 'b': 2, 'c': 'Ala ma kota'} 55 | >>> print(d) 56 | {'a': ['x', 9, 'z'], 'b': 2, 'c': 'Ala ma kota'} 57 | ``` 58 | 59 | 60 | ## Operations on dictionaries 61 | 62 | Once we define a dictionary, we can perform a variety of operations on it. 63 | 64 | 65 | ### Downloading the value of an element 66 | 67 | To obtain a value for a given key, you must enter the name of the dictionary, followed by the key name in square brackets. 68 | 69 | ```python 70 | >>> d = {'a': 1, 'b': 2} 71 | >>> print(d['a']) 72 | 1 73 | >>> print(d['a'] + d['b']) 74 | 3 75 | ``` 76 | 77 | :snake: See what happens if you retrieve a value for a key that does not exist in the dictionary. 78 | 79 | :snake: Write a function that takes two arguments, a list of dictionaries and a key, and returns a list of values under that key from each dictionary in the list. 80 | 81 | 82 | ### Defining an element 83 | 84 | At any time, we can define the value of a key in a dictionary. To do this, we need to refer to the specific key and assign a value to it. 85 | 86 | ```python 87 | >>> d = {'a': 1} 88 | >>> d['b'] = 2 89 | >>> d[5] = ['list of', 'elements'] 90 | >>> print(d) 91 | {'a': 1, 'b': 2, 5: ['list of', 'elements']} 92 | >>> print(d[5]) 93 | ['list of', 'elements'] 94 | ``` 95 | 96 | If the given key already exists, its value will be overwritten. 97 | 98 | ```python 99 | >>> d = {'a': 1} 100 | >>> print(d['a']) 101 | 1 102 | >>> d['a'] = 2 103 | >>> print(d['a']) 104 | 2 105 | ``` 106 | 107 | ### Removing an element 108 | 109 | We can delete any key from the dictionary using the `del` instruction: 110 | 111 | ```python 112 | >>> d = {'a': 1, 'b': 2} 113 | >>> del d['a'] 114 | >>> print(d) 115 | {'b': 2} 116 | ``` 117 | 118 | :snake: See what happens if you try to delete a key that does not exist in the dictionary. 119 | 120 | ### Iterating through keys and values 121 | 122 | In one of the previous chapters, we talked about iteration in the context of a list, meaning "going through" its elements. We used a `for` loop for this purpose. If we perform the same operation on a dictionary, we will go through its keys. 123 | 124 | ```python 125 | for key in dictionary: 126 | print(key) 127 | ``` 128 | 129 | :snake: Write a function that takes a dictionary as an argument and iterates through its keys, printing each one. 130 | 131 | In a similar way, we can iterate through only the values of a dictionary. This is done using the `values` method. 132 | 133 | ```python 134 | start_list = {1: 'Winnie the Pooh', 2: 'Piglet', 3: 'Tigger'} 135 | for competitor in start_list.values(): 136 | print(competitor) 137 | ``` 138 | 139 | :snake: Write a function that takes a dictionary as an argument and returns the sum of all values in the dictionary. We assume that the values are always numbers. 140 | 141 | The dictionary also has a `items` method, which allows us to iterate simultaneously over the keys and values of the dictionary. 142 | 143 | ```python 144 | start_list = {1: 'Winnie the Pooh', 2: 'Piglet', 3: 'Tigger'} 145 | for number_start, competitor in start_list.items(): 146 | print(number_start, ':', zawocompetitordnik) 147 | ``` 148 | 149 | Note that this time we defined two variables in the `for` loop: 150 | `starting_number` and `player`. This is not specific to dictionaries, 151 | but rather another feature of this loop. If the loop iterates through a list, 152 | where all elements are sequences (lists or tuples), 153 | we can immediately **unpack** all elements of these sequences into 154 | variables: 155 | 156 | ```python 157 | lists = [['a', 'Apple', 'Argentina'], ['b', 'Banana', 'Brasil']] 158 | for letter, fruit, country in lista: 159 | print(fruit) 160 | ``` 161 | 162 | Returning to dictionaries, in our case the first element of each sequence is the key, and the second is the value for that key. 163 | 164 | :snake: Write a function that takes two arguments, a dictionary and a value, and returns the name of the key whose value is equal to the argument value. 165 | 166 | 167 | ## Nesting dictionaries 168 | 169 | The value in the dictionary can be any object, including another dictionary. This allows us to easily create complex data structures. 170 | 171 | ```python 172 | >>> auto = {} 173 | >>> auto['color'] = 'red' 174 | >>> auto['engine'] = {'capacity': 1600, 'power': 130} 175 | >>> print(auto) 176 | {'color': 'red', 'engine': {'capacity': 1600, 'power': 130}} 177 | ``` 178 | 179 | 180 | ## The "length" of a dictionary 181 | 182 | When we first mentioned the `len` function, we said that it is used to check the length of objects. Each type of object (string, list, etc.) may interpret the concept of length differently. For strings, it refers to the number of characters, for lists it refers to the number of elements, etc. Dictionaries also have their own "length": it is equal to the number of keys. 183 | 184 | ```python 185 | >>> print(auto) 186 | {'color': 'red', 'engine': {'capacity': 1600, 'power': 130}} 187 | >>> len(auto) 188 | 2 189 | ``` 190 | 191 | 192 | ## What can we use dictionaries for? 193 | 194 | A dictionary is a very versatile data structure, which makes it useful for many applications. 195 | 196 | * representation of objects and their attributes (as in the example above), 197 | * mapping of one value to another (as in a real dictionary, where we map words from one language to another), 198 | * storing multiple related values in one place (e.g. keys are movie titles and values are their directors). 199 | 200 | :snake: Choose one of the above dictionary applications. Write a function `set` that takes three arguments, a dictionary, a key, and a value, and sets the given value in the dictionary under the given key. Write a function `get` that takes two arguments, a dictionary and a key, and returns the value of the dictionary under the given key. Using these functions, fill the dictionary with data appropriate for the chosen application and retrieve this data. 201 | 202 | ## :pushpin: Summary 203 | 204 | In this chapter: 205 | 206 | * we learned how to create dictionaries and perform operations on them, including iterating through them, 207 | * we also found out that the `len` function returns the number of keys in a dictionary, 208 | * we got to know the most commonly used applications of dictionaries. 209 | 210 | 211 | --- 212 | 213 | :checkered_flag: Next chapter: [`None`](./14_none.md) :checkered_flag: 214 | -------------------------------------------------------------------------------- /english/14_none.md: -------------------------------------------------------------------------------- 1 | # Chapter 14. `None` 2 | 3 | In this chapter: 4 | 5 | * you will learn what **`None`** is. 6 | 7 | 8 | ## `None` 9 | 10 | In Python, there is one particular value that does not represent any known type so far: **`None`**. It is not a number, string, or anything else you will learn while studying this language. `None` is a unique value that represents a separate type. It was created for the purpose of allowing the programmer to define "nothing". Why? It turns out that there are situations where you want to explicitly indicate that a particular operation did not return any significant information. In such situations, you can use the value `None`. Note that the mere use of this value is so exceptional that it suggests that some special circumstances have arisen. 11 | 12 | An example of using `None` can be dividing by 0. As we know, this mathematical operation is not allowed. Now, let's imagine that we are writing a function that takes two numbers as arguments and returns the result of dividing one by the other. 13 | 14 | ```python 15 | def divide(dividend, divisor): 16 | return dividend / divisor 17 | ``` 18 | 19 | What will happen if the `divisor` argument is equal to `0`? We will receive an error. 20 | 21 | ```python 22 | >>> divide(3, 0) 23 | Traceback (most recent call last): 24 | File "", line 1, in 25 | File "", line 2, in podziel 26 | ZeroDivisionError: division by zero 27 | ``` 28 | 29 | To prevent this, we can check the value of the argument before performing division and return `None` if necessary, signaling that we cannot calculate the result. 30 | 31 | Translate: 32 | 33 | ```python 34 | def divide(dividend, divisor): 35 | if divisor == 0: 36 | return None 37 | return dividend / divisor 38 | ``` 39 | 40 | Now we can easily recognize when the function encounters a non-standard call. 41 | 42 | ```python 43 | >>> result = divide(4, 2) 44 | >>> print(result) 45 | 2.0 46 | >>> result = divide(5, 0) 47 | >>> print(result) 48 | None 49 | ``` 50 | 51 | ## Default function value 52 | 53 | Let's write a simple function that takes an argument and prints it on the screen: 54 | 55 | Translate this .md fragment to English, keeping it in line with the previous paragraph. 56 | 57 | ```python 58 | def print_something(something): 59 | print(something) 60 | ``` 61 | 62 | Calling the function will result in the expected consequences. 63 | 64 | ```python 65 | >>> print_something(123) 66 | 123 67 | >>> print_something('ala ma kota') 68 | ala ma kota 69 | ``` 70 | 71 | We see that the function body has been executed, but what value was returned? In other words, what happens if we do not use the `return` statement? The answer is: the function will return `None`. 72 | 73 | ```python 74 | >>> result = print_something('abc') 75 | abc 76 | >>> print(result) 77 | None 78 | ``` 79 | 80 | The same thing happens if we use the `return` statement without providing any value: 81 | 82 | Translate this .md fragment to English, keeping in line with the previous paragraph. 83 | 84 | ```python 85 | def print_something(something): 86 | print(something) 87 | return 88 | ``` 89 | 90 | The effect will be the same as when we do not use `return`. 91 | 92 | ```python 93 | >>> result = print_something(3.14) 94 | 3.14 95 | >>> print(result) 96 | None 97 | ``` 98 | 99 | There is no magic behind this behavior: the creators of Python simply adopted the convention that a function returns "nothing" by default, and this value will be represented by `None`. 100 | 101 | 102 | ## `is` operator 103 | 104 | Now that we know that functions can return `None`, how can we use this? We can, for example, check the returned value in an `if` statement. 105 | 106 | ```python 107 | def name_surname(name, surname): 108 | if name != '' and surname != '': 109 | return name + ' ' + surname 110 | 111 | def username(name, surname, email): 112 | full_name = name_surname(imie, nazwisko) 113 | if full_name == None: 114 | return email 115 | else: 116 | return full_name 117 | ``` 118 | 119 | In the above example, the `username` function returns the full name of the user based on their first name, last name, and email address. If the first and last name are provided, the full name is returned, otherwise only the email address is returned. Checking if the full name is provided is saved in the `if full_name == None` statement. 120 | 121 | The `if variable == None` instruction is correct, however in general it may not always work. This is because when creating more advanced data structures in Python (which will not be discussed during these workshops), we can change the comparison behavior, resulting in a different return value for the `==` operator. If we do this carelessly, it may turn out that an `if` operation works differently than expected. We can get out of this situation by using the **`is` operator** instead. 122 | 123 | ```python 124 | if full_name is None: 125 | return email 126 | ``` 127 | 128 | In this way, our code will be insensitive to modifications of the behavior of the `==` operator. 129 | 130 | When should you use `is`? Use this operator whenever you compare a value to `None`. For now, it won't make a difference, but this way you will acquire a good habit that will prove useful in the future. 131 | 132 | :snake: Write a function that takes a list as an argument and returns a list containing all elements from the argument, except for values equal to `None`. 133 | 134 | ## :pushpin: Summary 135 | 136 | In this chapter: 137 | 138 | * we learned about `None`, 139 | * we found out that when comparing values to `None`, we should use 140 | the `is` operator. 141 | 142 | 143 | --- 144 | 145 | :checkered_flag: Next chapter: [`while` loop](./15_while_loop.md) :checkered_flag: 146 | -------------------------------------------------------------------------------- /english/15_while_loop.md: -------------------------------------------------------------------------------- 1 | # Chapter 15. `while` loop 2 | 3 | In this chapter: 4 | 5 | * you will learn how to use the `while` loop. 6 | 7 | 8 | ## The `while` loop 9 | 10 | You already know what a loop is and you know one of them: `for`. Now you will learn the second, and at the same time the last one that exists in Python: `while`. Its structure is even simpler than the previous one: 11 | 12 | ```python 13 | counter = 1 14 | while counter < 10: 15 | print(counter) 16 | counter = counter + 1 17 | ``` 18 | 19 | We start the definition of a loop with the word `while`, then we define the condition (just like in the `if` statement), and after a colon, in subsequent lines and indented, we write the instructions that will be executed as long as the condition is true. 20 | 21 | Note that if we define a condition that will always be true, then the loop will be executed infinitely. 22 | 23 | ```python 24 | while 1 == 1: 25 | print('.') 26 | ``` 27 | 28 | :snake: Write a function that takes a list as an argument and prints all its elements using a `while` loop. 29 | 30 | ## :pushpin: Summary 31 | 32 | In this chapter: 33 | 34 | * we have learned the `while` loop. 35 | 36 | 37 | --- 38 | 39 | :checkered_flag: Next chapter: [Standard library](./16_standard_library.md) :checkered_flag: 40 | -------------------------------------------------------------------------------- /english/16_standard_library.md: -------------------------------------------------------------------------------- 1 | # Chapter 16. Standard library 2 | 3 | In this chapter: 4 | 5 | * you will learn what the **standard library** is, 6 | * you will get to know the most important **modules** of the standard library. 7 | 8 | 9 | ## Library 10 | 11 | In programming, we use the concept of a **library**, which refers to a collection of programs and tools for building them that we can use when writing our own programs. An example of a library could be a set of mathematical functions (e.g. trigonometric functions) that we can refer to in our code instead of defining them ourselves. 12 | 13 | 14 | ## Modules 15 | 16 | In Python, programming libraries are accessible through **modules**. A module is simply code placed on a disk, in a location where Python can find it. This can be code written in Python, but there are ways to write modules in other programming languages. Python will find such code if it is placed in one of the predetermined directories. 17 | 18 | Anyone can write their own module for Python. On the internet, we can find thousands of modules that are shared by different individuals and companies. We can download and use them to write programs. We can also create our own modules and share them with other users. 19 | 20 | In order to use a module in our program code, we must **import** its name. We do this with the `import` statement. Once the module is imported, we can use the functions and variables defined within it. We do this by typing the module name, followed by a dot, and then the object name. 21 | 22 | In the following example, we import a module called `math` and call the `sqrt` function, which returns the square root of a given number. 23 | 24 | ```python 25 | import math 26 | print(math.sqrt(9)) 27 | ``` 28 | 29 | ## The Python Standard Library 30 | 31 | In addition to modules that users can write themselves, there is a set of modules that is always available in Python. This set is called the **standard library**. It contains dozens of modules, including tools for network communication, handling various file formats, mathematical calculations, etc. 32 | 33 | The standard library is extensively documented on the [official Python website](https://docs.python.org/3/library/index.html). 34 | 35 | ## The most important modules 36 | 37 | Discussing the entire standard library is a task that takes at least a few weeks, so during these workshops we will only mention a few of the most popular modules. 38 | 39 | ### [`math`](https://docs.python.org/3/library/math.html) 40 | 41 | The `math` module contains dozens of mathematical functions that can be useful for simple calculations. Below, we have described several of them. 42 | 43 | The `ceil` and `floor` functions return values rounded down and up, respectively. 44 | 45 | ```python 46 | >>> math.ceil(3.5) 47 | 4 48 | >>> math.floor(3.5) 49 | 3 50 | ``` 51 | 52 | The `sqrt` function returns the square root of a given number. 53 | 54 | ```python 55 | >>> math.sqrt(25) 56 | 5.0 57 | ``` 58 | 59 | `pi` and `e` represent values of mathematical constants: 60 | 61 | ```python 62 | >>> math.pi 63 | 3.141592653589793 64 | >>> math.e 65 | 2.718281828459045 66 | ``` 67 | 68 | :snake: Write a function that returns the value of the area of a circle with a given radius (according to the formula `PI * r^2`, where `r` is the radius). 69 | 70 | 71 | ### [`datetime`](https://docs.python.org/3/library/datetime.html) 72 | 73 | The `datetime` module is a basic tool for working with dates and time. It contains objects `date`, `datetime`, and `timedelta`, which represent a date, date and time, and a time difference, respectively. 74 | 75 | To get today's date, you need to call the `today` method on the `date` object. 76 | 77 | ```python 78 | >>> datetime.date.today() 79 | datetime.date(2024, 8, 29) 80 | ``` 81 | 82 | The object obtained in this way contains three **attributes**: `year`, `month`, and `day`, which correspond to the year, month, and day respectively. 83 | 84 | ```python 85 | >>> today = datetime.date.today() 86 | >>> today.year 87 | 2024 88 | >>> today.month 89 | 8 90 | >>> today.day 91 | 29 92 | ``` 93 | 94 | The `now` method on the `datetime` object will return the date and time that we have at the moment. In addition to the `year`, `month`, and `day` attributes, it also has `hour`, `minute`, `second`, and `microsecond`, which represent the hour, minute, second, and microsecond. 95 | 96 | ```python 97 | >>> now = datetime.datetime.now() 98 | >>> now 99 | datetime.datetime(2017, 8, 13, 18, 53, 13, 366193) 100 | >>> now.hour 101 | 18 102 | >>> now.minute 103 | 53 104 | >>> now.second 105 | 13 106 | >>> now.microsecond 107 | 366193 108 | ``` 109 | 110 | Both types of objects can be displayed on the screen in a readable format: 111 | 112 | ```python 113 | >>> print(today) 114 | 2017-08-13 115 | >>> print(now) 116 | 2017-08-13 18:53:13.366193 117 | ``` 118 | 119 | To create a representation of any moment in time, simply call `date` or `datetime` and provide `year`, `month`, `day`, `hour`, `minute`, `second`, `microsecond` in order. 120 | 121 | ```python 122 | >>> print(datetime.date(2010, 5, 10)) 123 | 2010-05-10 124 | >>> print(datetime.datetime(2020, 11, 23, 15, 7, 30)) 125 | 2020-11-23 15:07:30 126 | ``` 127 | 128 | :snake: See what happens if you try to create an object `date` with a month outside the range of 1 to 12 or a date that doesn't exist, like April 31st. 129 | 130 | :snake: See what will happen if you try to create a `datetime` object with an hour, minute, or second value outside of the allowable range (e.g. hour 26). 131 | 132 | If we want to see the difference in time between two objects of type `datetime`, we can simply subtract them from each other. 133 | 134 | ```python 135 | >>> a = datetime.datetime(2017, 8, 16, 17, 00) 136 | >>> b = datetime.datetime(2017, 8, 16, 19, 00) 137 | >>> diff = b - a 138 | >>> diff 139 | datetime.timedelta(0, 7200) 140 | >>> diff.seconds 141 | 7200 142 | 143 | In the above example, we received a `timedelta` object that has a `seconds` attribute with a value equal to the number of seconds between `a` and `b`. 144 | 145 | If the difference is greater than one day, it will be divided into two values: `seconds` and `days`, which are seconds and days. 146 | 147 | ```python 148 | >>> c = datetime.datetime(2017, 8, 16, 17, 00) 149 | >>> d = datetime.datetime(2017, 8, 18, 15, 00) 150 | >>> diff = d - c 151 | >>> diff.seconds 152 | 79200 153 | >>> diff.days 154 | 1 155 | ``` 156 | 157 | If we add one day and 79200 seconds to the date `c`, we will get `d`. 158 | 159 | :snake: Write a function that takes two dates as arguments. If the second date is smaller than the first one, the function should return `None`. Otherwise, the function should return the number of seconds between the two dates. Note that the difference can be greater than one day. In this case, the number of days should be converted to seconds. 160 | 161 | 162 | ### [`random`](https://docs.python.org/3/library/random.html) 163 | 164 | The `random` module is used to perform operations whose result is random: 165 | generating random numbers, randomly selecting objects from a given range, 166 | etc. 167 | 168 | The `randint` function takes two integers as arguments and returns a randomly selected integer whose value is between the arguments. 169 | 170 | ```python 171 | >>> random.randint(1, 100) 172 | 9 173 | >>> random.randint(1, 100) 174 | 44 175 | ``` 176 | 177 | The `choice` function takes any sequence (list, tuple, string) as an argument and returns a randomly chosen element. 178 | 179 | ```python 180 | >>> random.choice('ala ma kota') 181 | 'm' 182 | >>> random.choice([9, 7, 5, 3]) 183 | 7 184 | >>> random.choice(('pycon', 'pl', '2024')) 185 | 'pl' 186 | ``` 187 | 188 | :snake: Write a function that takes any sequence as an argument and returns a *tuple* with three randomly selected elements from it. 189 | 190 | ### [`json`](https://docs.python.org/3/library/json.html) 191 | 192 | The `json` module allows you to save Python objects (dictionaries and lists) as strings in the JSON (*JavaScript Object Notation*) format, which is commonly used in web services for exchanging data between the browser and the server. 193 | 194 | To convert an object to a string, you need to call the `dumps` function. 195 | 196 | ```python 197 | >>> json.dumps({'place': 'Ossa', 'date': '2017-08-16'}) 198 | '{"place": "Ossa", "date": "2017-08-16"}' 199 | >>> json.dumps([2017, 8, 16]) 200 | '[2017, 8, 16]' 201 | ``` 202 | 203 | Do zamiany stringa na słownik lub listę służy funkcja `loads`: 204 | 205 | ```python 206 | >>> json.loads('{"place": "Ossa", "date": "2017-08-16"}') 207 | {'place': 'Ossa', 'date': '2017-08-16'} 208 | >>> json.loads('[2017, 8, 16]') 209 | [2017, 8, 16] 210 | ``` 211 | 212 | ## What's next? 213 | 214 | Above, we listed only a few of the most popular modules, so we encourage you to familiarize yourself with the rest of the standard library. It's worth starting with the official documentation, but you can also find plenty of articles online dedicated to using the standard library in everyday programming. Of course, you don't need to know it all to program freely in Python. Many of these modules have very specific uses and most programmers never use them. However, it's worth remembering that if you encounter a new problem, it's good to first search the standard library for a module that may be helpful. 215 | 216 | ## :pushpin: Summary 217 | 218 | In this chapter: 219 | 220 | * we learned what the **standard library** is and how to use it, 221 | * we got to know the `math`, `datetime`, `random`, and `json` modules. 222 | 223 | 224 | --- 225 | 226 | :checkered_flag: Next chapter: [Summarizon](./17_summarizon.md) :checkered_flag: 227 | -------------------------------------------------------------------------------- /english/17_summarizon.md: -------------------------------------------------------------------------------- 1 | # Summary 2 | 3 | We are reaching the end of the course, but it's not the end of the workshops yet! There are still additional chapters waiting for you - you will find them in the "Add-ons" section below the table of contents. In addition, the mentors have a handful of tasks for you. You can also take this opportunity to ask the mentors as many questions as time allows - that's one of the reasons why we organized these workshops! 4 | 5 | 6 | ## What we didn't talk about 7 | 8 | Unfortunately, the time for the workshops is limited, so the range of topics we covered is not exhaustive. You already know the basics of Python. You can now write your own programs and reading others' will no longer be so difficult. However, at this stage, you will often come across code that you do not understand. Or maybe you already know about topics that seem interesting, but you do not know how to start. That is why we have prepared a list of topics for you, which you can treat as a continuation of these workshops. This list is not exhaustive, but it will certainly help you to get to know Python even better. In each point, we have included a link to a page that explains the given topic. 9 | 10 | * [More about exceptions and how to handle them](https://docs.python.org/3.12/tutorial/errors.html) 11 | * [Classes, or object-oriented programming](https://docs.python.org/3.12/tutorial/classes.html) 12 | * [Decorators](https://docs.python.org/3/glossary.html#term-decorator) 13 | * [Generators](https://docs.python.org/3/glossary.html#index-17) 14 | * [List comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) 15 | * [Sets](https://docs.python.org/3/tutorial/datastructures.html#sets) 16 | 17 | ## Finally... `dir` 18 | 19 | To conclude, we will show you one more, very useful built-in function. It is called `dir`, it takes any object as an argument and returns a list of all methods and attributes of that object. 20 | 21 | ```python 22 | >>> d = {'a': 1} 23 | >>> dir(d) 24 | ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values'] 25 | ``` 26 | 27 | In the example above, you will definitely recognize a few familiar names, such as `items` or `values`, but as you can see, dictionaries offer much more. Pay attention to names starting and ending with a double underscore. These are the names of attributes and methods that are not intended for object users. They are usually things used only within a specific object. Of course, they can still be used - they just may not be useful to us, so it is worth exploring the remaining names. 28 | 29 | What to do with such a list now? If a name seems obvious, we can simply try to use it - in the worst case scenario, we will receive an error message explaining what we did wrong. We can also - and we recommend it - use the `help` function, which will display the documentation of a given object. 30 | 31 | ```python 32 | help(d.update) 33 | ``` 34 | 35 | ## :checkered_flag: End 36 | 37 | Thank you for participating in the workshops! Once again, we encourage you to talk to the mentors - they will gladly answer all your questions and explain any topics that may be unclear. 38 | 39 | If you have any comments about this course, please share them by writing to the authors or passing them on to mentors. Your opinion is very important to us! 40 | 41 | ![Programming is fun again](https://imgs.xkcd.com/comics/python.png) 42 | -------------------------------------------------------------------------------- /english/README.md: -------------------------------------------------------------------------------- 1 | # PyLadies Workshops / PyCon PL 2 | 3 | Welcome to PyLadies workshops! During this course, you will learn how to program in **Python** from scratch. To get started, you don't need to install anything, no prior knowledge of programming or computer science is required. All you need is an internet browser and a desire to acquire knowledge! 4 | 5 | ## What do these workshops teach? 6 | 7 | This course will teach you how to create your own programs in Python. You will learn the basics of this language and find out how to expand your knowledge in the future, in order to independently create more interesting things. Thanks to these workshops, you will understand Python at a level that will allow you to write useful tools and delve into more advanced aspects of this language. 8 | 9 | In summary: Your adventure with programming begins right here! 10 | 11 | ## Legend 12 | 13 | Before we begin, familiarize yourself with the markings that have been used on the following pages of the course. 14 | 15 | :snake: stands for a place where we give you a task to complete. If the instructions are unclear or the task is causing you trouble - ask for help from a mentor. 16 | 17 | :pushpin: is a summary of the chapter. Before you continue, make sure you understand all the topics listed there. If you have any doubts - ask your mentor. Do not rely on others - that's why we do a summary, to make sure that everyone understood the chapter. 18 | 19 | :checkered_flag: is the end of the chapter. Click on the link to proceed to the next one. 20 | 21 | We highlighted important words and phrases with **bold text**. It is worth remembering them to better understand the following chapters. 22 | 23 | `In this way`, we have marked the sample code of the programs. 24 | 25 | 26 | ## Mentors 27 | 28 | Our team of mentors is here for you! If you have any questions, anything is unclear, or you are unsure how to complete a task - ask one of us for help. We are happy to answer, explain, and help you understand any topic. Don't hesitate: we also once asked questions and it is thanks to that that we can now answer them ourselves. 29 | 30 | ## Table of contents 31 | 32 | 1. [Interactive mode](./01_interactive_mode.md) 33 | 2. [Text](./02_text.md) 34 | 3. [`help` function](./03_help.md) 35 | 4. [Numbers](./04_numbers.md) 36 | 5. [Errors](./05_errors.md) 37 | 6. [Variables](./06_variables.md) 38 | 7. [Functions](./07_functions.md) 39 | 8. [`print` function](./08_print_function.md) 40 | 9. [Lists](./09_lists.md) 41 | 10. [`for` loop](./10_for_loop.md) 42 | 11. [Tuples](./11_tuples.md) 43 | 12. [True and False](./12_true_and_false.md) 44 | 13. [Dictionaries](./13_dictionaries.md) 45 | 14. [`None`](./14_none.md) 46 | 15. [`while` loop](./15_while_loop.md) 47 | 16. [Standard library](./16_standard_library.md) 48 | 17. [Summary](./17_summary.md) 49 | 50 | Additions 51 | 52 | 1. [Python installation](./d01_python_installation.md) 53 | 2. [Optional Installation of Visual Studio Code (document is in English)](./d01_instalacja_pythona.md) 54 | 55 | The important sections are: 56 | - [Prerequisites](https://code.visualstudio.com/docs/python/python-tutorial#_prerequisites) 57 | - [Start VS Code in a workspace folder](https://code.visualstudio.com/docs/python/python-tutorial#_start-vs-code-in-a-workspace-folder) 58 | - [Create a virtual environment](https://code.visualstudio.com/docs/python/python-tutorial#_create-a-virtual-environment) 59 | - [Create a Python source code file](https://code.visualstudio.com/docs/python/python-tutorial#_create-a-python-source-code-file) 60 | - [Run Python code](https://code.visualstudio.com/docs/python/python-tutorial#_run-python-code) 61 | 62 | 3. [Modules](./d02_modules.md) 63 | 4. [`input` function](./d03_input.md) 64 | 5. [File operations](./d04_files.md) 65 | 6. [Exercises](./d05_exercises.md) 66 | -------------------------------------------------------------------------------- /english/d01_python_installation.md: -------------------------------------------------------------------------------- 1 | # Appendix 1. Python Installation 2 | 3 | Working on the repl.it website is convenient for learning, however, in order to fully utilize Python, it is worth installing it on your own computer. Below you will find instructions for installing Python on a Windows system. If you are using a different operating system, ask a mentor for help. 4 | 5 | ## Step 1: download the installation program. 6 | 7 | Go to the website [https://www.python.org/downloads/](https://www.python.org/downloads/) and find "Download Python 3.12.5" button. Click on it. 8 | This way you will download the Python installation program. 9 | 10 | ![Step 1](../obrazy/d01/krok_1.png) 11 | 12 | ## Step 2: Run the Installer 13 | 14 | Locate the installer on your disk and run it. You will see a window titled "Install Python 3.12.5." Make sure the "Add python.exe to PATH" option is checked, and then click the "Install Now" button. 15 | 16 | > If you encounter issues installing Python with administrator privileges, uncheck the "Use admin privileges when installing py.exe" option and try again. 17 | > 18 | ![Step 2](../obrazy/d01/krok_2.png) 19 | 20 | ## Step 3: Wait until the installation is complete 21 | 22 | Python installation can take up to several minutes. 23 | 24 | ![Step 3](../obrazy/d01/krok_3.png) 25 | 26 | ## Step 4: make sure that the installation process was successful. 27 | 28 | If the installation is successful, the message "Setup was successful" will appear in the installation program window. If this does not happen, ask for help from a mentor. 29 | 30 | ![Step 4](../obrazy/d01/krok_4.png) 31 | 32 | ## Step 5: Run the IDLE program. 33 | 34 | Along with Python, the IDLE program was installed, where you can edit code files. There is also an interactive mode available. IDLE is a complete programming environment where you can create even advanced programs. 35 | 36 | Find IDLE among the programs installed on your computer and run it. 37 | 38 | ![Step 5](../obrazy/d01/krok_5.jpg) 39 | 40 | ## Step 6: interactive mode 41 | 42 | After the first launch, the interactive mode will open by default. Try entering a few commands that you know. 43 | 44 | ![Step 6](../obrazy/d01/krok_6.jpg) 45 | 46 | ## Step 7: Write and run your first program. 47 | 48 | Click on the "File" option in the top bar of the window, then select "New File". An editor window will appear. Type in the code of a program, for example `print('PyLadies')`. Save the file by choosing "File" and then "Save". To run the program, click on "Run" and "Run Module" (or press the F5 key). The program will be executed. If it prints any text on the screen, you will see it in the interactive mode window. 49 | 50 | ![Step 7](../obrazy/d01/krok_7.jpg) 51 | 52 | That's all. You now have a programming environment for Python on your computer. You can write code for programs, save it in files, open and run them. You can also work in interactive mode. 53 | -------------------------------------------------------------------------------- /english/d02_modules.md: -------------------------------------------------------------------------------- 1 | # Appendix 2. Modules 2 | 3 | As mentioned in the chapter ["Standard Library"](./16_standard_library.md), anyone can create their own module (library) for Python and share it with others, or simply use it in different projects. Below you will read about how to create modules and how to use them. 4 | 5 | ## Writing a module 6 | 7 | If you have [IDLE program](../d01_instalacja_pythona.md') on your computer, you probably already know that the code of programs written in Python is saved in files with the extension `.py`. This is a convention that allows for easy distinction between Python code and other files that do not contain it. 8 | 9 | Every file with the extension `.py` is also a program that we can run in Python. In other words: if we run Python and open a file with the extension `.py`, the code contained in this file will be executed. 10 | 11 | At the same time, every file with the extension `.py` is also a module. This means that we can import it in another file using the `import` statement and thus gain access to all the objects defined within it: functions, variables, etc. 12 | 13 | In summary: to write a module, all you need to do is place any code in a file with the extension `.py`. Each such file can potentially be used as a module. 14 | 15 | ## Importing Modules 16 | 17 | We can use the ready-made module in any other program or module by importing it there. It is important for both files to be located **in the same directory**, otherwise Python will throw an `ImportError` exception. 18 | 19 | We import the module using the `import` statement, in which we provide its name, which is the same as the name of the file in which we saved it, but without the `.py` extension. 20 | 21 | Let's assume that we have created a file named `functions.py` and saved the following code in it: 22 | 23 | The following is a translation of the previous paragraph and the given Python code into English: 24 | 25 | ```python 26 | def sum(a, b): 27 | return a + b 28 | ``` 29 | 30 | Now in the same directory, we can create a file `calculations.py` and enter the following code in it: 31 | 32 | ```python 33 | import functions 34 | 35 | print(functions.sum(2000, 17)) 36 | ``` 37 | 38 | If we run the `calculations.py` program, the number `2017` will be printed on the screen. 39 | 40 | ## Usage of modules 41 | 42 | Modules are one of the most powerful mechanisms in Python. They allow us to divide programs into logically separated fragments. For example, in one module we can place all the functions responsible for mathematical calculations, in another functions for displaying data on the screen, and in the third combine everything together using the other two modules. 43 | 44 | When writing programs, always keep in mind that dividing them into modules increases the readability of your code. It will also be easier for you to return to a program whose code has been organized in such a way. 45 | -------------------------------------------------------------------------------- /english/d03_input.md: -------------------------------------------------------------------------------- 1 | # Appendix 3. The `input` function. 2 | 3 | When writing a program, we often expect that its user will provide us with some data: their name and surname, numerical parameters, or other values that will affect the program's execution. The simplest method of obtaining such data is by using the built-in `input` function, which, when called, pauses the program's execution, waits for the user to type something and press enter, and then returns the entered text as a string: 4 | 5 | ```python 6 | print('Enter your age:') 7 | age = input() 8 | print('You are {}'.format(age)) 9 | ``` 10 | 11 | In the above example, we display a message on the screen - a request to enter age - then we retrieve this value from the user and display it in the next message. 12 | 13 | Remember that the value obtained in this way will always be a string. If you want to convert it to a number, you can use the built-in function [`int`](https://docs.python.org/3/library/functions.html#int). 14 | -------------------------------------------------------------------------------- /english/d04_files.md: -------------------------------------------------------------------------------- 1 | # Appendix 4. File operations 2 | 3 | Files are often the source of data in programs. If a file contains text, which are characters that can be displayed on the screen, we call it a **text file**. Such a file can be read in a text editor, for example in Notepad. There are also files whose contents we do not interpret as text, such as images. We call them **binary files**. 4 | 5 | Both types of files can be read and written in Python, however, in this article we will focus on text files. Once you learn how to work with them, operations on binary files will no longer be a problem for you. 6 | 7 | ## File path 8 | 9 | The most important attribute of a file is its **path**, which indicates where it is located in the directory structure and under what name. For example, if you log in as a user "Ala" in the Windows system and create a file "cat.txt" in the "My Documents" directory, the path of this file will most likely look like this: `C:\Users\Ala\Documents\cat.txt`. 10 | 11 | In Python, we store paths in strings, for example: 12 | 13 | ```python 14 | >>> file_path = 'C:\Users\Ala\Documents\cat.txt' 15 | >>> print(file_path) 16 | C:\Users\Ala\Documents\cat.txt 17 | ``` 18 | 19 | In the above example, we defined an **absolute path**, which precisely specifies the directory in which the file is located (`C:\Users\Ala\Documents`). If we refer to a file relative to the directory in which our program is located, we can define a **relative path**. For example, we can only provide the file name: `cat.txt`. In this case, Python will assume that we are looking for the file in the same directory as the program. We can also say that the file is located in the "higher" directory: `..\cat.txt`. 20 | 21 | Regardless of the chosen method, in order to operate on a file, we will need its path. 22 | 23 | ## Reading a file 24 | 25 | The built-in function `open` gives us access to the file by taking the path as an argument. 26 | 27 | ```python 28 | >>> file = open(path) 29 | ``` 30 | 31 | Once we define a file, we can read its entire content by calling the `read` method. 32 | 33 | ```python 34 | >>> data = file.read() 35 | >>> print(data) 36 | file contents 37 | ``` 38 | 39 | We can also iterate through a file, line by line. 40 | 41 | ```python 42 | for line in file: 43 | print(line) 44 | ``` 45 | 46 | When we read the file, a second attempt to read will return an empty string. This happens because Python keeps track of the position where we finished reading the file and starts subsequent reads from that position. If this position is at the end of the file, a second attempt to read will return nothing. To read the file from the beginning again, we must call the `seek` method with an argument of `0`, which will reset the reading position to the very beginning. 47 | 48 | ```python 49 | >>> file = open('cat.txt') 50 | >>> file.read() 51 | 'ala has a cat' 52 | >>> file.read() 53 | '' 54 | >>> file.seek(0) 55 | >>> file.read() 56 | 'ala has a cat' 57 | >>> file.read() 58 | '' 59 | ``` 60 | 61 | ## Writing to a file 62 | 63 | When opening a file with the `open` function, we can decide whether we want to perform reading or writing on it. By default, Python assumes reading. If we want to explicitly specify the **mode** of working with the file, we must pass a second argument, which should be a string. If we choose `'r'` (*read*), we will only be able to read the file. If `'w'` (*write*) is chosen, only writing will be possible. There are more available modes, which you can read about in the [documentation for the `open` function](https://docs.python.org/3/library/functions.html#open). 64 | 65 | After opening the file in write mode, we can enter text into the file using the `write` method. 66 | 67 | ```python 68 | >>> file = open('cat.txt', 'w') 69 | >>> file.write('ala ma kota') 70 | ``` 71 | 72 | If there was any text in the file before opening it, it will be **overwritten** after calling the `write` method. However, subsequent writes to the already open file will cause the text to be appended at the end. 73 | 74 | ```python 75 | >>> path = 'cat.txt' 76 | >>> open(path).read() 77 | 'at the beginning there was such a text' 78 | >>> file = open(path, 'w') 79 | >>> file.write('now we will overwrite') 80 | >>> file.write(' that text') 81 | >>> file.close() 82 | >>> open(path).read() 83 | 'now we will overwrite that text' 84 | ``` 85 | 86 | Note that in the above example, after saving the text, we called the `close` method. This way we closed the file, preserving the data on the disk. If we did not do this, calling the `read` method would return the original content of the file. The `close` method should be used if we want to read the same file again after saving. Otherwise, Python will automatically close the file: it will do so when the function in which we opened the file ends, or when the program finishes its execution. 87 | 88 | ## New line character 89 | 90 | When working with text files, we will come across the **new line character**, which is represented in Python as a string with the content `\n` (backslash and the letter "n"). It indicates the place where a line of text ends. The character itself is not special, it is just a character like `a` or `7`. However, it is commonly accepted that the new line character has a special meaning in order to allow text to be divided into separate lines. Therefore, it is treated differently than other characters, for example the `print` function will replace it with a new line. Importantly, this character is not directly related to files - it can be a part of any string. 91 | 92 | ```python 93 | >>> s = 'first line\nsecond line' 94 | >>> print(s) 95 | first line 96 | second line 97 | ``` 98 | -------------------------------------------------------------------------------- /english/d05_tasks.md: -------------------------------------------------------------------------------- 1 | # Appendix 5. Tasks 2 | 3 | This supplement contains a set of tasks that will help you consolidate the knowledge gained during the course. It will also teach you how to choose the appropriate types of data and operations depending on the problem you are facing. 4 | 5 | When solving tasks, focus primarily on writing a functional program. Do not think about its "quality": how quickly it works or how nice the code looks. Start by solving the problem, and only then evaluate whether anything needs to be improved. 6 | 7 | 8 | --- 9 | 10 | 11 | ## 1. The `title` function 12 | 13 | Write a function called `title` that will work like the `title` method on a string, but without using this method. 14 | 15 | Example: 16 | 17 | ```python 18 | >>> title('ala MA kOTA') 19 | 'Ala Ma Kota' 20 | ``` 21 | 22 | 23 | ## 2. Grouping dictionaries 24 | 25 | Write a function `group` that will group dictionaries according to the values for a selected key. 26 | 27 | Example: 28 | 29 | The following paragraph provides an example of how to translate a .md fragment into English while maintaining continuity with the previous paragraph. 30 | 31 | ```python 32 | >>> fruits = [ 33 | ... {'name': 'apple', 'color': 'red'}, 34 | ... {'name': 'banana', 'color': 'yellow'}, 35 | ... {'name': 'lemon', 'color': 'yellow'}, 36 | ... {'name': 'pear', 'color': 'green'}, 37 | ... {'name': 'strawberry', 'color': 'red'} 38 | ... ] 39 | >>> groups = group(fruits, 'color') 40 | >>> for color, fruit_list in groups.items(): 41 | ... print(color, fruit_list) 42 | ... 43 | red [{'name': 'apple', 'color': 'red'}, {'name': 'strawberry', 'color': 'red'}] 44 | yellow [{'name': 'banana', 'color': 'yellow'}, {'name': 'lemon', 'color': 'yellow'}] 45 | green [{'name': 'pear', 'color': 'green'}] 46 | ``` 47 | 48 | The function should take two arguments: a list of dictionaries and a key name. The result of the function should be a dictionary, where the keys are group names and the values are lists of dictionaries belonging to those groups. 49 | 50 | ## 3. The "delta compression" algorithm 51 | 52 | Write a `delta_compression` function that takes a **sorted** list of integers as an argument and returns the same list compressed using the following algorithm: 53 | 54 | 1. The first element of the output list is the same as the first element of the input list. 55 | 2. Each subsequent element of the output list is equal to the difference between the corresponding element of the input list and the element preceding it, that is `OUT[i] = IN[i] - IN[i-1]`. 56 | 57 | Example: 58 | 59 | ```python 60 | >>> we = [5, 7, 11, 21, 28, 39] 61 | >>> delta_compression(we) 62 | [5, 2, 4, 10, 7, 11] 63 | ``` 64 | 65 | ## 4. Group and count 66 | 67 | Write a function `group_and_count` that takes a list of two-element tuples as an argument, where the first element is a date (an instance of `datetime.date`) and the second is an integer, and calculates the sum of these numbers for each month that appears among these dates. The function should return a dictionary where the keys are tuples `(year, month)` and the values are the sums of the numbers. 68 | 69 | Example: 70 | 71 | ```python 72 | >>> x = group_and_count([ 73 | ... (datetime.date(2015, 1, 29), 10), 74 | ... (datetime.date(2015, 1, 30), 12), 75 | ... (datetime.date(2015, 1, 31), 10), 76 | ... (datetime.date(2015, 2, 1), 9), 77 | ... (datetime.date(2015, 2, 2), 9) 78 | ... ]) 79 | >>> print(x) 80 | {(2015, 1): 32, (2015, 2): 18} 81 | ``` 82 | 83 | ## 5. String Slicing 84 | 85 | Write a function `cut` that takes two arguments: text and a number. 86 | The function should return the text cut into fragments (a list), each 87 | with a length equal to the number given in the argument. The last fragment may 88 | be shorter than the required length. 89 | 90 | Example: 91 | 92 | ```python 93 | >>> cut('12345678', 3) 94 | ['123', '456', '78'] 95 | >>> cut('12345678', 5) 96 | ['12345', '678'] 97 | >>> cut('123', 4) 98 | ['123'] 99 | ``` 100 | 101 | ## 6. Counting words 102 | 103 | Write a function that takes any text as an argument and returns a dictionary, where the keys will be all the words from that text, and the values will be the number of occurrences of those words in the text. The function should be case-insensitive (meaning 'Cat' and 'cat' should be treated as one word) and should ignore punctuation marks. 104 | 105 | Example: 106 | 107 | ```python 108 | >>> text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer soliciting ultricies eros, vitae eleifend ipsum sodales ut. Pellentesque libero ipsum, euismod eget volutpat nec, hendrerit vel turpis." 109 | >>> count_words(text) 110 | {'soliciting': 1, 'elit': 1, 'vel': 1, 'eleifend': 1, 'sodales': 1, 'eros': 1, 'sit': 1, 'nec': 1, 'consectetur': 1, 'pellentesque': 1, 'vitae': 1, 'eget': 1, 'hendrerit': 1, 'dolor': 1, 'turpis': 1, 'euismod': 1, 'integer': 1, 'lorem': 1, 'amet': 1, 'ipsum': 3, 'ut': 1, 'ultricies': 1, 'libero': 1, 'adipiscing': 1, 'volutpat': 1} 111 | ``` 112 | -------------------------------------------------------------------------------- /english/d06_replit.md: -------------------------------------------------------------------------------- 1 | # Appendix 6. Creating an Account and Using replit.com 2 | 3 | This appendix provides information on how to use the `replit.com` platform. 4 | 5 | ## 1. Creating an Account 6 | 7 | Go to the account creation page on [replit.com](https://replit.com/languages/python3?authModal=language-page%3Ahero). 8 | 9 | ![Creating an account at replit.com](../obrazy/d06/krok_1.png) 10 | 11 | After creating your account, log in. 12 | 13 | ## 2. Choosing a Plan 14 | 15 | Select the "Starter" plan by clicking the "Continue with Starter" button. 16 | ![Choosing a Plan](../obrazy/d06/krok_2.png) 17 | 18 | ## 3. Testing the Platform 19 | 20 | In the open "main.py" file, enter the following code: 21 | 22 | ```python 23 | print("Hello, PyLadies!") 24 | ``` 25 | 26 | Then click the "Run" button at the top of the screen. 27 | 28 | ![First program](../obrazy/d06/krok_3.png) 29 | 30 | You will see the output in the window on the right side. 31 | -------------------------------------------------------------------------------- /obrazy/d01/krok_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d01/krok_1.png -------------------------------------------------------------------------------- /obrazy/d01/krok_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d01/krok_2.png -------------------------------------------------------------------------------- /obrazy/d01/krok_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d01/krok_3.png -------------------------------------------------------------------------------- /obrazy/d01/krok_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d01/krok_4.png -------------------------------------------------------------------------------- /obrazy/d01/krok_5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d01/krok_5.jpg -------------------------------------------------------------------------------- /obrazy/d01/krok_6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d01/krok_6.jpg -------------------------------------------------------------------------------- /obrazy/d01/krok_7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d01/krok_7.jpg -------------------------------------------------------------------------------- /obrazy/d06/krok_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d06/krok_1.png -------------------------------------------------------------------------------- /obrazy/d06/krok_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d06/krok_2.png -------------------------------------------------------------------------------- /obrazy/d06/krok_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d06/krok_3.png -------------------------------------------------------------------------------- /obrazy/d06/krok_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PyConPL/pyladies-workshop/9affa0e48976d81551fb3892de62fd19b8286880/obrazy/d06/krok_4.png --------------------------------------------------------------------------------