{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Программирование на Python\n", "\n", "*Алла Тамбовцева, НИУ ВШЭ*\n", "\n", "*Данный ноутбук основан на [лекции](http://nbviewer.math-hse.info/github/ischurov/pythonhse/blob/master/Lecture%203.ipynb#%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B0-%D1%83%D1%81%D0%BB%D0%BE%D0%B2%D0%B8%D0%B9) Щурова И.В., курс «Программирование на языке Python для сбора и анализа данных» (НИУ ВШЭ).*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Проверка условий" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Начнем с известных всем операторов. Проверим, \n", "\n", "* правда ли, что 8 меньше 9; \n", "* правда ли, что 9 больше 10." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8 < 9 # правда" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "9 > 10 # неправда" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Результат такой проверки имеет логический тип (*boolean*). " ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "res = 8 < 9\n", "res" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Как мы уже обсуждали, переменные такого типа могут принимать два значения `True` или `False`. Обратите внимание, что `True` и `False` не заключены в кавычки – добавив кавычки, мы получим строки \"True\" и \"False\" (тип *string*)." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"True\" == True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "При проверке равенства двух частей (переменных, списков и так далее) используется двойной знак равенства." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "6 == 6" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Одинарный знак «равно» используется для присваивания значений. Так ничего не сравним, но сохраним в переменную `a` число 6:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 6 \n", "a " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "А так уже проверим условия:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n" ] } ], "source": [ "print(a == 6) \n", "print(a == 9) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Отрицание равенства в Python обозначается с помощью оператора `!=` (вообще `!` в программировании используется для отрицания). " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "6 != 7" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Стоит отметить, что Python достаточно лояльно относится к разделению между типам данных. Например, если мы сравним целое число и то же число, но с плавающей точкой (с дробной частью равной 0), Python сообщит, что эти числа совпадают." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "6 == 6.0 # верно" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Сложные условия" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Пусть у нас есть три целочисленные переменные `a`, `b` и `c`, и мы планируем составлять сложные, составные уcловия, касающиеся этих переменных." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "a = 3\n", "b = 7\n", "c = 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Помогут операторы `and` и `or`. Оператор `and` соответствует одновременному выполнению условий, оператор `or` соответствует ситуации, когда хотя бы одно из условий выполняется. Оператор `or` в Python – обычное «или», не исключающее: либо верно первое условие, либо второе, либо оба." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a < b) and (b > c) # оба верны" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a < b) and (c > b) # второе неверно -> все неверно" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Вместо `and` можно использовать оператор `&`, он нам потом ещё пригодится при работе с датафреймами `pandas`:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a < b) & (c > b)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a < b) or (a > c) # первое верное -> хотя бы одно верно" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Вместо `or` можно использовать оператор `|`:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(a < b) | (a > c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Кроме `and` и `or` в Python есть еще полезные операторы: оператор принадлежности `in` и оператор отрицания `not`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Пусть у нас есть списки отличных, хороших, удовлетворительных и плохих оценок." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "excel = [8, 9, 10]\n", "good = [6, 7]\n", "sat = [4, 5]\n", "bad = [1, 2, 3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Проверим, лежит ли оценка 8 в плохих:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8 in bad" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Применим отрицание:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8 not in bad # верно!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Тут главное не увлечься и не начать писать грамматические фразы вида `8 is not in bad` :) Хотя оператор `is` в Python есть и его часто используют, если нужно сравнить какое-то значение с `None` или проверить тип объекта:" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8 is None # нет\n", "None is None # да" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# тип integer или нет\n", "a = 3\n", "type(a) is int" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# главное, кавычки не ставить вокруг типа\n", "type(a) is 'int'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "А вот это уже too much, хотя красиво и как в естественном языке:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m 8 is not in bad\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "8 is not in bad" ] } ], "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 }