{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python для сбора и анализа данных\n", "\n", "*Алла Тамбовцева, НИУ ВШЭ*\n", "\n", "## Семинар 1: ввод-вывод и приведение типов\n", "\n", "### Задание 0\n", "\n", "Посчитайте:\n", "\n", "* $\\log(25)$;\n", "* $\\log_{10}(1000)$;\n", "* $\\pi^3$;\n", "* $\\sqrt{459}$." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.2188758248682006\n", "2.9999999999999996\n", "3.0\n", "31.006276680299816\n", "21.42428528562855\n" ] } ], "source": [ "import math\n", "\n", "# 1\n", "print(math.log(25))\n", "\n", "# 2\n", "\n", "print(math.log(1000, 10))\n", "print(math.log10(1000)) # более точный ответ\n", "\n", "# 3\n", "\n", "print(math.pi ** 3)\n", "\n", "# 4\n", "\n", "print(math.sqrt(459))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задание 1\n", "\n", "В переменных `a` и `b` хранятся некоторые числа. Напишите код, который бы менял значения переменных местами. Создавать вспомогательные переменные можно.\n", "\n", "*Пример:*" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# до\n", "a = 2\n", "b = 5" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "5\n" ] } ], "source": [ "# после\n", "print(a)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Решение 1 (классическое):" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "2\n" ] } ], "source": [ "a = 2\n", "b = 5\n", "c = a\n", "a = b\n", "b = c\n", "print(a)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Решение 2 (множественное присваивание в Python):" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "2\n" ] } ], "source": [ "a = 2\n", "b = 5\n", "a, b = b, a\n", "print(a)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задание 3\n", "\n", "Напишите программу, которая запрашивает у пользователя с клавиатуры его рост в сантиметрах, его вес в килограммах (каждый показатель – с новой строки, в новом запросе) и выводит на экран сообщение вида:\n", "\n", " Индекс массы тела: [значение].\n", "\n", "где вместо `[значение]` подставляется посчитанное значение индекса массы тела.\n", "\n", "Индекс массы тела считается так:\n", "\n", "$$\\text{BMI}=\\frac{\\text{m}}{\\text{h}^2},$$\n", "\n", "где $\\text{m}$ – масса тела в килограммах, $\\text{h}$ – рост в метрах." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your height in cm: 168\n", "Enter your weight in kg: 56\n", "Индекс массы тела: 19.841269841269845.\n" ] } ], "source": [ "h = int(input(\"Enter your height in cm: \")) / 100\n", "m = int(input(\"Enter your weight in kg: \"))\n", "\n", "print(f\"Индекс массы тела: {m / h ** 2}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Если захотим округлить результат до второго знака после запятой:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Индекс массы тела: 19.84.\n" ] } ], "source": [ "print(f\"Индекс массы тела: {round(m / h ** 2, 2)}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задание 4\n", "\n", "Выполните задание 3, но вместо обычного запроса с клавиатуры используйте виджеты: \n", "\n", "* поле для ввода целого числа для роста в сантиметрах;\n", "* слайдер с целыми числами от 0 до 250 с шагом 1 для веса.\n", "\n", "Примеры виджетов можно посмотреть [здесь](https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20List.html)." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "69460a1699c4485cbdd65f0f8dc7dc53", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntText(value=1, description='Height')" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ce73b6d850fb4861b1b2766384cb62b5", "version_major": 2, "version_minor": 0 }, "text/plain": [ "IntSlider(value=1, description='Weight', max=250)" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "import ipywidgets as widgets\n", "w1 = widgets.IntText(value = 1, description = \"Height\")\n", "w2 = widgets.IntSlider(value = 1, \n", " min = 0, max = 250, step = 1,\n", " description = \"Weight\")\n", "display(w1)\n", "display(w2)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Индекс массы тела: 19.84.\n" ] } ], "source": [ "h, m = w1.value / 100, w2.value\n", "print(f\"Индекс массы тела: {round(m / h ** 2, 2)}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задание 5\n", "\n", "В Светлогорске, в музее Мирового океана есть прекрасные весы, которые позволяют узнать свой вес, измеренный в селёдках, в китах, в креветках и в других морских обитателях. Напишите код, который запрашивает у пользователя с клавиатуры его вес в килограммах (целое или дробное число) и выводит на экран его вес в селёдках, округленный до целого числа. Считайте, что средний вес селедки равен 350 граммам.\n", "\n", "**Пример исполнения кода:**\n", "\n", "Ввод:\n", "\n", " Enter your weight in kg: 56\n", "Вывод: \n", "\n", " Your weight is 160 herrings." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your weight: 56\n", "Your weight is 160 herrings.\n" ] } ], "source": [ "weight = float(input(\"Enter your weight: \"))\n", "print(f\"Your weight is {round(weight / 0.35)} herrings.\")" ] } ], "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.7.4" } }, "nbformat": 4, "nbformat_minor": 2 }