{"id":5825,"date":"2022-04-09T16:31:22","date_gmt":"2022-04-09T14:31:22","guid":{"rendered":"http:\/\/miro.borodziuk.eu\/?p=5825"},"modified":"2026-01-23T14:58:02","modified_gmt":"2026-01-23T13:58:02","slug":"exceptions-in-python","status":"publish","type":"post","link":"http:\/\/miro.borodziuk.eu\/index.php\/2022\/04\/09\/exceptions-in-python\/","title":{"rendered":"Exceptions in Python"},"content":{"rendered":"<p>1. In Python, there is a distinction between two kinds of errors:<\/p>\n<p><!--more--><\/p>\n<div class=\"small-12 large-6 columns\">\n<ul>\n<li><b>Syntax errors<\/b> (parsing errors), which occur when the parser comes across a statement that is incorrect. For example:<br \/>\nTrying to execute the following line:<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<div class=\"ace_line\">\n<pre class=\"lang:default decode:true\">print(\"Hello, World!)<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<p>will cause a <i>SyntaxError<\/i>, and result in the following (or similar) message being displayed in the console:<\/p>\n<pre class=\"lang:default decode:true\">File \"main.py\", line 1\r\nprint(\"Hello, World!)\r\nSyntaxError: EOL while scanning string literal<\/pre>\n<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<ul>\n<li><b>Exceptions<\/b>, which occur even when a statement\/expression is syntactically correct; these are the errors that are detected during execution when your code results in an error which is not <i>uncoditionally fatal<\/i>.\u00a0 For example:<br \/>\nTrying to execute the following line:<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<div class=\"ace_line\">\n<pre class=\"lang:default decode:true \">print(1\/0)<\/pre>\n<p>will cause a <i>ZeroDivisionError<\/i> exception, and result in the following (or similar) message being displayed in the console:<\/p>\n<\/div>\n<\/div>\n<\/div>\n<pre class=\"lang:default decode:true\">Traceback (most recent call last):\r\n  File \"main.py\", line 1, in\r\n    print(1\/0)\r\nZeroDivisionError: division by zero<\/pre>\n<p>The last line of the error message actually tells you what happened. There are many different types of exceptions, such as <i>ZeroDivisionError<\/i>, <i>NameError<\/i>, <i>TypeError<\/i>, and many more; and this part of the message informs you of what type of exception has been raised. The preceding lines show you the context in which the exception has occured.<\/li>\n<\/ul>\n<p>Python 3 defines 63 built-in exceptions, and all of them form a tree-shaped hierarchy, although the tree is a bit weird as its root is located on top.<\/p>\n<p>Some of the built-in exceptions are more general (they include other exceptions) while others are completely concrete (they represent themselves only). We can say that the closer to the root an exception is located, the more general (abstract) it is. In turn, the exceptions located at the branches&#8217; ends (we can call them leaves) are concrete.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-6013 size-full\" src=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Exceptions1.jpg\" alt=\"\" width=\"741\" height=\"359\" srcset=\"http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Exceptions1.jpg 741w, http:\/\/miro.borodziuk.eu\/wp-content\/uploads\/Exceptions1-300x145.jpg 300w\" sizes=\"(max-width: 706px) 89vw, (max-width: 767px) 82vw, 740px\" \/><\/p>\n<p>Note:<\/p>\n<p><code>ZeroDivisionError<\/code> is a special case of more a general exception class named <code>ArithmeticError<\/code>;<br \/>\n<code>ArithmeticError<\/code> is a special case of a more general exception class named just <code>Exception<\/code>;<br \/>\n<code>Exception<\/code> is a special case of a more general class named BaseException;<\/p>\n<p>We can describe it in the following way (note the direction of the arrows &#8211; they always point to the more general entity):<\/p>\n<p style=\"text-align: center;\"><code>BaseException<\/code><br \/>\n<code>\u2191<\/code><br \/>\n<code>Exception<\/code><br \/>\n<code>\u2191<\/code><br \/>\n<code>ArithmeticError<\/code><br \/>\n<code>\u2191<\/code><br \/>\n<code>ZeroDivisionError<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>2. You can &#8220;catch&#8221; and handle exceptions in Python by using the <code>try-except <\/code>block. So, if you have a suspicion that any particular snippet may raise an exception, you can write the code that will gracefully handle it, and will not interrupt the program. Look at the example:<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">while True:\r\n  try:\r\n    number = int(input(\"Enter an integer number: \"))\r\n    print(number\/2)\r\n    break\r\n  except:\r\n    print(\"Warning: the value entered is not a valid number. Try again...\")<\/pre>\n<p>The code above asks the user for input until they enter a valid integer number. If the user enters a value that cannot be converted to an int, the program will print <code>Warning: the value entered is not a valid number. Try again...<\/code>, and ask the user to enter a number again. What happens in such a case?<\/p>\n<\/div>\n<div><\/div>\n<\/div>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>The program enters the <i>while<\/i> loop.<\/li>\n<li>The <code>try<\/code> block\/clause is executed. The user enters a wrong value, for example: <code>hello!<\/code>.<\/li>\n<li>An exception occurs, and the rest of the <code>try<\/code> clause is skipped. The program jumps to the <code>except<\/code> block, executes it, and then continues running after the <i>try-except<\/i> block.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>If the user enters a correct value and no exception occurs, the subsequent instructions in the <i>try<\/i> block are executed.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<div>3. You can handle multiple exceptions in your code block. Look at the following examples:<\/div>\n<div><\/div>\n<div class=\"small-12 large-6 columns\">\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">while True:\r\n  try:\r\n    number = int(input(\"Enter an int number: \"))\r\n    print(5\/number)\r\n    break\r\n  except ValueError:\r\n    print(\"Wrong value.\")\r\n  except ZeroDivisionError:\r\n    print(\"Sorry. I cannot divide by zero.\")\r\n  except:\r\n    print(\"I don't know what to do...\")<\/pre>\n<p>You can use multiple <i>except<\/i> blocks within one <i>try<\/i> statement, and specify particular exception names. If one of the <code>except<\/code> branches is executed, the other branches will be skipped. Remember: you can specify a particular built-in exception only once. Also, don&#8217;t forget that the <b>default<\/b> (or generic) exception, that is the one with no name specified, should be placed <b>at the bottom of the branch<\/b> (use the more specific exceptions first, and the more general last).<\/p>\n<\/div>\n<\/div>\n<p>You can also specify and handle multiple built-in exceptions within a single <i>except<\/i> clause:<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true \">while True:\r\n  try:\r\n    number = int(input(\"Enter an int number: \"))\r\n    print(5\/number)\r\n    break\r\n  except (ValueError, ZeroDivisionError):\r\n    print(\"Wrong value or No division by zero rule broken.\")\r\n  except:\r\n    print(\"Sorry, something went wrong...\")<\/pre>\n<p>&nbsp;<\/p>\n<\/div>\n<\/div>\n<p>4. Some of the most useful Python built-in exceptions are:<code> ZeroDivisionError<\/code>, <code>ValueError<\/code>, <code>TypeError<\/code>, <code>AttributeError<\/code>, and <code>SyntaxError<\/code>. One more exception that, in our opinion, deserves your attention is the <code>KeyboardInterrupt<\/code> exception, which is raised when the user hits the interrupt key (CTRL-C or Delete).<\/p>\n<p>To learn more about the Python built-in exceptions, consult the official <a href=\"https:\/\/docs.python.org\/3\/library\/exceptions.html#bltin-exceptions\" target=\"_blank\" rel=\"noopener\">Python documentation<\/a>.<\/p>\n<p>&nbsp;<\/p>\n<p>5. Last but not least, you should remember about testing and debugging your code. Use such debugging techniques as <i>print<\/i> debugging; if possible \u2013 ask someone to read your code and help you to find bugs in it or to improve it; try to isolate the fragment of code that is problematic and susceptible to errors: <b>test your functions<\/b> by applying predictable argument values, and try to <b>handle<\/b> the situations when someone enters wrong values; <b>comment out<\/b> the parts of the code that obscure the issue. Finally, take breaks and come back to your code after some time with a fresh pair of eyes.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p>6. You cannot add more than one anonymous (unnamed) except branch after the named ones.<\/p>\n<pre class=\"lang:default decode:true\">:\r\n# The code that always runs smoothly.\r\n:\r\ntry:\r\n  :\r\n  # Risky code.\r\n  :\r\nexcept Except_1:\r\n  # Crisis management takes place here.\r\n  except Except_2:\r\n  # We save the world here.\r\nexcept:\r\n  # All other issues fall here.\r\n:\r\n# Back to normal.\r\n:<\/pre>\n<p>&nbsp;<\/p>\n<p>7. All the predefined Python exceptions form a hierarchy, i.e. some of them are more general (the one named <code>BaseException<\/code> is the most general one) while others are more or less concrete (e.g. <code>IndexError<\/code> is more concrete than <code>LookupError<\/code>).<\/p>\n<p>You should avoid placing more general exceptions before more specific ones inside the same except branche sequence. For example, you can do this:<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n  # Risky code.\r\nexcept IndexError:\r\n  # Taking care of mistreated lists\r\nexcept LookupError:\r\n  # Dealing with other erroneous lookups<\/pre>\n<p>but don&#8217;t do that (unless you&#8217;re absolutely sure that you want some part of your code to be useless)<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n  # Risky code.\r\nexcept LookupError:\r\n  # Dealing with erroneous lookups\r\nexcept IndexError:\r\n  # You'll never get here<\/pre>\n<p>Remember:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>the order of the branches matters!<\/li>\n<li>don&#8217;t put more general exceptions before more concrete ones;<\/li>\n<li>this will make the latter one unreachable and useless;<\/li>\n<li>moreover, it will make your code messy and inconsistent;<\/li>\n<li>Python won&#8217;t generate any error messages regarding this issue.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>Good:<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n    y = 1 \/ 0\r\nexcept ZeroDivisionError:\r\n    print(\"Zero Division!\")\r\nexcept ArithmeticError:\r\n    print(\"Arithmetic problem!\")\r\n\r\nprint(\"THE END.\")\r\n<\/pre>\n<p>Wrong:<\/p>\n<pre class=\"lang:default decode:true\">try:\r\n    y = 1 \/ 0\r\nexcept ArithmeticError:\r\n    print(\"Arithmetic problem!\")\r\nexcept ZeroDivisionError:\r\n    print(\"Zero Division!\")\r\n\r\nprint(\"THE END.\")<\/pre>\n<p>&nbsp;<\/p>\n<p>Example of bad use.<\/p>\n<pre class=\"lang:default decode:true \">try: \r\n    raise Exception \r\nexcept BaseException: \r\n    print(\"a\") \r\nexcept Exception: \r\n    print(\"b\") \r\nexcept: \r\n    print(\"c\") \r\n\r\n<\/pre>\n<p><code>a<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>8. The Python statement <code>raise ExceptionName<\/code> can raise an exception on demand. The same statement, but lacking <code>ExceptionName<\/code>, can be used inside the <code>try<\/code> branch only, and raises the same exception which is currently being handled.<\/p>\n<p>The instruction enables you to:<\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>simulate raising actual exceptions (e.g., to test your handling strategy)<\/li>\n<li>partially handle an exception and make another part of the code responsible for completing the handling (separation of concerns).<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \">def bad_fun(n):\r\n    raise ZeroDivisionError\r\n\r\ntry:\r\n    bad_fun(0)\r\nexcept ArithmeticError:\r\n    print(\"What happened? An error?\")\r\n\r\nprint(\"THE END.\")<\/pre>\n<p><code>What happened? An error?<\/code><br \/>\n<code>THE END.<\/code><\/p>\n<p>The raise instruction may also be utilized in the following way (note the absence of the exception&#8217;s name):<\/p>\n<pre class=\"lang:default decode:true \">raise<\/pre>\n<p>There is one serious restriction: this kind of raise instruction may be used inside the except branch only; using it in any other context causes an error.<\/p>\n<p>The instruction will immediately re-raise the same exception as currently handled.<\/p>\n<pre class=\"lang:default decode:true \">def bad_fun(n):\r\n    try:\r\n        return n \/ 0\r\n    except:\r\n        print(\"I did it again!\")\r\n        raise\r\n\r\ntry:\r\n    bad_fun(0)\r\nexcept ArithmeticError:\r\n    print(\"I see!\")\r\n\r\nprint(\"THE END.\")<\/pre>\n<p><code>I did it again!<\/code><br \/>\n<code>I see!<\/code><br \/>\n<code>THE END.<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>Without <code>rise<\/code>:<\/p>\n<pre class=\"lang:default decode:true \">def bad_fun(n):\r\n    try:\r\n        return n \/ 0\r\n    except:\r\n        print(\"I did it again!\")\r\n        \r\ntry:\r\n    bad_fun(0)\r\nexcept ArithmeticError:\r\n    print(\"I see!\")\r\n\r\nprint(\"THE END.\")\r\n<\/pre>\n<p><code>I did it again!<\/code><br \/>\n<code>THE END.<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>9. The Python statement <code>assert expression<\/code><\/p>\n<ul>\n<li style=\"list-style-type: none;\">\n<ul>\n<li>evaluates the expression;<\/li>\n<li>if the expression evaluates to True, or a non-zero numerical value, or a non-empty string, or any other value different than None, it won&#8217;t do anything else;<\/li>\n<li>otherwise, it automatically and immediately raises an exception named <code>AssertionError<\/code> (in this case, we say that the assertion has failed)<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<pre class=\"lang:default decode:true \">import math\r\n\r\nx = float(input(\"Enter a number: \"))\r\nassert x &gt;= 0.0\r\n\r\nx = math.sqrt(x)\r\n\r\nprint(x)<\/pre>\n<p><code>Enter a number: 2<\/code><br \/>\n<code>1.4142135623730951<\/code><\/p>\n<p><code>Enter a number: -1<\/code><br \/>\n<code>Traceback (most recent call last):<\/code><br \/>\n<code>File \"main.py\", line 4, in &lt;module&gt;<\/code><br \/>\n<code>assert x &gt;= 0.0<\/code><br \/>\n<code>AssertionError<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>10. The <code>else:<\/code> branch of the <code>try<\/code> statement is executed when there has been no exception during the execution of the <code>try:<\/code> block.<\/p>\n<pre class=\"lang:default decode:true\">def reciprocal(n):\r\n    try:\r\n        n = 1 \/ n\r\n    except ZeroDivisionError:\r\n        print(\"Division failed\")\r\n        return None\r\n    else:\r\n        print(\"Everything went fine\")\r\n        return n\r\n\r\nprint(reciprocal(2))\r\nprint(reciprocal(0))<\/pre>\n<p><code>Everything went fine<\/code><br \/>\n<code>0.5<\/code><br \/>\n<code>Division failed<\/code><br \/>\n<code>None<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>11. The <code>finally:<\/code> branch of the <code>try<\/code> statement is <b>always<\/b> executed.<\/p>\n<pre class=\"lang:default decode:true\">def reciprocal(n):\r\n    try:\r\n        n = 1 \/ n\r\n    except ZeroDivisionError:\r\n        print(\"Division failed\")\r\n        n = None\r\n    else:\r\n        print(\"Everything went fine\")\r\n    finally:\r\n        print(\"It's time to say goodbye\")\r\n        return n\r\n\r\nprint(reciprocal(2))\r\nprint(reciprocal(0))<\/pre>\n<p><code>Everything went fine<\/code><br \/>\n<code>It's time to say goodbye<\/code><br \/>\n<code>0.5<\/code><br \/>\n<code>Division failed<\/code><br \/>\n<code>It's time to say goodbye<\/code><br \/>\n<code>None<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>12. The syntax <code>except <i>Exception_Name<\/i> as an <i>exception_object<\/i>:<\/code> lets you intercept an object carrying information about a pending exception.<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n    i = int(\"Hello!\")\r\nexcept Exception as e:\r\n    print(e)\r\n    print(e.__str__())\r\n<\/pre>\n<p><code>invalid literal for int() with base 10: 'Hello!'<\/code><br \/>\n<code>invalid literal for int() with base 10: 'Hello!'<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>13. A\u00a0property named <code>args<\/code> it&#8217;s a <strong>tuple designed to gather all arguments passed to the class constructor<\/strong>. It is empty if the construct has been invoked without any arguments, or contains just one element when the constructor gets one argument (we don&#8217;t count the <code>self<\/code> argument here), and so on.<\/p>\n<pre class=\"lang:default decode:true\">def print_args(args):\r\n    lng = len(args)\r\n    if lng == 0:\r\n        print(\"\")\r\n    elif lng == 1:\r\n        print(args[0])\r\n    else:\r\n        print(str(args))\r\n\r\ntry:\r\n    raise Exception\r\nexcept Exception as e:\r\n    print(e, e.__str__(), sep=' : ' ,end=' \\n ')\r\n    print_args(e.args)\r\n\r\ntry:\r\n    raise Exception(\"my exception\")\r\nexcept Exception as e:\r\n    print(e, e.__str__(), sep=' : ', end=' \\n ')\r\n    print_args(e.args)\r\n\r\ntry:\r\n    raise Exception(\"my\", \"exception\")\r\nexcept Exception as e:\r\n    print(e, e.__str__(), sep=' : ', end=' \\n ')\r\n    print_args(e.args)\r\n<\/pre>\n<p><code>:<\/code><\/p>\n<p><code>my exception : my exception<\/code><br \/>\n<code>my exception<\/code><\/p>\n<p><code>('my', 'exception') : ('my', 'exception')<\/code><br \/>\n<code>('my', 'exception')<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>14. The exception classes can be extended to enrich them with new capabilities, or to adopt their traits to newly defined exceptions.<\/p>\n<pre class=\"lang:default decode:true\">class MyZeroDivisionError(ZeroDivisionError):\t\r\n    pass\r\n\r\ndef do_the_division(mine):\r\n    if mine:\r\n        raise MyZeroDivisionError(\"some worse news\")\r\n    else:\t\t\r\n        raise ZeroDivisionError(\"some bad news\")\r\n\r\nfor mode in [False, True]:\r\n    try:\r\n        do_the_division(mode)\r\n    except ZeroDivisionError:\r\n        print('Division by zero')\r\n\r\nfor mode in [False, True]:\r\n    try:\r\n        do_the_division(mode)\r\n    except MyZeroDivisionError:\r\n        print('My division by zero')\r\n    except ZeroDivisionError:\r\n        print('Original division by zero')<\/pre>\n<p><code>Division by zero<\/code><br \/>\n<code>Division by zero<\/code><br \/>\n<code>Original division by zero<\/code><br \/>\n<code>My division by zero<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>Another example:<\/p>\n<pre class=\"lang:default decode:true \">class PizzaError(Exception):\r\n    def __init__(self, pizza, message):\r\n        Exception.__init__(self, message)\r\n        self.pizza = pizza\r\n\r\nclass TooMuchCheeseError(PizzaError):\r\n    def __init__(self, pizza, cheese, message):\r\n        PizzaError.__init__(self, pizza, message)\r\n        self.cheese = cheese\r\n\r\ndef make_pizza(pizza, cheese):\r\n    if pizza not in ['margherita', 'capricciosa', 'calzone']:\r\n        raise PizzaError(pizza, \"no such pizza on the menu\")\r\n    if cheese &gt; 100:\r\n        raise TooMuchCheeseError(pizza, cheese, \"too much cheese\")\r\n    print(\"Pizza ready!\")\r\n\r\nfor (pz, ch) in [('calzone', 0), ('margherita', 110), ('mafia', 20)]:\r\n    try:\r\n        make_pizza(pz, ch)\r\n    except TooMuchCheeseError as tmce:\r\n        print(tmce, ':', tmce.cheese)\r\n    except PizzaError as pe:\r\n        print(pe, ':', pe.pizza)<\/pre>\n<p><code>Pizza ready!<\/code><br \/>\n<code>too much cheese : 110<\/code><br \/>\n<code>no such pizza on the menu : mafia<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>Example.<\/p>\n<pre class=\"lang:default decode:true\">try:\r\n    assert __name__ == \"__main__\"\r\nexcept:\r\n    print(\"fail\", end=' ')\r\nelse:\r\n    print(\"success\", end=' ')\r\nfinally:\r\n    print(\"done\")\r\n\r\n<\/pre>\n<p>The code outputs: <code>success done<\/code>.<\/p>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<div class=\"small-12 large-6 columns\">\n<h1><strong>Built-in exceptions<\/strong><\/h1>\n<\/div>\n<p><strong><code>BaseException<\/code><\/strong><\/p>\n<p>Location: <code>BaseException<\/code><\/p>\n<p>The most general (abstract) of all Python exceptions &#8211; all other exceptions are included in this one; It can be said that the following two except branches are equivalent: <code>except<\/code>: and<code> except BaseException<\/code>:.<\/p>\n<p>&nbsp;<\/p>\n<div class=\"small-12 large-6 columns\">\n<p><strong><code>ArithmeticError<\/code><\/strong><\/p>\n<p>Location: <code>BaseException \u2190 Exception \u2190 ArithmeticError<\/code><\/p>\n<p>An abstract exception including all exceptions caused by arithmetic operations like zero division or an argument&#8217;s invalid domain.<\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>AssertionError<\/code><\/strong><\/p>\n<p>Location: <code>BaseException \u2190 Exception \u2190 AssertionError<\/code><\/p>\n<p>Description: a concrete exception raised by the <code>assert<\/code> instruction when its argument evaluates to <code>False<\/code>, <code>None<\/code>, <code>0<\/code>, or an empty string<\/p>\n<pre class=\"lang:default decode:true \">from math import tan, radians\r\nangle = int(input('Enter integral angle in degrees: '))\r\n\r\n# We must be sure that angle != 90 + k * 180\r\nassert angle % 180 != 90\r\nprint(tan(radians(angle)))<\/pre>\n<\/div>\n<p>&nbsp;<\/p>\n<p><strong><code>LookupError<\/code><\/strong><\/p>\n<p>Location: <code>BaseException \u2190 Exception \u2190 LookupError<\/code><\/p>\n<p>An abstract exception including all exceptions caused by errors resulting from invalid references to different collections (lists, dictionaries, tuples, etc.)<\/p>\n<p>&nbsp;<\/p>\n<p><strong><code>IndexError<\/code><\/strong><\/p>\n<p>Location:<code> BaseException \u2190 Exception \u2190 LookupError \u2190 IndexError<\/code><\/p>\n<p>A concrete exception raised when you try to access a non-existent sequence&#8217;s element (e.g., a list&#8217;s element)<\/p>\n<pre class=\"lang:default decode:true\"># The code shows an extravagant way\r\n# of leaving the loop.\r\n\r\nthe_list = [1, 2, 3, 4, 5]\r\nix = 0\r\ndo_it = True\r\n\r\nwhile do_it:\r\n    try:\r\n        print(the_list[ix])\r\n        ix += 1\r\n    except IndexError:\r\n        do_it = False\r\n\r\nprint('Done')<\/pre>\n<p>&nbsp;<\/p>\n<p><strong><code>KeyError<\/code><\/strong><\/p>\n<p>Location: <code>BaseException \u2190 Exception \u2190 LookupError \u2190 KeyError<\/code><\/p>\n<p>A concrete exception raised when you try to access a collection&#8217;s non-existent element (e.g., a dictionary&#8217;s element)<\/p>\n<pre class=\"lang:default decode:true \"># How to abuse the dictionary\r\n# and how to deal with it?\r\n\r\ndictionary = { 'a': 'b', 'b': 'c', 'c': 'd' }\r\nch = 'a'\r\n\r\ntry:\r\n    while True:\r\n        ch = dictionary[ch]\r\n        print(ch)\r\nexcept KeyError:\r\n    print('No such key:', ch)<\/pre>\n<p>&nbsp;<\/p>\n<p><strong><code>KeyboardInterrupt<\/code><\/strong><\/p>\n<p>Location:<code> BaseException \u2190 KeyboardInterrupt<\/code><\/p>\n<p>A concrete exception raised when the user uses a keyboard shortcut designed to terminate a program&#8217;s execution (<code>Ctrl-C<\/code> in most OSs); if handling this exception doesn&#8217;t lead to program termination, the program continues its execution.<\/p>\n<p>Note: this exception is not derived from the Exception class. Run the program in IDLE.<\/p>\n<pre class=\"lang:default decode:true\"># This code cannot be terminated\r\n# by pressing Ctrl-C.\r\n\r\nfrom time import sleep\r\nseconds = 0\r\n\r\nwhile True:\r\n    try:\r\n        print(seconds)\r\n        seconds += 1\r\n        sleep(1)\r\n    except KeyboardInterrupt:\r\n        print(\"Don't do that!\")<\/pre>\n<p>&nbsp;<\/p>\n<p><strong><code>MemoryError<\/code><\/strong><\/p>\n<p>Location: <code>BaseException \u2190 Exception \u2190 MemoryError<\/code><\/p>\n<p>A concrete exception raised when an operation cannot be completed due to a lack of free memory.<\/p>\n<pre class=\"lang:default decode:true \"># This code causes the MemoryError exception.\r\n# Warning: executing this code may affect your OS.\r\n# Don't run it in production environments!\r\n\r\nstring = 'x'\r\ntry:\r\n    while True:\r\n        string = string + string\r\n        print(len(string))\r\nexcept MemoryError:\r\n    print('This is not funny!')<\/pre>\n<p>&nbsp;<\/p>\n<p><strong><code>OverflowError<\/code><\/strong><\/p>\n<p>Location: <code>BaseException \u2190 Exception \u2190 ArithmeticError \u2190 OverflowError<\/code><\/p>\n<p>A concrete exception raised when an operation produces a number too big to be successfully stored.<\/p>\n<pre class=\"lang:default decode:true\"># The code prints subsequent\r\n# values of exp(k), k = 1, 2, 4, 8, 16, ...\r\n\r\nfrom math import exp\r\n\r\nex = 1\r\n\r\ntry:\r\n    while True:\r\n        print(exp(ex))\r\n        ex *= 2\r\nexcept OverflowError:\r\n    print('The number is too big.')<\/pre>\n<p>&nbsp;<\/p>\n<div class=\"small-12 large-6 columns\">\n<p><strong><code>ImportError<\/code><\/strong><\/p>\n<p>Location: <code>BaseException \u2190 Exception \u2190 StandardError \u2190 ImportError<\/code><\/p>\n<p>A concrete exception raised when an import operation fails.<\/p>\n<\/div>\n<pre class=\"lang:default decode:true\"># One of these imports will fail - which one?\r\n\r\ntry:\r\n    import math\r\n    import time\r\n    import abracadabra\r\n\r\nexcept:\r\n    print('One of your imports has failed.')<\/pre>\n<p>&nbsp;<\/p>\n<p>&nbsp;<\/p>\n<div class=\"small-12 large-6 columns\">\n<h1>Some useful exceptions<\/h1>\n<h2><strong><code>ZeroDivisionError<\/code><\/strong><\/h2>\n<p>This appears when you try to force Python to perform any operation which provokes division in which the divider is zero, or is indistinguishable from zero. Note that there is more than one Python operator which may cause this exception to raise. Can you guess them all?<\/p>\n<p>Yes, they are: <code>\/<\/code>, <code>\/\/<\/code>, and <code>%<\/code>.<\/p>\n<h2><strong><code>ValueError<\/code><\/strong><\/h2>\n<p>Expect this exception when you&#8217;re dealing with values which may be inappropriately used in some context. In general, this exception is raised when a function (like <code>int()<\/code> or <code>float()<\/code>) receives an argument of a proper type, but its value is unacceptable.<\/p>\n<h2><strong><code>TypeError<\/code><\/strong><\/h2>\n<p>This exception shows up when you try to apply a data whose type cannot be accepted in the current context. Look at the example:<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">short_list = [1]\r\none_value = short_list[0.5]<\/pre>\n<p>You&#8217;re not allowed to use a float value as a list index (the same rule applies to tuples, too). <code>TypeError<\/code> is an adequate name to describe the problem, and an adequate exception to raise.<\/p>\n<p>&nbsp;<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"small-12 large-6 columns\">\n<h2><strong><code>AttributeError<\/code><\/strong><\/h2>\n<p>This exception arrives \u2013 among other occasions \u2013 when you try to activate a method which doesn&#8217;t exist in an item you&#8217;re dealing with. For example:<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true \">short_list = [1]\r\nshort_list.append(2)\r\nshort_list.depend(3)<\/pre>\n<p>The third line of our example attempts to make use of a method which isn\u2019t contained in the lists. This is the place where <code>AttributeError<\/code> is raised.<\/p>\n<\/div>\n<\/div>\n<h2><strong><code>SyntaxError<\/code><\/strong><\/h2>\n<p>This exception is raised when the control reaches a line of code which violates Python&#8217;s grammar. It may sound strange, but some errors of this kind cannot be identified without first running the code. This kind of behavior is typical of interpreted languages \u2013 the interpreter always works in a hurry and has no time to scan the whole source code. It is content with checking the code which is currently being run. An example of such a category of issues will be presented very soon.<\/p>\n<p>It&#8217;s a bad idea to handle this exception in your programs. You should produce code that is free of syntax errors, instead of masking the faults you\u2019ve caused.<\/p>\n<\/div>\n<div class=\"small-12 large-6 columns\">\n<h2><\/h2>\n<h2><strong><code>IndexError<\/code><\/strong><\/h2>\n<p>Look at the code in the editor. What will happen when you run it?<\/p>\n<pre class=\"lang:default decode:true \">my_list = []\r\nx = my_list[0]\r\n<\/pre>\n<p>You will see the following message in reply:<\/p>\n<p><code>Traceback (most recent call last):<\/code><br \/>\n<code>File \"lst.py\", line 2, in <\/code><br \/>\n<code>x = list[0]<\/code><br \/>\n<code>IndexError: list index out of range<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 1<\/em><strong><br \/>\n<\/strong><\/p>\n<p>What is the output of the following program if the user enters <code>0<\/code>?<\/p>\n<div class=\"ace-tm\">\n<div class=\"ace_static_highlight\">\n<pre class=\"lang:default decode:true\">try:\r\n  value = int(input(\"Enter a value: \"))\r\n  print(value\/value)\r\nexcept ValueError:\r\n  print(\"Bad input...\")\r\nexcept ZeroDivisionError:\r\n  print(\"Very bad input...\")\r\nexcept:\r\n  print(\"Booo!\")<\/pre>\n<p>&nbsp;<\/p>\n<p>The program will output: <code>Very bad input...<\/code>.<\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p><em>Ex. 2<\/em><\/p>\n<p>Assuming the user enters 2 as input, what is the output of the following code snippet?<\/p>\n<pre class=\"lang:default decode:true \">x = input(\"Enter a number: \")\r\nprint(x \/ 0)<\/pre>\n<p>&nbsp;<\/p>\n<p>The code will raise a <code>TypeError<\/code> exception<\/p>\n<ul>\n<li>The correct answer is <code><strong>TypeError<\/strong><\/code>. A <code><strong>TypeError<\/strong><\/code> exception is raised whenever an operation is performed on an incorrect data type. In our example, the <code><strong>input<\/strong><\/code> function assigns the value <code><strong>2<\/strong><\/code>, entered by the user, into the variable <code><strong>x<\/strong><\/code>, as a string: <code><strong>x = '2'<\/strong><\/code>.<\/li>\n<\/ul>\n<ul>\n<li>When evaluating the next <code><strong>print<\/strong><\/code> statement, the Python interpreter will raise a <code><strong>TypeError<\/strong><\/code> exception, since the division operator does not support string-type operands. In this case, the interpreter raises the <code><strong>TypeError<\/strong><\/code> exception before the <code><strong>ZeroDivisionError<\/strong><\/code> exception:<code><strong>print('2' \/ 0) <\/strong><\/code><strong>-&gt;<\/strong> <code><strong>TypeError<\/strong><\/code> .<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p><em>Ex. 3<\/em><\/p>\n<p>What is the output of the following code snippet?<\/p>\n<div class=\"result-pane--question-result-pane-wrapper--2bGiz\">\n<div class=\"result-pane--question-result-pane--sIcOh result-pane--accordion-panel--TEJg7\">\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div data-purpose=\"domain-pane\">\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<pre class=\"lang:default decode:true\">x = 0\r\n\u00a0\r\ntry:\r\n  print(1 \/ x)\r\n\u00a0\r\nexcept:\r\n  print('An error occurred')\r\n\u00a0\r\nexcept ZeroDivisionError:\r\n  print('Division by zero is not allowed')\r\n\u00a0\r\nexcept ValueError:\r\n  print('The value entered is incorrect')<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div data-purpose=\"domain-pane\">\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code><strong>An error occurred<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A <code><strong>SyntaxError<\/strong><\/code> exception<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code><strong>Division by zero is not allowed<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code><strong>The value entered is incorrect<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<p>&nbsp;<\/p>\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct answer<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A <code><strong>SyntaxError<\/strong><\/code> exception<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<ul>\n<li>The code snippet raises a <code><strong>SyntaxError<\/strong><\/code> exception because the <strong>default <\/strong><code><strong>except<\/strong><\/code><strong> block <\/strong>(the one without an exception name) must not be specified first but always last.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p><em>Ex. 4<\/em><\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>What is the output of the following code snippet?<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\">for i in range(0, 5, 0):\r\n  print(i)<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct answer<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A <code><strong>ValueError<\/strong><\/code> execption<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\"><\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<ul>\n<li>The syntax of the <code><strong>range()<\/strong><\/code> function is <code><strong>range(start, stop, step)<\/strong><\/code>.<\/li>\n<\/ul>\n<ul>\n<li><code><strong>range()<\/strong><\/code> returns a sequence of numbers containing all values from <code><strong>start<\/strong><\/code> to <code><strong>stop<\/strong><\/code> (excluded), where <code><strong>step<\/strong><\/code> specifies the increment.<\/li>\n<\/ul>\n<ul>\n<li>If the <code><strong>step<\/strong><\/code> value is <code><strong>0<\/strong><\/code>, Python will raise a <code><strong>ValueError<\/strong><\/code> exception.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 5<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>Which of the following code snippets raises a <code><strong>ValueError<\/strong><\/code> exception?<\/p>\n<p>(Select two answers)<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<pre class=\"lang:default decode:true\">l = [1, 2, 3] \r\nl.index(5) \r\n\r\nint(\"Python\")  \r\n\r\nint([1, 2])  \r\n\r\nd = {1: 'a', 2: 'b'} \r\nd.index(1)<\/pre>\n<p><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct selection<\/span>s:<\/p>\n<\/div>\n<div data-purpose=\"answer\">\n<pre class=\"lang:default decode:true \">l = [1, 2, 3] \r\nl.index(5)    # ValueError\r\n \r\nint(\"Python\") # ValueError\r\n\u00a0\r\nint([1, 2])   # TypeError \r\n\u00a0\r\nd = {1: 'a', 2: 'b'}\r\nd.index(1)    # AttributeError<\/pre>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<ul>\n<li>The Python interpreter generates a <code><strong>ValueError<\/strong><\/code> exception when a function receives an argument of the correct type but the wrong value, or, when you try to perform an operation on a value that does not exist.<\/li>\n<li>In <strong>line 4<\/strong> and <strong>6<\/strong>, we find the function <code><strong>int()<\/strong><\/code>, which converts a number or a string to an integer. <strong>Line 6<\/strong> raises a <code><strong>TypeError<\/strong><\/code> because the argument to the <code><strong>int()<\/strong><\/code> function (a <strong>list<\/strong>) is incorrect. <strong>Line 4 <\/strong>raises a <code><strong>ValueError<\/strong><\/code> exception because the argument is of the correct type (a <strong>string<\/strong>), but the <code><strong>\"Python\"<\/strong><\/code> value cannot be converted to an <strong>integer<\/strong>.<\/li>\n<li>The code in <strong>line 2<\/strong> and <strong>9<\/strong> uses the <code><strong>index()<\/strong><\/code> method, which takes an element of a list as an argument and returns the index of its first occurrence. In <strong>line 2<\/strong>, the code raises a <code><strong>ValueError<\/strong><\/code> exception because the value <code><strong>5<\/strong><\/code>, passed as an argument to the <code><strong>index()<\/strong><\/code> method, does not exist in the <code><strong>l<\/strong><\/code> list. Finally, <strong>line 9<\/strong> raises an <code><strong>AttributeError<\/strong><\/code> exception because dictionaries do not support the <code><strong>index()<\/strong><\/code> method.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 6<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>What is the output of the following code snippet?<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\">s = \"python\"\u00a0\r\ns[0] = 'P'\r\n\r\nprint(s)<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>Ppython<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>Python<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>A TypeError exception<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>pPython<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct answer<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A <code><strong>TypeError<\/strong><\/code> exception<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>The interpreter generates a <code><strong>TypeError<\/strong><\/code> exception because strings in Python are <strong>immutable<\/strong> objects and, therefore, cannot be modified by item assignment.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 7<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>Which of the following code snippets causes a <code><strong>SyntaxError<\/strong><\/code> exception?<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<pre class=\"lang:default decode:true \">x = 10; y = 2; print(y + x);\r\n\r\nx = 10; y = 2\r\nprint(y + x)\r\n\r\nx = 10; y = 2; print(y + x)\r\n\r\n<\/pre>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<p>&nbsp;<\/p>\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<ul>\n<li>No response raises <code><strong>SyntaxError<\/strong><\/code> exception.<\/li>\n<li>In Python, if you want to place <strong>multiple<\/strong> statements on a <strong>single<\/strong> physical line, you must separate them with a <strong>semicolon<\/strong> (<code><strong>;<\/strong><\/code>), which indicates the end of a statement.<\/li>\n<li>However, it is good practice to write a single instruction in a single physical line as far as possible.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 8<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>What is the output of the following code snippet?<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true \">tpl = (1, 2, 3, 4)\r\ntpl.append(5)<\/pre>\n<p><code>The code will raise the <strong>ValueError<\/strong> exception<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>The code will raise the <strong>AttributeError<\/strong> exception<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>The code will raise the <strong>TypeError<\/strong> exception<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>The code will raise the <strong>SyntaxError<\/strong> exception<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div><\/div>\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct answer<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>The code will raise the <code><strong>AttributeError<\/strong><\/code> exception<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<ul>\n<li>When we try to use a method on an object that doesn&#8217;t support it, Python raises an <code><strong>AttributeError<\/strong><\/code> exception. In our case, tuples are <strong>immutable<\/strong> objects and do not support the <code><strong>append<\/strong><\/code> method.<\/li>\n<li><strong>Additional note<\/strong>You can easily append new elements to a tuple by using the <code><strong>+<\/strong><\/code> operator. If you try to run the following code, you will see that the <code><strong>print<\/strong><\/code> statement will display the tuple <code><strong>tpl<\/strong><\/code> with the new <code><strong>4<\/strong><\/code> element added at the end.\n<pre class=\"lang:default decode:true \">tpl = (1, 2, 3)\r\ntpl = tpl + (4,) # line 2\r\n\u00a0\r\nprint(tpl)<\/pre>\n<div class=\"ud-component--base-components--code-block\">\n<div><\/div>\n<\/div>\n<p>However, even in this case, tuples are always immutable. In fact, <strong>line 2<\/strong> of the code does not append a new element to the old tuple, but creates a <strong>new tuple<\/strong> that is assigned to the same variable <code><strong>tpl<\/strong><\/code>. In other words, while at the beginning <code><strong>tpl<\/strong><\/code> points to the tuple <code><strong>(1, 2, 3)<\/strong><\/code>, at the end it points to the new tuple <code><strong>(1, 2, 3, 4)<\/strong><\/code>.<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>Ex. 9<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>What is the output of the following code snippet?<\/p>\n<pre class=\"lang:default decode:true\">def fun():\r\n\u00a0\r\nprint(fun())<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code><strong>pass<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>Nothing<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A <code><strong>SyntaxError<\/strong><\/code> exception<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code><strong>None<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct answer<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A <code><strong>SyntaxError<\/strong><\/code> exception<\/p>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<ul>\n<li>Python doesn\u2019t support <strong>empty<\/strong> code blocks. To write empty code blocks you can use the statement <code><strong>pass<\/strong><\/code>.<\/li>\n<\/ul>\n<ul>\n<li><code><strong>pass<\/strong><\/code> is a special statement that does nothing.\u00a0 So, you can define an empty function as follows:<\/li>\n<\/ul>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\">def fun():\r\n  pass<\/pre>\n<p>&nbsp;<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p>Ex. 10<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>Which of the following statements <strong>correctly<\/strong> handle <strong>multiple exceptions<\/strong> in a <strong>single<\/strong> <code><strong>except<\/strong><\/code> block?<\/p>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>except TypeError, ZeroDivisionError:<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>except (TypeError, ZeroDivisionError):<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>except TypeError, ZeroDivisionError<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>except (TypeError, ZeroDivisionError)<\/code><\/p>\n<div><\/div>\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct answer<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code><strong>except (TypeError, ZeroDivisionError):<\/strong><\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<ul>\n<li>To properly handle <strong>multiple exceptions<\/strong> in a <strong>single<\/strong> <code><strong>except<\/strong><\/code> block, we can group them into a <strong>parenthesized<\/strong> <strong>tuple<\/strong>, followed by a <strong>colon<\/strong>:<code>e<strong>xcept (except1, except2, ..., exceptionN):<\/strong><\/code>.<\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p>Ex. 11<\/p>\n<div class=\"result-pane--question-header-wrapper--3DCpC\">\n<div class=\"result-pane--question-header--pTUOx\">\n<div id=\"question-prompt\" class=\"result-pane--question-format--PBvdY ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>What is the output of the following code snippet?<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<pre class=\"lang:default decode:true\">def fun(n):\r\n  n += 2\r\n\r\nx = 3\r\nprint(x + fun(2))<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-result-pane-expanded-content--Og5Vc\">\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A <code>TypeError<\/code> exception<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>None<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>7<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-incorrect--vFyOv\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p><code>3<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--question-related-fields--c3m--\">\n<div><\/div>\n<div><\/div>\n<div class=\"overall-explanation-pane--overall-explanation--G-hLQ ud-form-group\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">Correct answer<\/span><\/div>\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>A <code><strong>TypeError<\/strong><\/code> exception<\/p>\n<\/div>\n<\/div>\n<div id=\"overall-explanation\" class=\"ud-text-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<ul>\n<li>In Python, a function without a <code><strong>return<\/strong><\/code> statement (or with a <code><strong>return<\/strong><\/code> statement without a value or expression) returns <code><strong>None<\/strong><\/code>.<\/li>\n<\/ul>\n<ul>\n<li><code><strong>None<\/strong><\/code> is a Python keyword and is used to represent the absence of a value. It can be assigned to a variable and can be used in comparison operations, but cannot be used as an operand in arithmetic expressions.<\/li>\n<\/ul>\n<ul>\n<li>For this reason, the print statement of the code will raise a <code><strong>TypeError<\/strong><\/code> exception:<strong>step by step<\/strong>Step 1 &#8211;\u00a0 <code><strong>print(x + fun(2))<\/strong><\/code>Step 2 &#8211; <code><strong>print(3 + None) <\/strong><\/code>Output &#8211; <code><strong>TypeError<\/strong><\/code><\/li>\n<\/ul>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p>&nbsp;<\/p>\n<p><em>Ex. 12<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true\">try:\r\n  print(\"Let's try to do this\")\r\n  print(\"#\"[2])\r\n  print(\"We succeeded!\")\r\nexcept:\r\n  print(\"We failed\")\r\nprint(\"We're done\")<\/pre>\n<p>Let&#8217;s try to do this<br \/>\n<code>We failed<\/code><br \/>\n<code>We're done<\/code><\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 13<\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n  print(\"alpha\"[1\/0])\r\nexcept ZeroDivisionError:\r\n  print(\"zero\")\r\nexcept IndexingError:\r\n  print(\"index\")\r\nexcept:\r\n  print(\"some\")<\/pre>\n<p><code>zero<\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p><em>Exercise 14<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true \">try:\r\n    print(1\/0)\r\nexcept ZeroDivisionError:\r\n    print(\"zero\")\r\nexcept ArithmeticError:\r\n    print(\"arith\")\r\nexcept:\r\n    print(\"some\")<\/pre>\n<p><code>zero<\/code><\/p>\n<p><em>Exercise 15<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true\">try:\r\n    print(1\/0)\r\nexcept ArithmeticError:\r\n    print(\"arith\")\r\nexcept ZeroDivisionError:\r\n    print(\"zero\")\r\nexcept:\r\n    print(\"some\")<\/pre>\n<p><code>arith<\/code><\/p>\n<p><em>Exercise 16<\/em><\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true\">def foo(x):\r\n    assert x\r\n    return 1\/x\r\n\r\ntry:\r\n    print(foo(0))\r\nexcept ZeroDivisionError:\r\n    print(\"zero\")\r\nexcept:\r\n    print(\"some\")\r\n<\/pre>\n<p><code>some<\/code><\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 17<\/em><\/p>\n<p>What is the expected output of the following code snippet ?<\/p>\n<pre class=\"lang:default decode:true \">from math import sqrt as root\r\n     \r\ndef my_root(x):\r\n    try:\r\n        return root(x)\r\n    except:\r\n        print('Function Error !')\r\n        raise\r\n     \r\nx=-2\r\ntry:\r\n    assert x + 2, \"Wrong input !\"\r\n    print(my_root(x))\r\nexcept Exception as e:\r\n    print(e)\r\nelse:\r\n    print('All good !')<\/pre>\n<p>The function <code>my_root()<\/code> attempts to return the result of <code>root(x)<\/code> (i.e. square root of x) and catches any exception &#8211; if there is an exception, message &#8220;Function Error !&#8221; is printed out and the same exception is raised again for processing outside of the function.<\/p>\n<p>Line <code>assert x + 2, \"Wrong input !\"<\/code> will raise an <code>AssertionError<\/code>\u00a0 if <code>x+2<\/code>\u00a0 returns <code>0<\/code>, along with the message &#8220;Wrong input !&#8221;.<\/p>\n<p>With <code>x=-2<\/code>, the <code>AssertionError<\/code>\u00a0 is raised and caught in the <code>except:<\/code> branch.<\/p>\n<p>Consequently, the following is printed out :<\/p>\n<p><code>Wrong input !<\/code><\/p>\n<p>If x had been a positive integer, then function <code>my_root()<\/code>\u00a0 would have returned the square root of x.<\/p>\n<p>If x had been a negative integer (other than -2), then function <code>my_root()<\/code>\u00a0 would have raised an exception (within the function and outside the function).<\/p>\n<p>&nbsp;<\/p>\n<p><em>Exercise 18<\/em><\/p>\n<p>What is the expected output of the following snippet ?<\/p>\n<pre class=\"lang:default decode:true \">    def list_func(x):\r\n        try:\r\n            return x[4]\/x[-1]\r\n        except ZeroDivisionError:\r\n            print(\"Function Error #1\")\r\n            raise\r\n        except IndexError:\r\n            print(\"Function Error #2\")\r\n            raise\r\n        except:\r\n            print(\"Function Error #3\")\r\n            raise\r\n     \r\n    my_list=[3,4,1,0]\r\n    try:\r\n        print(list_func(my_list))\r\n    except LookupError:\r\n        print(\"Program Error #1\")\r\n    except ArithmeticError:\r\n        print(\"Program Error #2\")\r\n    except:\r\n        print(\"Program Error #3\")<\/pre>\n<p>Function <code>list_func()<\/code> returns the result of the division of the 5th element (index 4) of the argument x by the last element (index -1) of the argument x.<\/p>\n<p><code>list_func(my_list)<\/code>\u00a0 where <code>my_list=[3,4,1,0]<\/code>\u00a0 will raise an exception because the list has only 4 elements. <span class=\"HwtZe\" lang=\"en\"><span class=\"jCAhz ChMk0b\"><span class=\"ryNqvb\">Division by zero won&#8217;t even be checked because the error occurs earlier.<\/span><\/span><\/span><\/p>\n<p>This type of exception is an <strong>IndexError <\/strong>exception which is a subclass of <strong>LookupError <\/strong>exception.<\/p>\n<p>So, the clause <code>except IndexError:<\/code>\u00a0 in the function <code>list_func()<\/code>\u00a0 will be executed and <code>Function error #2<\/code> will be printed.<\/p>\n<p>In addition, because of the <code>raise<\/code> command, the same IndexError exception is raised again &#8211; but this time the exception is handled outside of the function <code>list_func()<\/code>. The <code>except LookupError:<\/code> clause is the first one matching the IndexError exception and consequently <code>Program Error #1<\/code> is printed.<\/p>\n<p>So correct answer is :<\/p>\n<div class=\"ud-component--base-components--code-block\">\n<div>\n<p><code><span class=\"typ\">Function<\/span> <span class=\"typ\">Error<\/span> <span class=\"com\">#2<\/span><\/code><\/p>\n<p><code><span class=\"typ\">Program<\/span> <span class=\"typ\">Error<\/span> <span class=\"com\">#1<\/span><\/code><\/p>\n<\/div>\n<p>&nbsp;<\/p>\n<p><em>Exercise 19<\/em><\/p>\n<p>What is the expected output of the following code snippet ?<\/p>\n<pre class=\"lang:default decode:true \">    class AlphaDivisionError(ZeroDivisionError):\t\r\n        def __init__(self, message):\r\n            ZeroDivisionError.__init__(self, message)\r\n     \r\n    def func_div(x,y):\r\n        if y==0:\r\n            raise ZeroDivisionError(\"Can't divide by zero !\")\r\n        elif isinstance(y, str):\t\t\r\n            raise AlphaDivisionError(\"Can't divide by string !\")\r\n        else:\t\t\r\n            return x\/y\r\n     \r\n    try:\r\n        print(func_div(4,'a'))\r\n    except ZeroDivisionError as e:\r\n        print(str(e))\r\n    except Exception as e:\r\n        print(\"There is an error !\")\r\n    else:\r\n        print('All good !')<\/pre>\n<p><code>Can't divide by string !<\/code><\/p>\n<\/div>\n<p><strong>Explanation:<\/strong><\/p>\n<p><code>AlphaDivisionError<\/code> is a <strong>self-defined exception<\/strong> and is defined as a sub-class of the <code>ZeroDivisionError <\/code>class.<\/p>\n<p>In function <code>func_div()<\/code>, if the second argument is a string (i.e.<code> isinstance(y, str)<\/code> returns <code>True<\/code>), the <code>AlphaDivisionError<\/code> exception is raised.<\/p>\n<p>So :\u00a0 <code>print(func_div(4,'a'))<\/code> will raise the <code>AlphaDivisionError<\/code> exception. The first\u00a0 <code>except:<\/code>\u00a0 branch that matches the <code>AlphaDivisionError<\/code> exception is the branch <code>except ZeroDivisionError as e:<\/code>\u00a0 since <code>AlphaDivisionError<\/code>\u00a0 is a sub-class of <code>ZeroDivisionError<\/code>.<\/p>\n<p>Consequently, message <code>Can't divide by string !<\/code>\u00a0 is printed out.<\/p>\n<p>&nbsp;<\/p>\n<p>Ex. 20<\/p>\n<p>What is the expected output of the following code?<\/p>\n<pre class=\"lang:default decode:true\">    x = 'France'\r\n     \r\n    def func(x):\r\n        return x[:-3]\r\n     \r\n    try:\r\n        for i in range(3):\r\n            x = func(x)\r\n            assert x\r\n        print(x)    \r\n    except IndexError:\r\n        print(\"Error 1\")\r\n    except LookupError:\r\n        print(\"Error 2\")\r\n    except:\r\n        print(\"Error 3\")<\/pre>\n<p>Explanation:<\/p>\n<p>The function <code>func() <\/code>takes a string a returns it minus the last three characters.<\/p>\n<p>When executing this function twice on string <code>'France'<\/code>, the resulting string will be an empty string.<\/p>\n<p><code>assert expression<\/code>\u00a0 will evaluate the <em>expression <\/em>and if the <em>expression <\/em>meets one of the following criteria, then an <strong>AssertionError <\/strong>will be raised :<\/p>\n<p>&#8211; <em>expression <\/em>evaluates to <code>False<\/code><\/p>\n<p>&#8211; <em>expression <\/em>evaluates to <code>0<\/code><\/p>\n<p>&#8211; <em>expression <\/em>evaluates to an empty string<\/p>\n<p>&#8211; <em>expression <\/em>evaluates to <code>None<\/code><\/p>\n<p>So, in the <code>try:<\/code> branch above, an <strong>AssertionError <\/strong>will be raised since at one point <code>x<\/code> will become an empty string and <code>assert x<\/code> will raise the exception.<\/p>\n<p>So : <code>Error 3<\/code>\u00a0 will be printed.<\/p>\n<p>Try it yourself:<\/p>\n<pre class=\"lang:default decode:true \">    x = 'France'\r\n     \r\n    def func(x):\r\n        return x[:-3]\r\n     \r\n    try:\r\n        for i in range(3):\r\n            x = func(x)\r\n            print(x)            # Fra -&gt; empty string \r\n            assert x, \"Assert Error\"    # Added message to make it clear it is an AssertError\r\n        print(x)    \r\n    except IndexError:\r\n        print(\"Error 1\")\r\n    except LookupError:\r\n        print(\"Error 2\")\r\n    except Exception as e:\r\n        print(e)            # Assert Error\r\n        print(\"Error 3\")    # Error 3<\/pre>\n<p>&nbsp;<\/p>\n<p>Ex. 21<\/p>\n<p>What is the expected output of the following code if the user enters <code>133<\/code> when prompted with &#8220;<em>Enter integer between 0 and 100 : <\/em>&#8221; ?<\/p>\n<pre class=\"lang:default decode:true \">    class NotInRangeError(Exception):\r\n        def __init__(self, val, message=\"Value is out of range\"):\r\n            self.val = val\r\n            self.message = message\r\n            super().__init__(self.message, self.val)\r\n     \r\n    try:\r\n        guess = int(input(\"Enter integer between 0 and 100: \"))\r\n        if not 0 &lt;= guess &lt;= 100:\r\n            raise NotInRangeError(guess)\r\n    except Exception as ex:\r\n        for arg in ex.args:\r\n            print(arg, end=' ')<\/pre>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-correct--PLOEU\" data-purpose=\"answer\">\n<div><span class=\"result-pane--answer-by-user-label--PSH86 ud-heading-xs\" data-purpose=\"answer-result-header-user-label\">A. <\/span><code>Value is out of range 133<\/code><\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>B. <code>133 <\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>C. There will be an unhandled exception.<\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<div class=\"result-pane--answer-result-pane--Niazi\">\n<div class=\"answer-result-pane--answer-skipped--1NDPn\" data-purpose=\"answer\">\n<div class=\"answer-result-pane--answer-body--cDGY6\" data-purpose=\"answer-body\">\n<div id=\"answer-text\" class=\"ud-heading-md rt-scaffolding\" data-purpose=\"safely-set-inner-html:rich-text-viewer:html\">\n<p>D. <code>133 Value is out of range<\/code><\/p>\n<\/div>\n<\/div>\n<\/div>\n<\/div>\n<p><em>Explanation:<\/em><\/p>\n<p>Because the user enters a value that is not in the range [0,100], the <code>NotInRangeError<\/code> exception is raised. This is a custom exception, sub-class of the <code>Exception<\/code> class, and with two properties that are passed to the constructor of its superclass.<\/p>\n<p>The <code>args <\/code>property is a tuple that contains all arguments passed to the class constructor &#8211; in this case both the <code>message <\/code>and <code>val <\/code>properties of <code>NotInRangeError<\/code> are passed to the <code>Exception <\/code>constructor (in that order).<\/p>\n<p>The resulting output is : <code>Value is out of range 133<\/code><\/p>\n<p>A.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>1. In Python, there is a distinction between two kinds of errors:<\/p>\n","protected":false},"author":2,"featured_media":5924,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[100],"tags":[],"_links":{"self":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5825"}],"collection":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/comments?post=5825"}],"version-history":[{"count":53,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5825\/revisions"}],"predecessor-version":[{"id":6277,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/posts\/5825\/revisions\/6277"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/media\/5924"}],"wp:attachment":[{"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/media?parent=5825"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/categories?post=5825"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/miro.borodziuk.eu\/index.php\/wp-json\/wp\/v2\/tags?post=5825"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}