{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Conditionals" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Logical Operators\n", "Logical operators are ways of combining booleans.\n", "Recall that boolean is either `True` or `False`.\n", "We can combine two booleans through the use of one\n", "of 3 logical operators:\n", "* `and` - True if both operands are `True`\n", "* `or` - True if at least one of the operands are `True`\n", "* `not` - True if the operand is `False`\n", "\n", "### Examples\n", "Let's look at a few examples. Note that for operators with\n", "2 operands, the order of the operands does not matter.\n", "\n", "#### Examples: `and` " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tvar1 = True\n", "tvar2 = True\n", "fvar1 = False\n", "fvar2 = False\n", "\n", "print(tvar1 and tvar2)\n", "print(tvar1 and fvar1)\n", "print(fvar1 and tvar1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Examples: `or` " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(tvar1 or tvar2)\n", "print(tvar1 or fvar2)\n", "print(fvar1 or fvar2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Examples: `not`" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(not tvar1)\n", "print(not fvar1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Combinations\n", "Like with the numerical operators, we can combine\n", "multiple logical operations together. Like with\n", "the previously discussed operators for numerical types\n", "these operators have a precedence. From highest\n", "precedence to lowest precedence: `not`, `and`, `or`.\n", "\n", "Let's look at a few examples:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(not fvar1 and not fvar2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this example, we see that both of the `not` are applied first,\n", "followed by the `and`.\n", "\n", "Like with numerical operators, we can use parentheses to specify an\n", "order different than the precedence (or simply to make the order more\n", "clear even when it follows the precedence). For example, consider the\n", "two expressions below. Adding the parentheses causes the `not` to be\n", "applied to the result of the entire operation in the parentheses,\n", "changing the result." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(not fvar1 or tvar1 and tvar2)\n", "print(not (fvar1 or tvar1 and tvar2)) # added parentheses" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Boolean Expressions\n", "Logical operators on their own are not that helpful (we haven't\n", "yet created a scenario where we can combine them with other\n", "code aside from simply boolean variables). To make these\n", "useful, we combine them with *boolean expressions*: an expression\n", "that is either true or false. Boolean expressions\n", "involve a comparison between two values using a *comparison operator*: `==`, `!=`, `<`, `>`, `<=`, `>=`, all described in more detail below. The operands could be variables, literal values, or the results of another operation.\n", "\n", "* `val1 == val2` (true when `val1` is equal to `val2`)\n", "* `val1 != val2` (true when `val1` is not equal to `val2`)\n", "* `val1 < val2` (true when `val1` is less than `val2`)\n", "* `val1 <= val2` (true when `val1` is less than or equal to `val2`)\n", "* `val1 > val2` (true when `val1` is greater than `val2`)\n", "* `val1 >= val2` (true when `val1` is greater than or equal to `val2`)\n", "\n", "**Note: equality is tested with two equals signs. Recall that the single `=` is used for assignment statements. It is a extremely common mistake to attempt to use a single equal for comparison -- watch out for it." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 4\n", "y = 8\n", "\n", "print(x == y)\n", "print(x != y)\n", "\n", "print(x < 4)\n", "print(x <= 4)\n", "\n", "print(x > y)\n", "print(y >= 8)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "There's technically one additional comparison operator: `is`. This is different from `==` in that this actually checks if the underlying\n", "objects are in fact the same object (not just equal to one another).\n", "\n", "**Best rule of thumb:** Only use `is` when comparing to `None`.\n", "\n", "As a boolean expression evaluates to a boolean value, they can be\n", "combined with one another through the logical operators discussed\n", "above. For example, consider the following code snippet which\n", "checks if x is both less than 5 and even by combining multiple boolean\n", "expressions with the `and` operator. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(x < 5 and x % 2 == 0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that the precedence of the comparison operators are higher\n", "than that of the logical operators. All of the comparison operators\n", "have the same precedence and are evaluated left-to-right.\n", "\n", "## Conditionals\n", "Having built up the idea of boolean expressions based on comparison operators and logical operators, the natural question is, in what ways\n", "would we actually end up incorporating these into our code?\n", "\n", "Typically, we would use these as conditions that we \"check\", and\n", "change what happens based on the result. For instance at an amusement\n", "park, they may check whether the rider is greater than 48 inches tall.\n", "If so, the rider is allowed to ride. If they are not, the rider cannot\n", "go on the ride. Similarly, in the case of schools, the idea of\n", "prerequisites is another check, and whether or not you are allowed to register for a class depends on whether you meet the prerequisite. These are both examples of conditionals, where what happens changes based on the result of checking some condition.\n", "\n", "The same idea occurs in code: we can change what code executes by checking the result of a condition. These \"checks\" are known as conditional statements and are done through `if`, `elif`, and `else` statements and code blocks associated with each. The general form of these conditionals is shown below:\n", "\n", "\"diagram\n", "\n", "\n", "### Examples\n", "Let's start with a simple example of just an `if` statement to print\n", "\"even\" if `x` is even." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 6\n", "\n", "if x % 2 == 0:\n", " print(\"even\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We could modify the above to print \"odd\"\n", "if it is not even (instead of just doing nothing)\n", "by adding an \"else\" block. Note that the `else` block\n", "only executes if the `if` condition does not\n", "evaluate to `True`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 5\n", "\n", "if x % 2 == 0:\n", " print(\"even\")\n", "else:\n", " print(\"odd\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's look at a slightly more complex example. Suppose\n", "we wish to write a function that checks prints out\n", "a message of congratulations based on who wins\n", "a football game. A game can end in one of\n", "three ways:\n", "\n", "1. TeamA wins\n", "2. TeamB wins\n", "3. They tie" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def congrats(scoreA, scoreB):\n", " if scoreA > scoreB:\n", " print(\"Congrats Team A\")\n", " elif scoreA < scoreB:\n", " print(\"Congrats Team B\")\n", " else:\n", " print(\"Team A and Team B tied :(\")\n", "\n", "congrats(24,27)\n", "congrats(18,18)\n", "congrats(21, 18)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Nested Conditionals\n", "The best way to think of these different programming\n", "constructs covered so far are as building blocks.\n", "They can be combined with one another, and when doing\n", "so is when we start to see more powerful programs.\n", "\n", "Much like we can nest conditionals in a function,\n", "it's also possible to nest conditionals within each\n", "other. To see this, let's consider the example\n", "of a leap year. A leap year is a one where\n", "year is evenly divisible by 4, but not by 100 unless\n", "it is also divisible by 400.\n", "\n", "Let's look at the code to check and print a message if the\n", "desired year is a leap year." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "year = 2000\n", "\n", "if year % 4 == 0:\n", " if year % 100 != 0:\n", " print(year, \"is a leap year\")\n", " else:\n", " if year % 400 == 0:\n", " print(year, \"is a leap year\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Short-Circuiting\n", "Earlier, we said the order of the operands for logical\n", "expressions does not matter. While a true statement,\n", "when combining logical expressions with boolean statements,\n", "the order can be important. Consider the following code:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 6\n", "y = 0\n", "print(x/y > 2 and y > 0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This code gives us a divide by 0 error, because working left-to-right,\n", "`x/y > 2` attempts to divide by 0. Notice though that the second half,\n", "`y > 0`,\n", "is false, so there was really no point in even attempting to divide\n", "because the whole expression was then guaranteed to be false.\n", "\n", "Let's see what happens if we switch the order:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(y > 0 and x/y > 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that this time the result was `False`, even though `x/y` is still\n", "dividing by 0. This is called *short-circuiting* the evaluation.\n", "Python knows when there is no reason to continue\n", "evaluating, so it stops (without executing the\n", "remaining portion of the expression). The technique above, where\n", "a particular boolean expression is added before potentially problematic\n", "evaluations is known adding a *guard evaluation*. This is a very common\n", "way to take advantage of *short-circuiting* to avoid an error." ] } ], "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.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }