Skip to content

Instantly share code, notes, and snippets.

@niya3
Last active September 17, 2018 19:49
Show Gist options
  • Save niya3/847019cb3ddb1f882fb72f6459c03ce1 to your computer and use it in GitHub Desktop.
Save niya3/847019cb3ddb1f882fb72f6459c03ce1 to your computer and use it in GitHub Desktop.
Python 3 basics
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Основы программирования на языке Python 3\n",
"\n",
"\n",
"## Цель занятия\n",
" * изучим основы программирования\n",
" * освоим небольшую, но самодостаточную часть языка Python\n",
" * напишем несколько простых программ\n",
"\n",
"## Этапы программирования\n",
"1. Постановка задачи\n",
"1. Составление алгоритма\n",
"1. **Написание исходного кода**\n",
"1. Выполнение программы\n",
"1. Решение задачи\n",
"\n",
"Аналогия: записать рецепт приготовления сложного блюда для исполнительного, но недогадливого повара.\n",
"\n",
"## План\n",
"1. Python\n",
"1. Переменные\n",
"1. Структурное программирование\n",
"1. Функции\n",
"1. Методы\n",
"1. Строки"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"# Характерные черты Python\n",
"\n",
"## Что такое Python\n",
"\n",
"Python - это интерпретируемый высокоуровневый язык программирования общего назначения.\n",
"\n",
"\n",
"### Плюсы\n",
"* Простой и единообразный синтаксис\n",
"* Батарейки в комплекте (стандартная библиотека)\n",
"* Богатый репозиторий сторонних модулей\n",
"* Кроссплатформенный - windows, linux, macos, ... + архитектуры\n",
"\n",
"### Минусы\n",
"* Динамическая типизация\n",
" * проверки во время исполнения\n",
" * относительно медленное исполнение (решаемо<sup>[1][2]</sup>)\n",
"* Недостаточная поддержка параллельности<sup>[3]</sup>\n",
"\n",
"\n",
"1. [How can SciPy be fast if it is written in an interpreted language like Python?](https://www.scipy.org/scipylib/faq.html#id11)\n",
"1. [Integrating Python With Other Languages](https://wiki.python.org/moin/IntegratingPythonWithOtherLanguages)\n",
"1. [GoLang vs Python: deep dive into the concurrency](https://made2591.github.io/posts/go-py-benchmark)\n",
"\n",
"\n",
"### Почему Python\n",
"* Широко распространён\n",
"* Просто начать изучать и использовать\n",
"* Просто разрабатывать\n",
"* Много вакансий :)\n",
"\n",
"\n",
"1. [Python Design Patterns](https://www.youtube.com/watch?v=Er5K_nR5lDQ)\n",
"\n",
"### Применение Python\n",
"Прикладное ПО, игры, веб-программирование, системной администрирование, научные расчеты, встраиваемые системы\n",
"\n",
"1. [List of Python software](https://en.wikipedia.org/wiki/List_of_Python_software)\n",
"\n",
"### Python 2 vs Python 3\n",
"```python\n",
"Поддержка Python 2.7 заканчивается в 2020 => Python 3\n",
"```\n",
"\n",
"## Реализации\n",
"PyPy, IronPython, QPython, Stackless, Jython, ..., **CPython** - эталонная реализация\n",
"\n",
"\n",
"1. [Python Implementations](https://wiki.python.org/moin/PythonImplementations)\n",
"\n",
"## Интерпретатор\n",
"python, ipython, jupyter notebook, IDE или онлайн-интерпретаторы:\n",
"\n",
"* https://repl.it/languages\n",
"* https://www.onlinegdb.com/online_python_compiler\n",
"\n",
"## Скрипт\n",
"Текстовый файл с программой, доступный на чтение. На целевой машине должна быть нужная версия интерпретатора + установлены зависимости.\n",
"\n",
"## замораживаем в исполняемый файл\n",
"* bbFreeze\n",
"* py2exe\n",
"* pyInstaller\n",
"\n",
"\n",
"1. [Freezing Your Code](https://docs.python-guide.org/shipping/freezing/)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Основы программирования\n",
"* Императивное структурное программирование\n",
"* [Теорема Бёма-Якопини](https://ru.wikipedia.org/wiki/Теорема_Бёма_—_Якопини) - любой алгоритм можно записать, используя всего три инструмента:\n",
" * Последовательность - выполнение нескольких команд подряд\n",
" * Условный переход\n",
" * Повторение\n",
"\n",
"\n",
"## Основы Python 3.7"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, world!\n"
]
}
],
"source": [
"print('Hello, world!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Ключевые слова \n",
"```python\n",
"False await else import pass\n",
"None break except in raise\n",
"True class finally is return\n",
"and continue for lambda try\n",
"as def from nonlocal while\n",
"assert del global not with\n",
"async elif if or yield\n",
"```\n",
"\n",
"\n",
"1. [Python 3.7 keywords](https://docs.python.org/3/reference/lexical_analysis.html#keywords)\n",
"\n",
"\n",
"### Атомарные типы\n",
"\n",
"#### Числа\n",
"\n",
"* целые: `1; 6; 1024`\n",
"* с плавающей точкой `0.5; 3.1415`\n",
"* комплексные: `7 - 3j`\n",
"\n",
"\n",
"Поддерживают операции `+ - * / % **`, и многие другие\n",
"\n",
"Можно смешивать в выражении целочисленные и с плавающей точкой.\n",
"\n",
"1. [Numeric Types — int, float, complex](https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex)\n",
"\n",
"#### Логический тип:\n",
"```python\n",
"True False\n",
"```\n",
"Символизируют истинность или ложность\n",
"\n",
"#### NoneType\n",
"```python\n",
"None\n",
"```\n",
"Символизирует пустоту\n",
"\n",
"Python удобно использовать как калькулятор!\n",
"\n",
"**NB** Помни про приоритет операторов и сам расставляй скобки."
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"-0.25"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"1 + 1 - 9 / 4"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`#` - скрывает остаток строки от интерпретатора, комментирует"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# раскомментируй и выполни, чтобы увидеть как Python сообщает об ошибках\n",
"# 1 / 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Переменные\n",
"\n",
"1. Сохраняем промежуточные результаты, получившиеся во время выполнения программы.\n",
"2. Считываем.\n",
"\n",
"Аналогия - телефонная книжка с номерами.\n",
"\n",
"Допустимые имена переменных содержат:\n",
"\n",
"* цифры (но не начинаются с них)\n",
"* буквы (в [Unicode понимании этого слова](https://docs.python.org/3/reference/lexical_analysis.html#identifiers), но можно ограничиться латиницей :) )\n",
"* подчеркивания (подчеркивания в начале и конце имени имеют [особый смысл](https://www.pythonmania.net/en/2017/03/05/underscore-in-python/))\n",
"\n",
"Рекомендуемый стиль: [*snake_case*](https://en.wikipedia.org/wiki/Snake_case), он же *lower_case_with_underscores*"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"current_year = 2018\n",
"π = 333/106\n",
"комплексное_число = 1 - 2j"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2018"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"current_year"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3.141509433962264"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"π"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(1-2j)"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"комплексное_число"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [],
"source": [
"# Не получится использовать ключевое слово в качестве имени переменной\n",
"\n",
"# True = True"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hi!\n"
]
}
],
"source": [
"# Можно, но не стоит так поступать: скрываем имя встроенной функции. Аккуратно выбирайте имена!\n",
"# NB после выполнения следующей строчки исходный print больше недоступен, перезапустите интерпретатор\n",
"# print = 'print'\n",
"\n",
"print('Hi!')"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"# одновременное присваивание\n",
"a, b = 42, None\n",
"a, b = b, a # swap\n",
"\n",
"# _ - неименованная переменная, часто используется для отбрасывания \"лишнего\"\n",
"wanted, _, _, _ = True, False, None, 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Логика"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"1 > 2"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"3 + 2 != 5"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x = 3; 3 <= x < 5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Любой объект [можно интерпретировать](https://docs.python.org/3/library/stdtypes.html#truth-value-testing) как False или True.\n",
"\n",
"`False --- False, None, 0, 0.0, пустые объекты ссылочных типов, ...; True - всё остальное`"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### not \n",
"\n",
" |A|not||\n",
" |-|--|--|\n",
" | True|False|\n",
" | False|True|\n",
"\n",
"### or\n",
" |A|B|or|\n",
" |-|-|-|\n",
" |True|True|True|\n",
" |True|False|True|\n",
" |False|True|True|\n",
" |False|False|False|\n",
"\n",
"### and\n",
" |A|B|and|\n",
" |-|-|-|\n",
" |True|True|True|\n",
" |True|False|False|\n",
" |False|True|False|\n",
" |False|False|False|\n",
" \n",
"**NB**\n",
" \n",
"* Вычисление `B` может быть пропущено, если из `A` всё ясно (`True or ... => True`)\n",
"* `and и or` возвращают не `True или False`, но `A или B` "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Ветвления: if, elif, else\n",
"Условно выполняющиеся блоки кода\n",
"\n",
"\n",
"Аналогия - выбор, куда свернуть на перекрестке\n",
"\n",
"[if statements](https://docs.python.org/3/tutorial/controlflow.html#if-statements)\n",
"\n",
"Обрати внимание на двоеточие и одинаковые отступы от левого края\n",
"```python\n",
"before_if\n",
"\n",
"if condition:\n",
" pass # \"ничего не делай\". здесь замещает ещё не написанный блок кода\n",
"elif another_condition:\n",
" doing_smt1\n",
" doing_smt2\n",
" doing_smt3\n",
"elif one_more_condition:\n",
" doing_nothing\n",
"else:\n",
" doing_another\n",
" \n",
"after_if\n",
"```"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Time to sleep\n"
]
}
],
"source": [
"current_hour = 23\n",
"if current_hour > 22:\n",
" print('Time to sleep')"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Time to wake up\n"
]
}
],
"source": [
"current_hour = 8\n",
"if current_hour > 7:\n",
" print('Time to wake up')\n",
" #print('Good morning!')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Циклы и итерации: while, for\n",
"Многократно выполняющиеся блоки кода\n",
"\n",
"Аналогия - смена месяцев, времен года. \n",
"\n",
"\n",
"```python\n",
"while condiniton:\n",
" doing_one_stuff\n",
" doing_another_stuff\n",
"```\n",
"\n",
"Тело цикла выполняется пока условие истинно. Необходимо предусмотреть выход из цикла.\n",
"\n",
"[Итерация по последовательности](https://docs.python.org/3/reference/compound_stmts.html#the-for-statement)\n",
"```python\n",
"for elem in sequence:\n",
" doing_smt\n",
"```\n",
"\n",
"Элементы последовательности поочередно записываются в переменную.\n",
"\n",
"[Управляем циклом](https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)\n",
"\n",
"```python\n",
"continue - перейти к следующей итерации цикла\n",
"break - прервать цикл\n",
"else - обработка случая \"цикл не был прерван\"\n",
"```\n",
"\n",
"**NB** Можно случайно написать \"вечный\" цикл - условие которого всегда истинно и выполнение программы не выходит за пределы этого цикла. Прервать \"зависший\" интерпретатор можно нажатием комбинации клавиш `Ctrl-C`."
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"100\n",
"90\n",
"80\n",
"70\n",
"60\n",
"50\n",
"40\n",
"30\n",
"20\n",
"10\n",
"0\n"
]
}
],
"source": [
"i = 100\n",
"while i >= 0:\n",
" print(i)\n",
" i = i - 10"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"1\n",
"2\n",
"3\n",
"4\n",
"5\n",
"6\n",
"7\n",
"8\n",
"9\n"
]
}
],
"source": [
"for i in range(10):\n",
" print(i)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Практика"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"# Выведем на экран числа от 10 до 1, используя while"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"# ... добавив условие и continue, вывести только числа меньше 7"
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [],
"source": [
"# ... добавив условие и break, вывести только числа больше 5"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"# ... дополнив предыдущее условие, вывести только четные числа больше 5\n",
"# hint: and i % 2 == 0"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Функции\n",
"Именованные блоки кода\n",
"\n",
"Черный ящик - что-то на входе, нечто на выходе и (обычно) не важно, что внутри.\n",
"\n",
"Аналогия - функция в математике. "
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [],
"source": [
"# синтаксис определения функции\n",
"def some_func():\n",
" pass"
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"<function __main__.some_func()>"
]
},
"execution_count": 23,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# имя функции\n",
"some_func"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [],
"source": [
"# синтаксис вызова функции - ()\n",
"some_func()"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"# не всё можно вызвать\n",
"# None()\n",
"# 1()"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1\n",
"2\n",
"3\n"
]
}
],
"source": [
"# аргументы - то, что подается на вход и является доступным внутри функции\n",
"def printer(x, y, z):\n",
" print(x)\n",
" print(y)\n",
" print(z)\n",
" \n",
"printer(1, 2, 3)"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"a\n",
"[1, 2, 3]\n",
"5\n"
]
}
],
"source": [
"printer('a', [1, 2, 3], 3 + 2)"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2 . 8 = 256\n"
]
}
],
"source": [
"# значения аргументов по умолчанию\n",
"def printer(x, y=8, z=256):\n",
" print(f'{x} . {y} = {z}')\n",
"\n",
"printer(2)"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"16 . 16 = 256\n"
]
}
],
"source": [
"# можно переставлять именованные аргументы\n",
"printer(y=16, x=16)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: все аргументы передаются \"по ссылке\", но изменять переданные в функции можно лишь объекты изменяемых типов(списки, словари, множества...).\n",
"\n",
"Note: функция доступна только ниже её определения, когда интерпретатор \"пройдёт\" её\n",
"\n",
"Note: помните про [области видимости](https://python-scripts.com/scope) "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Возврат значения"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3\n"
]
}
],
"source": [
"def add(a, b):\n",
" s = a + b\n",
" return s\n",
"\n",
"one_plus_two = add(1, 2)\n",
"print(one_plus_two)"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"catdog\n"
]
}
],
"source": [
"cat_and_dog = add('cat', 'dog')\n",
"print(cat_and_dog)"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[2, 12][85,[0,6]]\n"
]
}
],
"source": [
"phone = add('[2, 12]', '[85,[0,6]]')\n",
"print(phone)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Некоторые встроенные функции\n",
"\n",
"```python\n",
"min, max, sum, len\n",
"str, int, float, list, tuple, dict, set\n",
"dir, help\n",
"```\n",
"\n",
"### Документация"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on built-in function sum in module builtins:\n",
"\n",
"sum(iterable, start=0, /)\n",
" Return the sum of a 'start' value (default: 0) plus an iterable of numbers\n",
" \n",
" When the iterable is empty, return the start value.\n",
" This function is intended specifically for use with numeric values and may\n",
" reject non-numeric types.\n",
"\n"
]
}
],
"source": [
"help(sum)"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on function add in module __main__:\n",
"\n",
"add(a, b)\n",
" Prints sum of two elements\n",
"\n"
]
}
],
"source": [
"# продокументируем нашу фунцию - добавим строку после её определения\n",
"def add(a, b):\n",
" ' Prints sum of two elements '\n",
" s = a + b\n",
" return s\n",
"\n",
"help(add)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Вложенные функции\n",
"\n",
"Функция (как и всё остальное) - полноправный объект, можно передавать в функцию, можно возвращать из функции."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"12\n"
]
}
],
"source": [
"def adder(x):\n",
" \n",
" def add_y(y):\n",
" return x + y\n",
"\n",
" return add_y\n",
"\n",
"# создадим функцию add2, возвращающую результат сложения единственного аргумента и числа 2\n",
"add2 = adder(2)\n",
"\n",
"print(add2(10))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: [замыкания](https://devpractice.ru/closures-in-python/)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Практика"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"# Пишем функцию, которая выводит слово \"Привет\""
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"# ..., которая выводит свой единственный аргумент"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [],
"source": [
"# ..., которая возвращает свой __второй__ аргумент"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [],
"source": [
"# Пишем функции калькулятора: sub, div, mul\n",
"\n",
"def add(x, y):\n",
" r = x + y\n",
" return s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Объекты и методы (поверхностно)\n",
"\n",
"* Всё есть объект!\n",
"* Метод - функция, связанная с объектом."
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']\n"
]
}
],
"source": [
"# выведем все поля и методы объекта 1 типа int, их довольно много\n",
"print(dir(1))"
]
},
{
"cell_type": "code",
"execution_count": 41,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 41,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# синтаксис вызова: имя_объекта.имя_метода()\n",
"some_num = 255\n",
"some_num.bit_length()"
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {
"scrolled": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']\n"
]
}
],
"source": [
"# функция - объект и имеет методы\n",
"print(dir(help))"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'None'"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
" None.__str__()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: магия Python заключается в методах с подчеркиваниями, именно они знают как вывести справку, как привести к строковому представлению, как итерироваться по последовательности и много другое. Такие [методы](https://habr.com/post/186608/) называются [магическими](https://ru.coursera.org/lecture/diving-in-python/maghichieskiie-mietody-tpT6t)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Строки\n",
"\n",
"Строка - неизменяемая последовательность символов\n",
"\n",
"Определение:\n",
"* пара `' или \"` - однострочная строка. Разницы между `' и \"` нет.\n",
"* пара `''' или \"\"\"` - многострочная строка (полезно для длинных текстов и документирования). Можно использовать как блочный комментарий :)"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello!\n"
]
}
],
"source": [
"greeting = \"Hello!\"\n",
"\n",
"print(greeting)"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# длина\n",
"len(greeting)"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'H'"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# обращение по индексу\n",
"greeting[0]"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'e'"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# строка из единственного символа - тоже строка\n",
"greeting[1][0][0][0][0]"
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'!'"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# индексация с конца\n",
"greeting[-1]"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"He\n",
"llo!\n"
]
}
],
"source": [
"# срез. начало включается, конец не включается\n",
"print(greeting[0:2])\n",
"print(greeting[2:])"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'!olleH'"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# в обратном порядке\n",
"greeting[::-1]"
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"H\n",
"e\n",
"l\n",
"l\n",
"o\n",
"!\n"
]
}
],
"source": [
"# итерируемся\n",
"for ch in greeting:\n",
" print(ch)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Форматирование строк\n",
"\n",
"Преобразуем переменные к нужному строковому представлению одним из способов."
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [],
"source": [
"city = 'Нижний Новгород'\n",
"age = 800"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Городу Нижний Новгород исполнилось 800 лет.'"
]
},
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# конкатенация (сложение) строк\n",
"'Городу ' + city + ' исполнилось ' + str(age) + ' лет.'"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Городу Нижний Новгород исполнилось 800 лет.'"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"'Городу %s исполнилось %d лет.' % (city, age)"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Городу Нижний Новгород исполнилось 800 лет.'"
]
},
"execution_count": 55,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"'Городу {} исполнилось {} лет.'.format(city, age)"
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Городу Нижний Новгород исполнилось 800 лет.'"
]
},
"execution_count": 56,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# мой любимый\n",
"f'Городу {city} исполнилось {age} лет.'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Форматируем [c-style](https://docs.python.org/3/library/stdtypes.html#old-string-formatting)"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'800 800.0000 8e+02'"
]
},
"execution_count": 57,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f\"%d %2.4f %1.e\" % (age, age, age)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"И [python-style](https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals)"
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'result: 12.35'"
]
},
"execution_count": 58,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"width = 10\n",
"precision = 4\n",
"value = 12.34567\n",
"f\"result: {value:{width}.{precision}}\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Некоторые методы строк"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']\n"
]
}
],
"source": [
"# их много!\n",
"print(dir(str))"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'hi!'"
]
},
"execution_count": 60,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"greeting = 'Hello!'\n",
"\n",
"# возврат измененной строки\n",
"greeting.replace('Hello', 'hi')"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'Hello!'"
]
},
"execution_count": 61,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# NB исходная строка не изменилась\n",
"greeting"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'HELLO!'"
]
},
"execution_count": 62,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"greeting.upper()"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'hello!'"
]
},
"execution_count": 63,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"greeting.lower()"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# состоит только из букв?\n",
"'hi'.isalpha()"
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 65,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# состоит только из цифр?\n",
"'hi'.isdigit()"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"greeting.isalpha()"
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"5"
]
},
"execution_count": 67,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# вернёт индекс первого вхождения или -1\n",
"greeting.find('!')"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"-1"
]
},
"execution_count": 68,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"'hi'.find('0')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Практика"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [],
"source": [
"# Сохраним свое имя в переменную"
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [],
"source": [
"# Приведем имя к верхнему регистру (В КАПСЕ)"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [],
"source": [
"# Заменим в имени первую букву на последнюю \n",
"# hint: .replace() и [-1] "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Ещё методы строк"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [],
"source": [
"# разобъём строку по пробельным символам на список строк\n",
"months = \"Jan Feb Mar Apr May Jun\"\n",
"\n",
"splitted = months.split()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: [про списки](http://ru.diveintopython.net/odbchelper_list.html) поговорим на следующей встрече"
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']\n"
]
}
],
"source": [
"print(splitted)"
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Jan, Feb, Mar, Apr, May, Jun\n"
]
}
],
"source": [
"print(', '.join(splitted))"
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Jan\n",
"Feb\n",
"Mar\n",
"Apr\n",
"May\n",
"Jun\n"
]
}
],
"source": [
"# итерируемся по списку\n",
"for month in splitted:\n",
" print(month)"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Входит ли строка в под строку?\n",
"'ay Jun' in months"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"False"
]
},
"execution_count": 77,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"'January'.startswith('Feb')"
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 78,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"'Ноябрь'.endswith('ябрь')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Практика"
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [],
"source": [
"# Выведем список месяцев, начинающихся с буквы 'J'\n",
"# hint: startswith\n",
"months_list = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [],
"source": [
"# Выведем список месяцев, содержащих букву 'a' \n",
"# hint: in\n",
"months_list = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Преобразование типов"
]
},
{
"cell_type": "code",
"execution_count": 81,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0"
]
},
"execution_count": 81,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"int(\"0\")"
]
},
{
"cell_type": "code",
"execution_count": 82,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 82,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"int(1.5)"
]
},
{
"cell_type": "code",
"execution_count": 83,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"9.0"
]
},
"execution_count": 83,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"float(9)"
]
},
{
"cell_type": "code",
"execution_count": 84,
"metadata": {},
"outputs": [],
"source": [
"# int('nine')"
]
},
{
"cell_type": "code",
"execution_count": 85,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['n', 'i', 'n', 'e']"
]
},
"execution_count": 85,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"list('nine')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Ввод информации\n",
"\n",
"`input` прерывает выполнение программы, пока нажатием Enter не завершится ввод с клавиатуры.\n",
"\n",
"Аналогия - ожидание отзыва по рации после фразы \"Как слышно? Приём\"."
]
},
{
"cell_type": "code",
"execution_count": 86,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Который сейчас год? 2018\n"
]
}
],
"source": [
"# NB попробуйте ввести и что-то похожее на целое число, и что-то не похожее на целое число\n",
"current_year = input('Который сейчас год? ')\n",
"\n",
"python_age = int(current_year) - 1991"
]
},
{
"cell_type": "code",
"execution_count": 87,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Язык Python появился 27 лет назад.\n"
]
}
],
"source": [
"print(f'Язык Python появился {python_age} лет назад.')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Практика"
]
},
{
"cell_type": "code",
"execution_count": 88,
"metadata": {},
"outputs": [],
"source": [
"# Пишем конвертеры. Пользователь вводит число, а мы его переводим:\n",
"# из фунтов фунты в килограммы (*0.4536)\n",
"# из рублей в доллары (/68.04)\n",
"# из мегабайтов в байты (*2**20 или битовый сдвиг: <<20)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Домашнее задание"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"1. Пишем игру \"Угадай число\". Компьютер \"загадывает\" число в некотором дипазоне и предлагает игроку его отгадать. Игрок вводит свой вариант ответа, а компьютер \"подсказывает\": загаданное число больше (или меньше) чем введённое. Игра заканчивается, когда игрок угадал."
]
},
{
"cell_type": "code",
"execution_count": 89,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"86\n"
]
}
],
"source": [
"# Hint: делаем игру интересной :)\n",
"\n",
"import random\n",
"number = random.randrange(100) + 1\n",
"print(number)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Note: [import и модули](https://www.ibm.com/developerworks/ru/library/l-python_part_5/index.html)\n",
"\n",
"2. Добавляем в игру предложение сыграть ещё раз. И ещё раз. И ещё ;)\n",
"\n",
"Hint: не забудьте сформулировать условие выхода, например, игрок ввёл специальную фразу.\n",
"\n",
"3. (\\*) Добавляем обработку неправильных входных данных, нельзя ведь сравнивать 5 и 'пять'!\n",
"\n",
"Hint: [исключения и их обработка](https://younglinux.info/python/exceptions)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Продолжаем учиться!\n",
"\n",
"## Справка\n",
"* `help(smt)`\n",
"* `dir(smt)`\n",
"* [Python 3 documentation](https://docs.python.org/3/)\n",
"\n",
"\n",
"## Учебники и курсы\n",
"* [Python. Введение в программирование](https://younglinux.info/python.php)\n",
"* [Учебник по языку Python 3.1](https://pep8.ru/doc/tutorial-3.1/)\n",
"* [Программирование на Python, лекции CSC 2018](https://compscicenter.ru/courses/python/2018-spring)\n",
"* [Python для сетевых инженеров](https://natenka.gitbooks.io/pyneng/)\n",
"* [The Python Tutorial](https://docs.python.org/3/tutorial/index.html)\n",
"\n",
"## Задачи\n",
"* [Учите Python](https://pythontutor.ru/)\n",
"* [Адаптивный тренажер Python](https://stepik.org/course/431/)\n",
"* Project Euler: [en](https://projecteuler.net/), [ru](http://euler.jakumo.org/)\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.5"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment