{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 4 Conditionals - flow-control structures\n", "\"Open\n", "\n", "- http://openbookproject.net/thinkcs/python/english3e/conditionals.html\n", "\n", "## Topics\n", "- conditional statements and types\n", "- comparision operators\n", "- Truth tables\n", "\n", "## 4.1 Conditional/Logical Structures\n", "- conditional statements control the flow of execution of codes\n", " - makes some block of code to skip or execute based on some conditions\n", " - loosely speaking, it helps computer think and make decision\n", "- boolean values - True or False\n", "- boolean expressions - comparison operators are used to compare values that result in True or False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.2 Comparison operators\n", "- allow us to compare data values resulting in True or False outcome\n", "- these are binary operators; take two operands where left hand side is compared with right hand side\n", "- **==** (equal to)\n", "- **!=** (not equal to)\n", "- **>** (greater than)\n", "- **>=** (greater than or equal to)\n", "- **<** (less than)\n", "- **<=** (less than or equal to)\n", "- comparison operators are used to create conditional statements" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Examples of various comparison operators\n", "x = 5\n", "y = 10" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# is x equal to y? True or False?\n", "x == y" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# is x not equal to y? True of False?\n", "x != y" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# is x is greater than y? True or False?\n", "x > y" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# is x less than y?\n", "x < y" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# is x less than or equal to y?\n", "x <= y" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# is x greater than or equal to y\n", "x >= y" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.3 Conditional execution\n", "- execute or skip a block of code when some condition is met\n", "- conditional statments are created using keyword **if (condition) **\n", "- three types of conditional selectors\n", "- One-way, Two-way and Multi-way selectors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.4 One-way selector\n", "- just an if statement by itself\n", "- syntax:\n", "```python\n", "if == True:\n", " # execute this block of code\n", "```\n", "- boolean expression can also comapre to False; the ultimate comparison result has to be True!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [Visualize in PythonTutor.com](http://pythontutor.com/visualize.html#code=a%20%3D%20'apple'%0Aif%20a%20%3D%3D%20'apple'%3A%0A%20%20%20%20print%28'var%20a%20equals%20to%20apple'%29%0Aprint%28'continue%20execution%20here...'%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello, there!\n" ] } ], "source": [ "if True:\n", " print('Hello, there!')" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value of a equals to apple\n", "continue execution here...\n" ] } ], "source": [ "a = 'apple'\n", "if a == 'apple': # this should evaluate True\n", " print('value of a equals to apple')\n", "print('continue execution here...')" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "continue execution here...\n" ] } ], "source": [ "a = 'apple'\n", "if a == 'Apple': # this should evaluate False\n", " print('value of a equal to Apple') # this block will NOT be executed!\n", "print('continue execution here...')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.5 Two-way selector\n", "- if statement followed by else statement\n", "- syntax:\n", "\n", "```python\n", "if == True:\n", " # execute this block of code\n", "else:\n", " # otherwise, execute this\n", " \n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [Visualize in PythonTutor.com](http://pythontutor.com/visualize.html#code=num1%20%3D%20100.5%0Anum2%20%3D%20100.49999999999999%0A%0Aif%20%20num1%20%3E%20num2%3A%0A%20%20%20%20print%28'%7B%7D%20is%20greater%20than%20%7B%7D'.format%28num1,%20num2%29%29%0Aelse%3A%0A%20%20%20%20print%28'%7B%7D%20is%20NOT%20greater%20than%20%7B%7D'.format%28num1,%20num2%29%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "100.5 is greater than 100.49999999999999\n" ] } ], "source": [ "num1 = 100.5\n", "num2 = 100.49999999999999\n", "\n", "if num1 > num2:\n", " print('{} is greater than {}'.format(num1, num2))\n", "else:\n", " print('{} is NOT greater than {}'.format(num1, num2))" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "print 10 is NOT greater than or equal to 20\n" ] } ], "source": [ "if 10 >= 20:\n", " print ('print 10 is greater than or equal to 20')\n", "else:\n", " print ('print 10 is NOT greater than or equal to 20')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.6 Multi-way selector\n", "- similar to multiple-choice questions with only one valid answer\n", "- start from first **if statement**, if a **conditional expression** is evaluated True, the rest **elif** and **else** are ignored\n", "\n", "```python\n", "if : \n", " # block1\n", " # execute this...\n", "elif :\n", " # block2 \n", " # execute this\n", "... \n", "... \n", "else: \n", " # if all the previous conditions are evaluated False; this is the alternative!\n", " # else block\n", " # execute code in this block\n", " \n", "```" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a number between 1-5: 2\n", "You entered 2\n" ] } ], "source": [ "# Guess the number entered by user\n", "ans = int(input('Enter a number between 1-5: '))\n", "if ans == 1:\n", " print('You entered 1')\n", "elif ans == 2:\n", " print('You entered 2')\n", "elif ans == 3:\n", " print('You entered 3')\n", "elif ans == 4:\n", " print('You entered 4')\n", "elif ans == 5:\n", " print('You entered 5')\n", "elif ans > 5:\n", " print('You entered a number larger than 5')\n", "else:\n", " print('Hmm.... I do not know what you entered!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [Visualize in PythonTutor.com](https://goo.gl/ZSm9KS)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.7 Logical Operators\n", "**and**, **or**, and **not** -- allow to build more complex boolean expressions
\n", "\n", "**Truth table for and**\n", "\n", "| a | b | a **and** b |\n", "| --- | --- | --- |\n", "| T | T | T |\n", "|T | F | F |\n", "|F | T | F |\n", "|F | F | F |\n", "\n", "\n", "**Truth table for or**\n", "\n", "| a | b | a **or** b |\n", "| --- | --- | --- |\n", "| T | T | T |\n", "|T | F | T |\n", "|F | T | T |\n", "|F | F | F |\n", "\n", "**Truth table for not**\n", "\n", "|a | not a |\n", "|---|---|\n", "|T | F |\n", "|F | T |\n", "\n", "### Order of Evaluations of operators and expressions: \n", "- Highest to Lowest: http://www.informit.com/articles/article.aspx?p=459269&seqNum=11" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 is even and positive\n" ] } ], "source": [ "# and demo\n", "num = 10\n", "if (num%2 == 0 and num > 0):\n", " print(f\"{num} is even and positive\")" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-14 is even and negative\n" ] } ], "source": [ "# and demo\n", "num = -14\n", "if num %2 == 0 and num < 0:\n", " print(f\"{num} is even and negative\")" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "How much money have you saved? 100000\n", "Do you have a farrari? [y/yes | n/no]: yes\n", "Congrats!! You can retire now.\n" ] } ], "source": [ "# or demo\n", "# a retimerment calculator\n", "money = int(input('How much money have you saved? '))\n", "ferrari = input('Do you have a farrari? [y/yes | n/no]: ')\n", "if money >= 1000000 or ferrari == 'y' or ferrari == 'yes':\n", " print('Congrats!! You can retire now.')\n", "else:\n", " print('Sorry, keep working!!')" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "# not example\n", "if not False:\n", " print('True')" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "How much money have you saved? 10\n", "Do you have a farrari? [y/yes | n/no]: y\n", "Congrats!! You can retire now.\n" ] } ], "source": [ "# not demo\n", "# a retimerment calculator\n", "money = int(input('How much money have you saved? '))\n", "ferrari = input('Do you have a farrari? [y/yes | n/no]: ')\n", "if not (money >= 1000000 or ferrari == 'y' or ferrari == 'yes'):\n", " print('Sorry, keep working!!')\n", "else:\n", " print('Congrats!! You can retire now.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.8 Nested conditionals\n", "- conditional statements can be nested inside another conditional statements\n", "- syntax:\n", "\n", "```python\n", "if condition:\n", " if condition1:\n", " # do something\n", " else:\n", " # do something else\n", " if condition2:\n", " # do something...\n", "else:\n", " # do this...\n", "\n", "```" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "-100 is even and negative\n", "done\n" ] } ], "source": [ "# program that determines if a given number is even or odd, positive or negative \n", "num = -100\n", "if num == 0:\n", " print(f'{num} is zero!')\n", "elif num%2 == 0:\n", " if num > 0:\n", " print(f\"{num} is even and positive\")\n", " else:\n", " print(f'{num} is even and negative')\n", "else:\n", " if num > 0:\n", " print(f\"{num} is odd and positive\")\n", " else:\n", " print(f'{num} is odd and negative')\n", " \n", "print('done')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### [Visualize in PythonTutor.com](http://pythontutor.com/visualize.html#code=num%20%3D%20-100%0Aif%20num%20%3D%3D%200%3A%0A%20%20%20%20print%28'%7B%7D%20is%20zero!'.format%28num%29%29%0Aelif%20num%252%20%3D%3D%200%3A%0A%20%20%20%20if%20num%20%3E%200%3A%0A%20%20%20%20%20%20%20%20print%28num,%20%22is%20even%20and%20positive%22%29%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print%28num,%20'is%20even%20and%20negative'%29%0Aelse%3A%0A%20%20%20%20if%20num%20%3E%200%3A%0A%20%20%20%20%20%20%20%20print%28num,%20%22is%20odd%20and%20positive%22%29%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print%28num,%20'is%20odd%20and%20negative'%29&cumulative=false&curInstr=0&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4.9 Exercises\n", "Exercise 1: Write a program to test whether a given whole number is even, odd or zero." ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a whole number:1\n", "1 is odd\n" ] } ], "source": [ "x = input('Enter a whole number: ')\n", "x = int(x)\n", "if x == 0:\n", " print(x, 'is zero')\n", "elif x%2 == 0:\n", " print(x, 'is even')\n", "else:\n", " print(x, 'is odd')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 1.1: Rewrite Exercise 1 using a function and write 2 test cases." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def isEvenOddOrZero(num):\n", " if num == 0:\n", " return 'zero'\n", " elif num%2 == 0:\n", " return 'even'\n", " else:\n", " return 'odd'" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "def test():\n", " assert isEvenOddOrZero(10) == 'even'\n", " assert isEvenOddOrZero(0) == 'zero'\n", " assert isEvenOddOrZero(19) == 'odd'\n", " print('all test cases passed...')" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "all test cases passed...\n" ] } ], "source": [ "test()" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Exercise 2. Write a function that returns whether the given whole number is positive or negative. Also write at least 2 test cases." ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [], "source": [ "def positiveNegativeOrZero(num):\n", " if num == 0:\n", " return 'zero'\n", " elif num > 0:\n", " return 'positive'\n", " else:\n", " return 'negative'" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "def test_positiveNegativeOrZero():\n", " assert positiveNegativeOrZero(0) == 'zero'\n", " assert positiveNegativeOrZero(100) == 'positive'\n", " assert positiveNegativeOrZero(-99.99) == 'negative'\n", " print('all test cases passed for positiveNegativeOrZero()')" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "all test cases passed for positiveNegativeOrZero()\n" ] } ], "source": [ "test_positiveNegativeOrZero()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 3: Write a program that converts students' grade value (0-100) to corresponding letter grade (A-F) where\n", " ```\n", " 90 and above is A\n", " 80 and above is B\n", " 70 and above is C\n", " 60 and above is B\n", " 59 and below is F\n", " ```\n", " Write test cases to test each outcome." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 4: Write a program that helps someone decide where to go eat lunch depending on amount of money one has in their pocket." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 5: Given a day of week as integer (say 1 for Sunday) write a program that tells whether that day is weekend, or weekday and the actual name of the day." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 6: Write a program that determines whether someone is eligible to vote in the US federal election." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 7: Write a function day_name that converts an integer number 0 to 6 into the name of a day. Assume day 0 is “Sunday”. Once again, return None if the argument to the function is not valid." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "def day_name(day):\n", " pass" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# Here are some tests that should pass\n", "def test_day_name():\n", " assert day_name(3) == \"Wednesday\"\n", " assert day_name(6) == \"Saturday\"\n", " assert day_name(42) == None\n", " print('all test cases passed for day_name()')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "ename": "AssertionError", "evalue": "", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtest_day_name\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mtest_day_name\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mtest_day_name\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32massert\u001b[0m \u001b[0mday_name\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"Wednesday\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 3\u001b[0m \u001b[0;32massert\u001b[0m \u001b[0mday_name\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m6\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;34m\"Saturday\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;32massert\u001b[0m \u001b[0mday_name\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m42\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;32mNone\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'all test cases passed for day_name()'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mAssertionError\u001b[0m: " ] } ], "source": [ "test_day_name()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Exercise 8: Write a function that helps answer questions like ‘“Today is Wednesday. I leave on holiday in 19 days time. What day will that be?”’ So the function must take a day name and a delta argument (the number of days to add) and should return the resulting day name.s" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "def day_add(dayName, delta):\n", " pass" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "# Here are some tests that should pass\n", "def test_day_add():\n", " assert day_add(\"Monday\", 4) == \"Friday\"\n", " assert day_add(\"Tuesday\", 0) == \"Tuesday\"\n", " assert day_add(\"Tuesday\", 14) == \"Tuesday\"\n", " assert day_add(\"Sunday\", 100) == \"Tuesday\"\n", " assert day_add(\"Sunday\", -1) == \"Saturday\"\n", " assert day_add(\"Sunday\", -7) == \"Sunday\"\n", " assert day_add(\"Tuesday\", -100) == \"Sunday\"\n", " print('all test cases passed for day_add()')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "test_day_add()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Kattis problems\n", "- almost every problem involve some form of conditional statements" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.3" } }, "nbformat": 4, "nbformat_minor": 2 }