{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python для сбора и анализа данных\n", "\n", "*Алла Тамбовцева, НИУ ВШЭ*\n", "\n", "## Семинар 3: условные конструкции и цикл `while`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 1\n", "Напишите программу, которая просит пользователя ввести положительное число, и если пользователь вводит положительное число, выводит на экран сообщение \"Молодец!\", если нет – \"Это не положительное число.\".\n", "\n", "Считайте, что пользователь в любом случае вводит числа, а не какой-то текст." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a number: 4\n", "Молодец!\n" ] } ], "source": [ "n = float(input(\"Enter a number: \"))\n", "if n > 0:\n", " print(\"Молодец!\")\n", "else:\n", " print(\"Это не положительное число\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "При желании можно написать более универсальный код, который будет на первом шаге проверять, ввёл ли пользователь строку с числом. Можно сохранить `input()` в переменную и посмотреть на метод `.isnumeric()` или `.isdigit()` для строк (только для целых чисел)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 2\n", "\n", "Пользователь вводит с клавиатуры два числа через пробел. Напишите код, который возвращает максимальное из двух введенных значений. \n", "\n", "**Пример:**\n", "\n", "Ввод: \n", "\n", " Введите два числа: 5.7 8\n", " \n", "Вывод: \n", "\n", " 8" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter two numbers: 5 7\n", "7.0\n" ] } ], "source": [ "# решение 1 – с if-else\n", "\n", "inp = input(\"Enter two numbers: \")\n", "strings = inp.split()\n", "numbers = [float(i) for i in strings]\n", "\n", "if numbers[0] > numbers[1]:\n", " print(numbers[0])\n", "else:\n", " print(numbers[1])" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter two numbers: 5 7.6\n", "7.6\n" ] } ], "source": [ "# решение 2 – без if-else\n", "\n", "inp = input(\"Enter two numbers: \")\n", "strings = inp.split()\n", "numbers = [float(i) for i in strings]\n", "print(max(numbers))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 3\n", "\n", "Дан список `N` из целых чисел. Напишите код, который делает следующее: выводит каждый элемент списка на экран и для каждого элемента либо выводит комментарий \"Это четное число\", либо комментарии \"Это нечетное число\".\n", "\n", "*Подсказка:* оператор для нахождения остатка от деления – это `%`." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3 Это нечетное число\n", "6 Это четное число\n", "7 Это нечетное число\n", "0 Это четное число\n", "1 Это нечетное число\n", "9 Это нечетное число\n" ] } ], "source": [ "N = [3, 6, 7, 0, 1, 9]\n", "\n", "for n in N:\n", " if n % 2 == 0:\n", " print(n, \"Это четное число\")\n", " else:\n", " print(n, \"Это нечетное число\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 4\n", "\n", "У питона есть набор любимых чисел.\n", "\n", " favorites = [3, 7, 11, 23, 18, 48, 81]\n", "\n", "Напишите программу, которая просит пользователя ввести целое число, и если оно нравится питону, на экран будет выводиться сообщение: \"Мое любимое число!\", если нет ‒ \"Эх, ну почему?\"." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Введите число: 5\n", "Эх, ну почему?\n" ] } ], "source": [ "# решение 1 – с оператором in\n", "\n", "favorites = [3, 7, 11, 23, 18, 48, 81]\n", "num = int(input(\"Введите число: \"))\n", "\n", "if num in favorites:\n", " print(\"Мое любимое число!\")\n", "else:\n", " print(\"Эх, ну почему?\")" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Введите число: 23\n", "Мое любимое число!\n" ] } ], "source": [ "# решение 2 – без оператора in\n", "\n", "favorites = [3, 7, 11, 23, 18, 48, 81]\n", "num = int(input(\"Введите число: \"))\n", "\n", "s = 0\n", "\n", "for i in favorites:\n", " if num == i:\n", " s += 1\n", " else:\n", " s += 0\n", " \n", "if s == 1:\n", " print(\"Мое любимое число!\")\n", "else:\n", " print(\"Эх, ну почему?\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Мое любимое число!\n" ] } ], "source": [ "# решение 3 – без in, но с any()\n", "\n", "if any([num == n for n in favorites]):\n", " print(\"Мое любимое число!\")\n", "else:\n", " print(\"Эх, ну почему?\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Дополнение к задачам на ввод чисел – проверка, числовой ли ввод (рассмотрен случай только целых чисел):" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Введите число: 5\n", "Ок\n" ] } ], "source": [ "word = input(\"Введите число: \")\n", "\n", "if word.isdigit():\n", " print(\"Ок\")\n", " z = int(word)\n", "else:\n", " print(\"Введите число!\")\n", " word = input(\"Введите число: \")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Дополнение к строкам: как сделать так, чтобы текст внутри строки исполнялся как «настоящий» код Python:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'print(2 + 4)'" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# просто строка с текстом\n", "\n", "\"print(2 + 4)\"" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n" ] } ], "source": [ "# eval() – запускает код, заключенный в строке\n", "\n", "eval(\"print(2 + 4)\")" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [], "source": [ "# exec() – запускает код, заключенный в строке + \n", "# позволяет таким образом создавать переменные\n", "\n", "exec(\"x1 = 2\")" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "# создаем в цикле переменные x1-x5 вида:\n", "# x1 = \"folder1\" ... x5 = \"folder5\"\n", "\n", "for i in range(1, 6):\n", " s = f\"x{i} = 'folder{i}'\"\n", " exec(s)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "folder1 folder2 folder3 folder4 folder5\n" ] } ], "source": [ "print(x1, x2, x3, x4, x5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Задача 5\n", "Напишите программу, которая запрашивает у пользователя пароль, и далее:\n", "\n", "* если пароль верный, выводит на экран сообщение \"Login success\".\n", "* если пароль неверный, выводит на экран сообщение \"Incorrect password, try again!\" до тех пор, пока пользователь не введет верный пароль." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your password: hse\n", "Incorrect password, try again!\n", "Enter your password: h\n", "Incorrect password, try again!\n", "Enter your password: hsepassword\n", "Login success\n" ] } ], "source": [ "# вариант 1 – классический while\n", "\n", "password = \"hsepassword\"\n", "attempt = input(\"Enter your password: \")\n", "\n", "while attempt != password:\n", " print(\"Incorrect password, try again!\")\n", " attempt = input(\"Enter your password: \")\n", "print(\"Login success\")" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your password: 4\n", "Incorrect password, try again!\n", "Enter your password: 5\n", "Incorrect password, try again!\n", "Enter your password: hse\n", "Incorrect password, try again!\n", "Enter your password: hsepassword\n", "Login success\n" ] } ], "source": [ "# вариант 2 – while True\n", "\n", "password = \"hsepassword\"\n", "attempt = input(\"Enter your password: \")\n", "\n", "while True:\n", " if password == attempt:\n", " break \n", " else:\n", " print(\"Incorrect password, try again!\")\n", " attempt = input(\"Enter your password: \")\n", "print(\"Login success\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Ещё пара решений с ограничением на количество попыток ввода пароля:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your password: р\n", "Enter your password: hsepassword\n", "Login success\n" ] } ], "source": [ "password = \"hsepassword\"\n", "attempt = input(\"Enter your password: \")\n", "\n", "for i in range(0, 2):\n", " if password == attempt:\n", " print(\"Login success\")\n", " break\n", " else:\n", " attempt = input(\"Enter your password: \")" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter your password: t\n", "Incorrect password, try again!\n", "Enter your password: t\n", "Incorrect password, try again!\n", "Enter your password: t\n", "Incorrect password, try again!\n" ] } ], "source": [ "password = \"hsepassword\"\n", "\n", "for i in range(0, 3):\n", " attempt = input(\"Enter your password: \")\n", " if password == attempt:\n", " print(\"Login success\")\n", " break\n", " else:\n", " print(\"Incorrect password, try again!\")" ] } ], "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 }