class: center, middle, inverse # Функції, об’єкти, стандартні структури даних ## Python 101 .footnote[ ###Богдан Кулинич ] --- layout: true ## Функції --- ### def function - Код, який можна повторно використовувати (reuse) - Один з найголовніших елементів будь-якої програми ```python def convert_to_celcius(fahrenheit): return (fahrenheit - 32) * 5 / 9 print(convert_to_celcius(32)) print(convert_to_celcius(451)) ``` --- ### return Повертає значення з функції, яке можна використовувати далі. ```python def square(x): return x**2 y = square(6) # 36 ``` --- ### Область видимості (scope) ```python x = 'plumbum' def attempt_at_magic(): x = 'gold' attempt_at_magic() print(x) # 'plumbum' def magic(): global x x = 'gold' magic() print(x) # 'gold' ``` --- ### Параметри - Передача незмінних типів або літералів ```python x = 10 # 10 def square(x): x = x**2 square(x) print(x) # 10 ``` - Передача змінних типів ```python a = [1, 2, 3] def mutate(iterable): iterable.append(4) mutate(a) print(a) # [1, 2, 3, 4] ``` --- Незмінні типи: `int`, `float`, `str` (!), і ще декілька Змінні типи: `list`, `dict`, і... всі інші --- ### Параметри - Параметри за замовчуванням ```python def say(message, times=1): (message * times) say('Hello') # Hello say('Hello', 2) # HelloHello ``` - Параметри за ключовими словами. Оператори `*`, `**` ```python def hello(**kwargs): print('Hello', kwargs[firstname], kwargs[lastname]) hello(name='Petryk', lastname='Pyatochkin') # Hello Petryk Pyatochkin ``` --- ### Документація - 'Docstrings' ```python def convert_to_celcius(fahrenheit): """Convert Fahrenheit degrees to Celcius Use formula C = (F - 32) * 5 / 9 """ return (fahrenheit - 32) * 5 / 9 ``` --- - Короткий запис функції ```python square = lambda x: x**2 square(4) # 16 ``` - Рекурсія ```python def factorial(n): if n == 0: return 1 elif n > 0: return n * factorial(n-1) ``` --- layout: true ## Об’єкти --- Значення з певним станом і поведінкою --- ```python numbers = [1, 3, 5, 7] numbers.append(9) # [1, 3, 5, 7, 9] numbers.extend([11, 13]) # [1, 3, 5, 7, 9, 11, 13] numbers.pop() # [1, 3, 5, 7, 9, 11] numbers.reverse() # [11, 9, 7, 5, 3, 1] numbers.sort() # [1, 3, 5, 7, 9, 11] # Contrast to: reversed(numbers) sorted(numbers) ``` --- layout: false ## Більше структур даних! - Список (list) - Словник (dict) - Множина (set) - Кортеж (tuple) --- ## Comprehensions Короткі записи циклів, які будують різні структури даних --- ### List comprehension ```python squares = [] for x in range(5): squares.append(x**2) ``` ```python squares = [x**2 for x in range(5)] # [0, 1, 4, 9, 16] ``` Також: ```python list(map(lambda x: x**2, range(5))) ``` --- class: middle ### Set comprehension (Python 3) ```python {x for x in [5, 5, 2, 2]} # {2, 5} ``` --- class: middle ### Dict comprehension (Python 3) ```python {name: i for i, name in enumerate(['a', 'b'])} # {'a': 0, 'b': 1} ``` --- ### Генераторний вираз Генератор vs. список: ```python (x**2 for x in range(5)) #
at 0x7f516cb622d0> [x**2 for x in range(5)] # [0, 1, 4, 9, 16] ``` --- layout: true ## Обробка помилок --- try-except блок (Python 3, в Python 2 трохи інакший синтаксис) ```python try: user_input = get_user_input() except ValueError as e: print('You entered not a valid number') except TypeError as e: print(e) except Exception as e: print(e) except: print('Unexpected error') finally: print('Anyway') ``` --- Команда raise ```python def get_user_input(): # ... raise ValueError('Bad thing happened') # ... ``` --- layout: true ## Менеджер контексту --- Деякі об’єкти потрібно деініціалізовувати ```python f = open('data.txt') for line in f: print(line) f.close() ``` --- ```python with open('data.txt') as f: for line in f: print(line) ```