{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Tutorial A6 – Solutions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__1__ Below you can find the implementation of a \"question-answer\"-game, in which the player is asked to evaluate boolean statements with comparison operators. For each right answer you get a point. Do not worry, if you do not understand the implementation! We will cover the elements that we do not know yet in the coming exercises. Execute the code cell in a Jupyter notebook to play the game. __a)__ The program prints the Player's total points after 10 rounds to the screen (at the very end of the code). Add a set of if-else statements to additionally print a message commenting the number of points. __Advanced b)__ Try to read through the implementation and identify the code block within the `doComparison` function definition where comparisons are choosen via a set of if-else statements. Comment the lines of this block in the code cell." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3 == 8\n", "True or False: \n", "Wrong!\n", "\n", "10 != 8\n", "True or False: \n", "Wrong!\n", "\n", "2 == 7\n", "True or False: \n", "Wrong!\n", "\n", "1 < 7\n", "True or False: \n", "Wrong!\n", "\n", "10 > 6\n", "True or False: \n", "Wrong!\n", "\n", "8 == 1\n", "True or False: \n", "Wrong!\n", "\n", "5 < 10\n", "True or False: \n", "Wrong!\n", "\n", "8 < 2\n", "True or False: \n", "Wrong!\n", "\n", "9 != 2\n", "True or False: \n", "Wrong!\n", "\n", "5 <= 2\n", "True or False: \n", "Wrong!\n", "\n", "--------------------------------------------------------------------------------\n", "You have 0 out of 10 points.\n" ] } ], "source": [ "#\n", "# Game: True or False\n", "#\n", "# The computer writes a statement to screen.\n", "# The user rates it as true or false.\n", "# The game has 10 rounds. For every correct answer the user gets a point.\n", "#\n", "\n", "import random \n", "# Random number generator (will be treated in a later exercise)\n", "\n", "#-----------------------------------------------------------------------\n", "\n", "def doComparison(i, a, b):\n", " \"\"\"Generate a comparison\n", " \n", " Compares two integers a and b using one of six comparison operators.\n", " The comparison operator is determined by the index i:\n", " \n", " 0: `==`\n", " 1: `!=`\n", " 2: `>=`\n", " 3: `<=`\n", " 4: `>`\n", " 5: `<`\n", "\n", " Args:\n", " i (int): index linked to a comparison operator\n", " a (int): first number\n", " b (int): second number\n", "\n", " Raises:\n", " AssertionError: Arguments `i`, `a`, and `b` must be of type `int`\n", " AssertionError: Index `i` must be in range(6)\n", "\n", " Returns:\n", " True or False\n", " \"\"\"\n", " \n", " # Arguments need to be of type `int` \n", " assert isinstance(i, int)\n", " assert isinstance(a, int)\n", " assert isinstance(b, int)\n", " \n", " if i == 0: \n", " return a == b\n", " elif i == 1:\n", " return a != b\n", " elif i == 2:\n", " return a >= b\n", " elif i == 3:\n", " return a <= b\n", " elif i == 4:\n", " return a > b\n", " elif i == 5:\n", " return a < b \n", " else: \n", " raise AssertionError(\n", " \"Index `i` must be in range(6)\"\n", " ) \n", " \n", "#-----------------------------------------------------------------------\n", "\n", "# List of comparison operators\n", "operators = [\"==\", \"!=\", \">=\", \"<=\", \">\", \"<\"]\n", "\n", "# Counter for the number of correct answers\n", "points = 0\n", "\n", "for run in range(10):\n", " # Pick two random numbers between 1 and 10 \n", " a = random.randint(1, 10)\n", " b = random.randint(1, 10)\n", "\n", " # Pick a random number that determines the comparison operator\n", " i = random.randint(0, 5)\n", "\n", " # Print the comparison to screen \n", " print(str(a) + \" \" + operators[i] + \" \" + str(b))\n", "\n", " # Ask whether the statement is true or false\n", " user_input = input(\"True or False: \")\n", "\n", " #****************************************\n", " # __b)__ This block should be commented #\n", " #****************************************\n", " \n", " result = doComparison(i, a, b)\n", " if user_input == \"True\" and result == True: \n", " print(\"Correct!\")\n", " points += 1\n", " elif user_input == \"False\" and result == False: \n", " print(\"Correct!\")\n", " points += 1 \n", " else: \n", " print(\"Wrong!\")\n", "\n", " print(\"\")\n", "\n", "#**************************************************\n", "# __a)__ Write a code block that rates the result # \n", "# 0-3 points -> Not so good #\n", "# 4-6 points -> You'll get there if you practice #\n", "# 7-9 points -> Well done! #\n", "# 10 points -> Boolean master #\n", "#**************************************************\n", "print(\"-\" * 80)\n", "print(\"You have \" + str(points) + \" out of 10 points.\") \n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function doComparison in module __main__:\n", "\n", "doComparison(i, a, b)\n", " Generate a comparison\n", " \n", " Compares two integers a and b using one of six comparison operators.\n", " The comparison operator is determined by the index i:\n", " \n", " 0: `==`\n", " 1: `!=`\n", " 2: `>=`\n", " 3: `<=`\n", " 4: `>`\n", " 5: `<`\n", " \n", " Args:\n", " i (int): index linked to a comparison operator\n", " a (int): first number\n", " b (int): second number\n", " \n", " Raises:\n", " AssertionError: Arguments `i`, `a`, and `b` must be of type `int`\n", " AssertionError: Index `i` must be in range(6)\n", " \n", " Returns:\n", " True or False\n", "\n" ] } ], "source": [ "help(doComparison)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__2__ Below you find the implementation of another game, in which the Player needs to find a secret number. Again don't worry about the parts of the implementation you may not understand already. Execute the code cell to play the game __Advanced b)__ Try to read through the implementation and identify the code block where comparisons are choosen via a set of if-else statements. Comment the lines of this block in the code cell." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Make statements of the form: a == 7 or a >= 5.\n", "Your statement a == 0\n", "False\n", "Your statement a == 1\n", "False\n", "Your statement a == 2\n", "True\n", "\n", "You won!\n", "The number is 2.\n" ] } ], "source": [ "#\n", "# Game: guess the number\n", "#\n", "# The program picks a random integer in the interval [0, maxNum].\n", "# The user tries to guess the number by making statements about the\n", "# number.\n", "# The program replies True or False.\n", "# If the user makes maxCount false statements, the computer wins. \n", "# If the user guesses the number correctly before making maxCount false\n", "# statements, the user wins.\n", "#\n", "\n", "import random\n", "\n", "\n", "# Largest number that can be picked\n", "maxNum = 10\n", "\n", "# Number of wrong guesses\n", "maxCount = 3\n", "\n", "#-----------------------------------------------------------------------\n", "\n", "# Pick a random integer between 1 and maxNum\n", "a = random.randint(1, maxNum)\n", "\n", "# Boolean that states whether number has been guessed already\n", "guessed_number = False\n", "\n", "# Counts the number of wrong guesses\n", "count = 0\n", "\n", "# Instruction to the user \n", "print(\"Make statements of the form: a == 7 or a >= 5.\")\n", "\n", "while (count < maxCount) and (guessed_number == False):\n", " # read in the statement\n", " statement = input(\"Your statement \")\n", " \n", " try:\n", " # Extract the comparison operator\n", " comparator = statement.split()[1]\n", " # and the number\n", " number = int(statement.split()[2]) \n", " except (IndexError, ValueError):\n", " # IndexError: Indexing the list returned by `.split()` fails.\n", " # ValueError: Conversion to int fails\n", " print(\"Input formatted incorrectly.\")\n", " continue\n", " \n", " #****************************************\n", " # __b)__ This block should be commented # \n", " #****************************************\n", " if comparator == \"==\" and a == number: \n", " print(\"True\")\n", " guessed_number = True\n", " elif comparator == \"!=\" and a != number:\n", " print(\"True\") \n", " elif comparator == \">=\" and a >= number:\n", " print(\"True\") \n", " elif comparator == \"<=\" and a <= number:\n", " print(\"True\") \n", " elif comparator == \"<\" and a < number:\n", " print(\"True\") \n", " elif comparator == \">\" and a > number:\n", " print(\"True\")\n", " else: \n", " print(\"False\")\n", " count += 1\n", " \n", "if count < 3:\n", " print(\"\")\n", " print(\"You won!\")\n", "else: \n", " print(\"\")\n", " print(\"You lost!\")\n", " \n", "print(\"The number is \" + str(a) + \".\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__3__ What is the outcome of theses statements? Why is this?" ] }, { "cell_type": "markdown", "metadata": { "run_control": { "marked": true } }, "source": [ " - `10 == \"10\"`" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "10 == \"10\" # A number is not a string" ] }, { "cell_type": "markdown", "metadata": { "run_control": { "marked": true } }, "source": [ " - `bool(\"False\")`" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(\"False\")\n", "# Existing objects (\"False\" is a string) evaluate to True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " - `bool(print(\"x\"))`" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x\n" ] }, { "data": { "text/plain": [ "False" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(print(\"x\"))\n", "# Print displays x and returns None\n", "# None evaluates to False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " - `float(1) == int(1)`" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "float(1) == int(1) # Numerically identical" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " - `float(1) is int(1)`" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "float(1) is int(1) # A float is not an integer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " - `not(True or False)`" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "not(True or False)\n", "# True or False is True\n", "# not True is False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " - `True in {1}`" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "True in {1} # 1 == True" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " - `True > False`" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "True > False # True == 1; False == 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ " - `1 > \"a\"`" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'>' not supported between instances of 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\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[0;36m1\u001b[0m \u001b[0;34m>\u001b[0m \u001b[0;34m\"a\"\u001b[0m \u001b[0;31m# cannot compare apples and oranges\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: '>' not supported between instances of 'int' and 'str'" ] } ], "source": [ "1 > \"a\" # cannot compare apples and oranges" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__4__ __a)__ Write an if-else statement that checks if a variable is an integer and adds 1 to it if it is. Print a message if it is not. Show that this works for both cases." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "i = 1\n", "if isinstance(i, int):\n", " i += 1\n", "else:\n", " print(\"i is not an integer\")\n", " \n", "print(i)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "i is not an integer\n", "1\n" ] } ], "source": [ "i = \"1\"\n", "if isinstance(i, int):\n", " i += 1\n", "else:\n", " print(\"i is not an integer\")\n", " \n", "print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Advanced b)__ Rewrite this as a try-except statement checking if 1 can be added to the variable at all." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "i = 1\n", "try:\n", " i += 1\n", "except TypeError:\n", " print(\"Can not add 1 to i\")\n", "print(i)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Can not add 1 to i\n", "1\n" ] } ], "source": [ "i = \"1\"\n", "try:\n", " i += 1\n", "except TypeError:\n", " print(\"Can not add 1 to i\")\n", "print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Advanced 1__ Can you figure out what this code does? How does the value of `c` effect the outcome." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "c = None\n", "if not c:\n", " c = True\n", "elif c:\n", " c = None\n", "else:\n", " print(\"Never thought I could land here ...\")\n", "if c:\n", " c = not c\n", "elif not c:\n", " c = True\n", " \n", "# print(c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Advanced 2__ Here is something you can wrap you head around. Can you understand what's going on here?" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n" ] } ], "source": [ "a = False\n", "print(a and 2 or 1)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "1\n" ] } ], "source": [ "a = False\n", "print(a and 2) # Returns first False value\n", "print(False or 1) # Returns last value" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "run_control": { "marked": true } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "a = True\n", "print(a and 2 or 1)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "2\n" ] } ], "source": [ "a = True\n", "print(a and 2) # Returns last True value\n", "print(2 or 1) # Returns first True value" ] } ], "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.1" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": {}, "toc_section_display": true, "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 4 }