{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Объектно-ориентированное программирование и информационная безопасность\n",
    "\n",
    "*Валерий Семенов, Самарский университет*\n",
    "\n",
    "<div style=\"text-align:center\"><img src=\"Python.png\" width=\"200\"></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2 style=\"text-align:center; margin-top:60px\">Встроенные функции для работы с числами</h2>\n",
    "\n",
    "<div style=\" margin-left:50px\">\n",
    "<li style=\"text-align:justify\"><strong>abs()</strong> – абсолютная величина;</li>\n",
    "<li style=\"text-align:justify\"><strong>divmod()</strong> – частное и остаток от деления;  </li>\n",
    "<li style=\"text-align:justify\"><strong>pow()</strong> – возведение в степень;  </li>\n",
    "<li style=\"text-align:justify\"><strong>round()</strong> – округление десятичного числа.  </li>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = -4\n",
    "b = 5.8"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "abs(a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.8"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "abs(b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2, 3)"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "divmod(11, 4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "divmod(11,4)[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pow(2,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.0"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pow(9, 1/2)        # Вычисляем корень"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "int(pow(9, 0.5))   # Вычисляем корень"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5.57"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 5.56812        \n",
    "round(a,2)         # Округление"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2 style=\"text-align:center; margin-top:60px\">Основные функции и методы для работы с последовательностями</h2>\n",
    "\n",
    "<div style=\" margin-left:50px\">\n",
    "<li style=\"text-align:justify\"><strong>len(</strong><i>последовательность</i><strong>)</strong> - возвращает количество элементов в последовательности; </li>\n",
    "<li style=\"text-align:justify\"><strong>sum(</strong><i>последовательность</i><strong>)</strong> – сумма членов изменяемой последовательности; </li>\n",
    "<li style=\"text-align:justify\"><strong>max(</strong><i>последовательность</i><strong>)</strong> - возвращает максимальное значение в последовательности;  </li>\n",
    "<li style=\"text-align:justify\"><strong>min(</strong><i>последовательность</i><strong>)</strong> - возвращает минимальное значение в последовательности;  </li>\n",
    "<li style=\"text-align:justify\"><i>последовательность</i><strong>.index(</strong><i>элемент</i><strong>)</strong> - возвращает индекс элемента, имеющего указанное значение;  </li>\n",
    "<li style=\"text-align:justify\"><i>последовательность</i><strong>.count(</strong><i>элемент</i><strong>)</strong> - возвращает число вхождений элемента в последовательность.    </li>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = 'Python'\n",
    "len(s)  # Количество элементов в строке s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "q = [1, 3, 5, 1]\n",
    "max(q)  # Максимальный элемент в списке чисел"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max(range(5))  # Максимальное значение в диапазоне"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'y'"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max(s)  # Максимальный элемент в строке (выбирается по коду символа)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "min(q)  # минимальный элемент числового списка"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'<' not supported between instances of 'str' and 'int'",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[15], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m \u001b[38;5;28mmin\u001b[39m([\u001b[38;5;241m1\u001b[39m, \u001b[38;5;241m5\u001b[39m, \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mv\u001b[39m\u001b[38;5;124m'\u001b[39m])\n",
      "\u001b[1;31mTypeError\u001b[0m: '<' not supported between instances of 'str' and 'int'"
     ]
    }
   ],
   "source": [
    "min([1, 5, 'v'])  # Нельзя смешивать числовые и символьные последовательности"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "26"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 5\n",
    "b = 4\n",
    "sum((a,b,a,b,2*b))  # Суммирование последовательности (кортежа)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "31"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum([1,7,9,5,a,b])  # Суммирование последовательности (списка)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 'Привет'\n",
    "a.index('в') # Индекс символа П в строке а"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "range(5).index(3)  # Индекс 1 в диапазоне чисел от 0 до 4"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "w = [1, 12, 3, 7, 2, 3, 5]\n",
    "w.count(3)  # Количество элементов равных 1 в числовом списке l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2 style=\"text-align:center; margin-top:60px\">Полезные методы для работы со списками</h2>\n",
    "\n",
    "<div style=\" margin-left:50px\">\n",
    "<li style=\"text-align:justify\"><i>список</i><strong>.append(</strong><i>элемент</i><strong>)</strong> - добавляет элемент в конец списка;  </li>\n",
    "<li style=\"text-align:justify\"><i>список</i><strong>.extend(</strong><i>последовательность</i><strong>)</strong> - добавляет элементы последовательности в конец списка;  </li>\n",
    "<li style=\"text-align:justify\"><i>список</i><strong>.insert(</strong><i>индекс, элемент</i><strong>)</strong> - добавляет один элемент в указанную позицию;  </li>\n",
    "<li style=\"text-align:justify\"><i>список</i><strong>.pop(</strong><i>индекс</i><strong>)</strong> - удаляет элемент, расположенный по указанному индексу; </li>\n",
    "<li style=\"text-align:justify\"><i>список</i><strong>.remove(</strong><i>элемент</i><strong>)</strong> - удаляет первый элемент списка, содержащий указанное значение; </li>\n",
    "<li style=\"text-align:justify\"><i>список</i><strong>.reverse()</strong> - изменяет порядок следования элементов списка на противоположный;  </li>\n",
    "<li style=\"text-align:justify\"><i>список</i><strong>.sort()</strong> - сортирует список;  </li>\n",
    "<li style=\"text-align:justify\"><i>список</i><strong>.copy()</strong> - копирует список.</li> \n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 1, 'a']"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spisok = [1, 2, 1, 'a']\n",
    "spisok"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 1, 'a', 'buka']"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spisok.append(\"buka\")  # Добавляем строку в конец списка spisok\n",
    "spisok"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 1, 'a', 'buka', 'c', 'd', 'e']"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spisok.extend('cde')  # Добавляем элементы строки в конец списка spisok\n",
    "spisok"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 1, 'a', 88, 'buka', 'c', 'd', 'e']"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spisok.insert(4, 88)  # Добавляем элемент 88 в позицию 4\n",
    "spisok"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 1, 'a', 88, 'buka', 'c', 'd']"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spisok.pop(-1)  # Удаляем последний элемент списка\n",
    "spisok"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[2, 1, 'a', 88, 'buka', 'c', 'd']"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spisok.remove(1)  # Удаляет первый элемент равный 1\n",
    "spisok"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['d', 'c', 'buka', 88, 'a', 1, 2]"
      ]
     },
     "execution_count": 27,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "spisok.reverse()  # Переворачивает список\n",
    "spisok"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\"><strong><u><i>Замечание!</i></u></strong> Если необходимо изменить порядок следования и <strong>получить новый список</strong>, то следует воспользоваться функцией <strong>reversed(</strong><i>последовательность</i><strong>)</strong>. Эта функция возвращает <strong><i>итератор</i></strong> (итераторы в Python — это специальные объекты, которые позволяют получать элементы коллекции один за другим, без необходимости знать внутреннюю структуру данных), который можно преобразовать в список с помощью функции <strong>list()</strong>.</div>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Проиллюстрируем использование функции <strong>reversed()</strong> для создания строки, в которой порядок символов изменен на обратный:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python'"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stroka_old = \"Python\"  # Исходная строка\n",
    "stroka_old"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'nohtyP'"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "k = reversed(stroka_old)   # Реверсивный итератор k из исходной строки\n",
    "new = list(k)              # Преобразуем в список символов\n",
    "stroka_new = \"\".join(new)  # \"Склеиваем\" в новую строку\n",
    "stroka_new"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'nohtyP'"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stroka_new = \"\".join(list(reversed(stroka_old)))  # Без дополнительных переменных\n",
    "stroka_new"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('Python', 'nohtyP')"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "stroka_old, stroka_new  # Старая и новая строки"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('Python', 'nohtyP')"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Намного проще изменить порядок символов в строке при помощи срезов !!!!!!!!!\n",
    "stroka_new = stroka_old[::-1]  \n",
    "stroka_old, stroka_new         # Старая и новая строки"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 5, 5, 6, 7]"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = [7, 5, 3, 5, 6]  # Сортируем список\n",
    "d.sort()\n",
    "d"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">В некоторых случаях необходимо получить отсортированный список, а текущий список оставить без изменений. </div>\n",
    "<div style=\"text-indent:30px; text-align:justify\">Для этого следует воспользоваться функцией <strong>sorted()</strong>.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "([7, 5, 3, 5, 6], [3, 5, 5, 6, 7])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "d = [7, 5, 3, 5, 6]\n",
    "u = sorted(d)  # Сортируем список\n",
    "d, u"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 5, 5, 6, 7]"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t = u.copy()  # Копируем список\n",
    "t"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "u is t  # Переменные указывают на один и тот же объект?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t = u\n",
    "u is t  # Переменные указывают на один и тот же объект?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 5, 6, 7]"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Удаление заданного элемента\n",
    "del t[1]\n",
    "t"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2 style=\"text-align:center; margin-top:60px\">Основные методы для работы со строками</h2>\n",
    "\n",
    "<div style=\" margin-left:50px\">\n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.find(</strong><i>подстрока</i><strong>)</strong> - поиск подстроки в строке. Возвращает номер первого вхождения данной строки (“поиск слева”) или <strong>-1</strong> ; </li>\n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.rfind(</strong><i>подстрока</i><strong>)</strong> - поиск подстроки в строке. Возвращает индекс последнего вхождения данной строки (“поиск справа”) или <strong>-1</strong> ; </li>\n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.replace(</strong><i>шаблон, замена</i><strong>)</strong> - замена шаблона на замену; </li>\n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.split(</strong><i>символ</i><strong>)</strong> - разбиение строки по разделителю; </li>  \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.isdigit()</strong> - проверяет состоит ли строка только из цифр; </li> \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.isalpha()</strong> - проверяет состоит ли строка только из букв; </li> \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.upper()</strong> - преобразование строки к верхнему регистру (заглавные буквы); </li> \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.lower()</strong> - преобразование строки к нижнему регистру (строчные буквы); </li>  \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.startswith(</strong><i>шаблон</i><strong>)</strong> - проверяет начинается ли строка с шаблона; </li>  \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.endswith(</strong><i>шаблон</i><strong>)</strong> - проверяет заканчивается ли строка шаблоном; </li>   \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.join(</strong><i>список</i><strong>)</strong> - формирует строку из списка с разделителем; </li>  \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.strip(</strong><i>символ</i><strong>)</strong> - удаление символов в начале и в конце строки; </li> \n",
    "<li style=\"text-align:justify\"><i>строка</i><strong>.partition(</strong><i>шаблон</i><strong>)</strong> - возвращает кортеж, содержащий часть перед шаблоном, сам шаблон, и часть после шаблона. Если шаблон не найден, возвращается кортеж, содержащий саму строку, а затем две пустых строки; </li>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"Python - мой любимый язык программирования\"\n",
    "s.find('мой')  # Поиск подстроки в строке СЛЕВА"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8\n",
      "13\n"
     ]
    }
   ],
   "source": [
    "sss = \"Привет, мир! Мир - прекрасен\"\n",
    "print(sss.find('мир'))   # Позиция 8\n",
    "print(sss.rfind('Мир'))  # Позиция 13"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Как видно из предыдущих примеров, методы <strong>.find()</strong> и <strong>.rfind()</strong> не предоставляют информации обо всех вхождениях подстроки в строку. </div>\n",
    "<div style=\"text-indent:30px; text-align:justify\">В этом случае можно использовать регулярные выражения или цикл для прохождения по строке и поиска всех вхождений подстроки (подробнее об этом можно почитать <a href=\"https://sky.pro/media/poisk-vseh-vhozhdenij-podstroki-v-stroke-v-python/\"><strong>здесь</strong></a>).</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python - наш любимый язык программирования'"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "z = s.replace('мой', 'наш')  # замена в строке \"мой\" на \"наш\"\n",
    "z"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Python', '-', 'мой', 'любимый', 'язык', 'программирования']"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.split()  # Разбиение строки по пробелам"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 43,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.isdigit()  # Состоит ли строка из цифр?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.isalpha()  # Состоит ли строка из букв?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'python'.isalpha()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'PYTHON - МОЙ ЛЮБИМЫЙ ЯЗЫК ПРОГРАММИРОВАНИЯ'"
      ]
     },
     "execution_count": 46,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.upper()  # Заменяем все буквы на заглавные (верхний регистр)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'python - мой любимый язык программирования'"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.lower()  # Заменяем все буквы на строчные (нижний регистр)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.startswith('Python')  # Начинается ли строка с шаблона?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "False"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.endswith('Python')  # Заканчивается ли строка шаблоном?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python3'"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "''.join(['Py', 'thon', '3'])  # Формирует строку из списка с указанным разделителем"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python - мой любимый язык программировани'"
      ]
     },
     "execution_count": 51,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.strip('я')  # Удаление символов в начале и в конце строки"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python'"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "t = ' Python '\n",
    "t.strip(' ')  # Удаление лишних пробелов в начале и в конце"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('Python - ', 'мой', ' любимый язык программирования')"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s.partition('мой')  # Разбиение строки по шаблону"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2 style=\"text-align:center; margin-top:60px\">Форматирование строк</h2>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify\"><u>Задача.</u></div> \n",
    "<div style=\"text-indent:30px; text-align:justify\">Пользователь вводит 3 значения: день (ДД), месяц (ММ) и год (ГГГГ). </div>\n",
    "<div style=\"text-indent:30px; text-align:justify\">Нужно вывести на экран дату в формате <strong>ДД-ММ-ГГГГ</strong>.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdin",
     "output_type": "stream",
     "text": [
      "Введите день  7\n",
      "Введите месяц  12\n",
      "Введите год  1957\n"
     ]
    }
   ],
   "source": [
    "dd = input(\"Введите день \")\n",
    "mm = input(\"Введите месяц \")\n",
    "yyyy = input(\"Введите год \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Вы ввели дату 7-12-1957\n"
     ]
    }
   ],
   "source": [
    "# Вариант 1\n",
    "print('Вы ввели дату {}-{}-{}'.format(dd, mm, yyyy))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Вы ввели дату 7-12-1957\n"
     ]
    }
   ],
   "source": [
    "# Вариант 2\n",
    "print('Вы ввели дату %s-%s-%s' % (dd, mm, yyyy)) "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Вы ввели дату 7-12-1957\n"
     ]
    }
   ],
   "source": [
    "# Вариант 3\n",
    "print(f'Вы ввели дату {dd}-{mm}-{yyyy}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\"><u>Задача.</u></div> \n",
    "<div style=\"text-indent:30px; text-align:justify\">Округлить число до 4 знаков после запятой с помощью методов форматирования строк.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [],
   "source": [
    "k = 5.87346"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Округленное число 5.8735\n"
     ]
    }
   ],
   "source": [
    "print('Округленное число {0:.4f}'.format(k))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Округленное число 5.8735\n"
     ]
    }
   ],
   "source": [
    "print('Округленное число %.4f' % k)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2 style=\"text-align:center; margin-top:60px\">Методы для работы со словарями</h2>\n",
    "\n",
    "<div style=\" margin-left:50px\">\n",
    "<li style=\"text-align:justify\"><i>словарь</i><strong>.copy()</strong> - возвращает копию словаря; </li>\n",
    "<li style=\"text-align:justify\"><i>словарь</i><strong>.get()</strong> - возвращает значение ключа, но если его нет, то возвращает <strong>None</strong>; </li>\n",
    "<li style=\"text-align:justify\"><i>словарь</i><strong>.items()</strong> - возвращает пары (ключ, значение); </li>  \n",
    "<li style=\"text-align:justify\"><i>словарь</i><strong>.keys()</strong> - возвращает ключи в словаре; </li>  \n",
    "<li style=\"text-align:justify\"><i>словарь</i><strong>.values()</strong> - возвращает значения в словаре; </li>  \n",
    "<li style=\"text-align:justify\"><i>словарь</i><strong>.update(</strong><i>словарь</i><strong>)</strong> - обновляет словарь, добавляя пары (ключ, значение) из другого словаря; </li>  \n",
    "<li style=\"text-align:justify\"><i>словарь</i><strong>.clear()</strong> - очищает словарь. </li>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [],
   "source": [
    "users = {\"Tom\": {\n",
    "    \"phone\": \"+786532469\",\n",
    "    \"email\": \"tom1@gmail.com\"},\n",
    "        \"Bob\":{\n",
    "    \"phone\": {\"mob\": \"+65435680\", \"home\": \"224583\"},\n",
    "    \"email\": \"booob@gmail.com\"}\n",
    "        }"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Tom': {'phone': '+786532469', 'email': 'tom1@gmail.com'},\n",
       " 'Bob': {'phone': {'mob': '+65435680', 'home': '224583'},\n",
       "  'email': 'booob@gmail.com'}}"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "u_1 = users.copy()  # Копирование словаря\n",
    "u_1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['Tom', 'Bob'])"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users.keys()  # Все ключи"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_keys(['phone', 'email'])"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users[\"Bob\"].keys()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_values([{'phone': '+786532469', 'email': 'tom1@gmail.com'}, {'phone': {'mob': '+65435680', 'home': '224583'}, 'email': 'booob@gmail.com'}])"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users.values()  # Все значения"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_values(['+65435680', '224583'])"
      ]
     },
     "execution_count": 66,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users[\"Bob\"][\"phone\"].values()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dict_items([('Tom', {'phone': '+786532469', 'email': 'tom1@gmail.com'}), ('Bob', {'phone': {'mob': '+65435680', 'home': '224583'}, 'email': 'booob@gmail.com'})])"
      ]
     },
     "execution_count": 67,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users.items()  # Пары ключ-значение"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 68,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Tom': {'phone': '+786532469', 'email': 'tom1@gmail.com'},\n",
       " 'Bob': {'phone': {'mob': '+65435680', 'home': '224583'},\n",
       "  'email': 'booob@gmail.com'},\n",
       " 'Ann': {'skype': 'ann_123'}}"
      ]
     },
     "execution_count": 68,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user = {\"Ann\": {\"skype\": \"ann_123\"}}\n",
    "users.update(user)  # Объединение словарей\n",
    "users"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 69,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'Tom': {'phone': '+786532469'},\n",
       " 'Bob': {'phone': {'mob': '+65435680', 'home': '224583'},\n",
       "  'email': 'booob@gmail.com'},\n",
       " 'Ann': {'skype': 'ann_123'}}"
      ]
     },
     "execution_count": 69,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Удаление элемента словаря по ключу\n",
    "del users[\"Tom\"][\"email\"]\n",
    "users"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 70,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{}"
      ]
     },
     "execution_count": 70,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users.clear()  # Полная очистка словаря\n",
    "users"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
