{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Объектно-ориентированное программирование и информационная безопасность\n",
    "\n",
    "*Валерий Семенов, Самарский университет*\n",
    "\n",
    "<div style=\"text-align:center\"><img src=\"Python.png\" width=\"200\"></div>\n",
    "\n",
    "<h1 style=\"text-align:center; margin-top:40px\">Вычисления в Python</h1>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify\">Привычные арифметические действия (сложение, вычитание, умножение, деление) в Python выглядят так же, как и в обычных калькуляторах:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1 + 4  # сложение"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "11"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "5 * 4 - 9  # умножение и вычитание"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.5"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "7 / 2  # деление"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Однако с делением все не так просто. Python всегда будет выдавать результат в виде числа с плавающей десятичной точкой (<strong>float</strong>), даже тогда, когда ожидается целочисленный ответ.</div>\n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Например:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.0"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "8 / 2  # не 4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Получился дробный результат, где дробная часть равна 0.</div>\n",
    "<div style=\"text-indent:30px; text-align:justify\">Как быть, если нужен ответ в виде целого числа?</div>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Можно воспользоваться целочисленным делением.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "8 // 2  # теперь 4"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Тут важно помнить, что при использовании оператора <strong>//</strong> дробная часть всегда будет просто отбрасываться – никакого округления происходить не будет. Для округления (обычное арифметическое, в большую и в меньшую сторону) существуют специальные функции, и мы их обсудим позже.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "7 // 2  # от 3.5 осталось 3"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Что еще можно делать с числами?</div>\n",
    "<div style=\"text-indent:30px; text-align:justify\">Возводить в степень и извлекать из них корень.</div>\n",
    "    \n",
    "<div style=\"text-indent:30px; text-align:justify\">При расчетах на калькуляторе (и в Excel) для возведения числа в степень мы обычно используем символ <strong>^</strong>.</div> \n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Попробуем:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "6 ^ 2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Получилось что-то неожиданное!</div>\n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Дело в том, что в Python оператор <strong>^</strong> используется для побитного сложения по модулю два.</div>\n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Для возведения числа в степень потребуется <strong>**</strong> (<i>смотрите картинку \"Математические операторы\" из предыдущего блокнота</i>):</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "36"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "6 ** 2  # как нужно"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "216"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "6 ** 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.8171205928321397"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "6 ** (1/3)  # дробная степень - корень 3 степени"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">В Python есть небольшое количество встроенных базовых функций, в том числе математических:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5.3459, 5.35)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = abs(-5.3459)  # возвращает абсолютное значение числа\n",
    "b = round(a, 2)  # округляет число до n знаков после запятой (n — необязательный аргумент)\n",
    "a, b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Теперь попробуем извлечь квадратный корень из числа с помощью привычной функции <strong>sqrt()</strong> (C++, Java, JavaScript, Turbo Pascal):</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'sqrt' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[12], line 1\u001b[0m\n\u001b[1;32m----> 1\u001b[0m sqrt(\u001b[38;5;241m9\u001b[39m)\n",
      "\u001b[1;31mNameError\u001b[0m: name 'sqrt' is not defined"
     ]
    }
   ],
   "source": [
    "sqrt(9)  # не получается!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Python пишет, что не знает, что такое <strong>sqrt</strong>. </div>\n",
    "    \n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">В каких случаях Python может такое писать? Например, если мы опечатались в названии функции (Python не понимает, что мы от него хотим) или если мы пытаемся обратиться к функции, которая не является базовой (Python не знает, откуда ее брать). В данном случае мы столкнулись со второй проблемой. </div>\n",
    "\n",
    "<h2 style=\"text-align:center; margin-top:40px\">Модуль <strong>math</strong></h2>\n",
    "    \n",
    "<div style=\"text-indent:30px; text-align:justify\">Функция для вычисления квадратного корня из числа хранится в специальном модуле <strong>math</strong>. Этот модуль стандартный, дополнительно устанавливать его не нужно. Но для того чтобы воспользоваться этой функцией, нужно сначала импортировать модуль, а потом вызвать из него функцию <strong>sqrt()</strong>.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.0"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math   # импортируем модуль maths\n",
    "math.sqrt(9)  # теперь все работает"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Если из <strong>math</strong> нам нужна только одна функция <strong>sqrt()</strong>, можно извлечь только ее, и тогда прописывать название модуля перед функцией не понадобится:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.0"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import sqrt\n",
    "sqrt(16)    # так тоже работает"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Иногда, если неизвестно, сколько функций потребуется, но каждый раз прописывать полностью название модуля не хочется, можно импортировать его сразу с сокращенным названием (псевдонимом):</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.0"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math as ma   # сократили название модуля math до ma\n",
    "ma.sqrt(9)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Примечание: то же будет верно и для библиотек. Пока мы столкнулись с двумя модулями – <strong>os</strong> и <strong>math</strong>, в темах по обработке данных мы будем активно работать с разными библиотеками. Если совсем упростить, модуль – это набор функций, а библиотека – это набор модулей, то есть что-то более сложное по структуре и более насыщенное по функционалу.</div>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">В модуле <strong>math</strong> есть много полезных функций для вычислений. Чтобы посмотреть, какие функции там есть, после импортирования модуля можно набрать <strong>dir(math)</strong>:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['__doc__',\n",
       " '__loader__',\n",
       " '__name__',\n",
       " '__package__',\n",
       " '__spec__',\n",
       " 'acos',\n",
       " 'acosh',\n",
       " 'asin',\n",
       " 'asinh',\n",
       " 'atan',\n",
       " 'atan2',\n",
       " 'atanh',\n",
       " 'cbrt',\n",
       " 'ceil',\n",
       " 'comb',\n",
       " 'copysign',\n",
       " 'cos',\n",
       " 'cosh',\n",
       " 'degrees',\n",
       " 'dist',\n",
       " 'e',\n",
       " 'erf',\n",
       " 'erfc',\n",
       " 'exp',\n",
       " 'exp2',\n",
       " 'expm1',\n",
       " 'fabs',\n",
       " 'factorial',\n",
       " 'floor',\n",
       " 'fmod',\n",
       " 'frexp',\n",
       " 'fsum',\n",
       " 'gamma',\n",
       " 'gcd',\n",
       " 'hypot',\n",
       " 'inf',\n",
       " 'isclose',\n",
       " 'isfinite',\n",
       " 'isinf',\n",
       " 'isnan',\n",
       " 'isqrt',\n",
       " 'lcm',\n",
       " 'ldexp',\n",
       " 'lgamma',\n",
       " 'log',\n",
       " 'log10',\n",
       " 'log1p',\n",
       " 'log2',\n",
       " 'modf',\n",
       " 'nan',\n",
       " 'nextafter',\n",
       " 'perm',\n",
       " 'pi',\n",
       " 'pow',\n",
       " 'prod',\n",
       " 'radians',\n",
       " 'remainder',\n",
       " 'sin',\n",
       " 'sinh',\n",
       " 'sqrt',\n",
       " 'sumprod',\n",
       " 'tan',\n",
       " 'tanh',\n",
       " 'tau',\n",
       " 'trunc',\n",
       " 'ulp']"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import math\n",
    "dir(math)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Примеры:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.6931471805599453"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.log(2)   # натуральный логарифм"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.0"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.log10(100)   # десятичный логарифм (логарифм по основанию 10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.0031853017931379904"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.sin(2*3.14)   # синус"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Здесь же хранятся функции для округления в большую или меньшую сторону:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.ceil(8.7)   # ceil - потолок"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "8"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "math.floor(8.7)  # floor - пол"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">А еще из модуля <strong>math</strong> можно импортировать константы <strong>π</strong>, <strong>e</strong> и экспоненциальную функцию <strong>exp()</strong>:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import pi, exp, e   # можно сразу несколько - перечислить через запятую"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.141592653589793"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "pi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.718281828459045"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "e"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function math.exp(x, /)>"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "exp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "2.718281828459045"
      ]
     },
     "execution_count": 26,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "exp(1)   # e = e^1 = exp(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Примечание: если мы знаем, что будем использовать практически все функции из модуля <strong>math</strong>, их можно извлечь все сразу, и тогда прописывать название библиотеки нам не понадобится нигде:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "from math import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Однако в общем случае так делать нежелательно, потому что это нерационально и увеличивает время исполнения кода (Python подгружает все функции, а мы пользуемся только двумя, например).</div>\n",
    "<div style=\"text-indent:30px; text-align:justify\">Также мы можем столкнуться с еще одной неприятностью. Например, мы используем свою переменную, имя которой совпадает с именем константы или функции из модуля:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "12345"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "gamma = 12345\n",
    "gamma"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<function math.gamma(x, /)>"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from math import *\n",
    "gamma"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Рассмотрим еще один интересный момент, связанный с вычислениями в Python:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "4.1513310942010236e-32"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1 / 18 ** 25"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Результат выше это <a href=\"https://ru.wikipedia.org/wiki/%D0%A7%D0%B8%D1%81%D0%BB%D0%BE_%D1%81_%D0%BF%D0%BB%D0%B0%D0%B2%D0%B0%D1%8E%D1%89%D0%B5%D0%B9_%D0%B7%D0%B0%D0%BF%D1%8F%D1%82%D0%BE%D0%B9\"><strong>число с плавающей точкой</strong></a>, то есть компьютерная форма экспоненциальной записи числа. Возможно, тот, кто считал что-то на научных или инженерных калькуляторах, уже сталкивался с такой записью. Здесь <strong>e-32</strong> – это <strong>10<sup>−32</sup></strong>, а вся запись означает <strong>4.1513310942010236&bull;10<sup>−32</sup></strong>, то есть примерно <strong>4.15&bull;10<sup>−32</sup></strong>.</div>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify\">Теоретически, если число было очень большим, после <strong>e</strong> стояла бы положительная степень. Но в Python такое не случается, обычно он выводит огромные числа, просто переходя на новую строку, если места на одной не хватает.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1179860169468393696094850428398574326812951635768632922638247087305169015296897617090552227029728639332790976165833425012873149029569699243476515762146016403288859933975483731219169926506009362673657387238695354440796670371519895159054179885491366910550124753230630656795784813304948275683081727373233853822010494533842659031456932120263703593279055881044608336618479280113137341318187829384933999323035259811785124498715761011415678013143401952409490509789109658195124702004920241991962260580648931584784740866102626676425599544913867187349914307227741835534044125794437572270180201766008780256272679995970685845474461023887843627618537419795424357371662835493400389096889848144392669284697565958297091399784816195776935986604336499743558218049"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "33 ** 490"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Компьютерная форма записи числа отчасти помогает понять, почему дробные числа называются числами с плавающей точкой (<strong>float</strong>). </div>\n",
    "    \n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Возьмем число попроще, например, <strong>12.34</strong>.\n",
    "<div style=\"text-indent:30px; text-align:justify\">Его можно записать как <strong>12.34</strong>, как <strong>1.234&bull;10</strong>, как <strong>123.4&bull;10<sup>−1</sup></strong>, <strong>1234&bull;10<sup>−2</sup></strong> и так далее. Точка, отделяющая дробную часть от целой, будет «плавать», однако само число при этом меняться не будет, будут меняться только множители – разные степени десятки.</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"text-align:center; margin-top:40px\">Переменные в Python — это указатели (ссылки)</h3>\n",
    "    \n",
    "<div style=\"text-indent:30px; text-align:justify\">Переменная в Python является лишь ссылкой на объект в памяти. При создании любой переменной (число, строка или массив) в нее записывается ссылка на объект, а сам объект находится где-то в оперативной памяти далеко от самой переменной со ссылкой. Таким образом, несколько переменных могут указывать на один объект, и при изменении объекта (например, списка) изменится результат обращения к нему с использованием каждой переменной.</div>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify\">Все объекты в Python имеют свой уникальный идентификатор (номер объекта). Идентификатор присваивается объекту при его создании. Идентификатор является адресом памяти объекта и будет отличаться при каждом запуске программы. </div>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify; margin-top:20px\">Чтобы получить уникальный идентификатор объекта в программе используется функция <strong>id(object)</strong>:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(4, 5)"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 4\n",
    "b = 5\n",
    "a, b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(140725525555736, 140725525555768)"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "id(a), id(b)  # Посмотрим идентификаторы переменных a и b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(5, 5)"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = b\n",
    "a, b"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(140725525555768, 140725525555768)"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "id(a), id(b)  # Посмотрим идентификаторы переменных a и b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Теперь переменные <strong>a</strong> и <strong>b</strong> ссылаются на один и тот же объект:</div>\n",
    "\n",
    "<div style=\"text-align:center\"><img src=\"id.png\" width=\"400\"></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1 style=\"text-align:center; margin-top:60px\">Типы данных в Python</h1>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify\">Типом данных называют большое количество значений и комплекс операций, которые можно использовать на этих значениях. В языке программирования Python к ним относятся числа, строки, списки, словари, кортежи, множества и логический тип данных. Типы данных в Python можно разделить на:</div>\n",
    "<div style=\" margin-left:50px\">\n",
    "<li style=\"text-align:justify\">изменяемые (множества, списки, словари);</li>\n",
    "<li style=\"text-align:justify\">неизменяемые (кортежи, строки, числа);</li>\n",
    "<li style=\"text-align:justify\">упорядоченные (списки, строки, кортежи, словари);</li>\n",
    "<li style=\"text-align:justify\">неупорядоченные (множества).</li>\n",
    "</div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-align:center\"><img src=\"data_types.png\"></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\"><strong>Последовательности</strong> – упорядоченные коллекции элементов. В последовательностях каждый элемент имеет свою позицию (номер, индекс) в соответствии с которой элемент сохраняется и извлекается из последовательности.</div>  \n",
    "<div style=\"text-indent:30px; text-align:justify\">Элементы <strong>отображений</strong> являются соответствиями одних данных другим. Первые при этом называют ключами, вторые – значениями. </div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2 style=\"text-align:center; margin-top:60px\">Строки (<strong>str</strong>)</h2>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python3'"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = \"Python3\"\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Python3\n"
     ]
    }
   ],
   "source": [
    "print(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "str"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "type(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python3Python3'"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s += s\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Трагедия Пушкина «Моцарт и Сальери» занимает всего десять страниц. О чем она? \\nО зависти или о том, что «гений и злодейство — две вещи несовместные»? \\nЕсть ли оправдание Сальери, который, по версии Пушкина, отравил Моцарта?'"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Тройные кавычки позволяют создавать многострочные строки \n",
    "txt = '''Трагедия Пушкина «Моцарт и Сальери» занимает всего десять страниц. О чем она? \n",
    "О зависти или о том, что «гений и злодейство — две вещи несовместные»? \n",
    "Есть ли оправдание Сальери, который, по версии Пушкина, отравил Моцарта?'''\n",
    "txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Трагедия Пушкина «Моцарт и Сальери» занимает всего десять страниц. О чем она? \n",
      "О зависти или о том, что «гений и злодейство — две вещи несовместные»? \n",
      "Есть ли оправдание Сальери, который, по версии Пушкина, отравил Моцарта?\n"
     ]
    }
   ],
   "source": [
    "print(txt)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'a'"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s = 'a'\n",
    "s"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Самарский университет\n"
     ]
    }
   ],
   "source": [
    "SSS = \"Самарский университет\"\n",
    "print(SSS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid syntax (228149484.py, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  Cell \u001b[1;32mIn[44], line 1\u001b[1;36m\u001b[0m\n\u001b[1;33m    SSS = \"\"Самарский университет\"\"\u001b[0m\n\u001b[1;37m            ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n"
     ]
    }
   ],
   "source": [
    "SSS = \"\"Самарский университет\"\"\n",
    "print(SSS)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Самарский университет\n"
     ]
    }
   ],
   "source": [
    "SSS = \"\"\"Самарский университет\"\"\"\n",
    "print(SSS)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"text-align:center; margin-top:20px\">Обращение по индексу</h3>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-align:center\"><img src=\"positive-and-negative-indexing.jpg\"></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Чтобы обратиться к элементу по индексу используют запись <strong>имя_последовательности[индекс]</strong> </div> \n",
    "<div style=\"text-indent:30px; text-align:justify\">Индексация в Python начинается с <strong>0</strong>. Также можно использовать обратную индексацию - номер последнего элемента имеет индекс <strong>-1</strong>.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 46,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = 'Python'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'P'"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'n'"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[-1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'n'"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[5]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'h'"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[3]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"text-align:center; margin-top:20px\">Срезы</h3>\n",
    "\n",
    "<div style=\"text-indent:30px; text-align:justify\">Операция взятия среза: <strong>имя_последовательности[</strong>начало<strong>:</strong>конец <i>(не включается)</i><strong>:</strong>шаг<strong>]</strong>.</div>  \n",
    "<div style=\"text-indent:30px; text-align:justify\">Если начало не указано - используется 0; если не указан конец, то берется конец строки; если не указан шаг, используется шаг равный 1.</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "metadata": {},
   "outputs": [],
   "source": [
    "s = 'Python'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Pyth'"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[:4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'on'"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[4:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'yth'"
      ]
     },
     "execution_count": 54,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[1:4]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Pto'"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[::2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Python'"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "s[:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'string'"
      ]
     },
     "execution_count": 57,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'str' + 'ing' # конкатенация (склеивание)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'PyPyPy'"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "'Py'*3 # повторение"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 59,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"Py\" in \"Python\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 60,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\"2\" not in 'Python'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Строки - неизменяемый тип данных!</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'str' object does not support item assignment",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "Cell \u001b[1;32mIn[1], line 2\u001b[0m\n\u001b[0;32m      1\u001b[0m a \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mПривет\u001b[39m\u001b[38;5;124m'\u001b[39m\n\u001b[1;32m----> 2\u001b[0m a[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m] \u001b[38;5;241m=\u001b[39m \u001b[38;5;124m'\u001b[39m\u001b[38;5;124mд\u001b[39m\u001b[38;5;124m'\u001b[39m\n",
      "\u001b[1;31mTypeError\u001b[0m: 'str' object does not support item assignment"
     ]
    }
   ],
   "source": [
    "a = 'Привет'\n",
    "a[-1] = 'д' # Строки - неизменяемый тип данных!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Привед'"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = a[0:-1] + 'д'\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'Приветики'"
      ]
     },
     "execution_count": 63,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 'Приветики'\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'УнИВер'"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "txt = \"Универ\"\n",
    "txt = txt[:2] + \"ИВ\" + txt[4:]\n",
    "txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-indent:30px; text-align:justify\">Для преобразования объектов других типов в строки используется функция <strong>str()</strong>:</div>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8765.56 8765.56\n",
      "<class 'float'> <class 'str'>\n"
     ]
    }
   ],
   "source": [
    "s1 = 8765.56\n",
    "s2 = str(s1)\n",
    "print(s1, s2)\n",
    "print(type(s1), type(s2))"
   ]
  }
 ],
 "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
}
