{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python 101\n", "## Part VI. extra\n", "\n", "---\n", "\n", "## Custom Exceptions\n", "\n", "We can define our own Exceptions!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class MyError(Exception):\n", " def __init__(self, value):\n", " self.value = value\n", " \n", " def __str__(self):\n", " # repr returns the string representation of the object.\n", " return repr(self.value)\n", "\n", "try:\n", " raise MyError(2*2)\n", "except MyError as e:\n", " print('My exception occurred, value:', e.value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the previous example, the Exception class' default `__init__()` method has been overridden. Instead of `*args`, this new Exception has a `value` attribute. \n", "When creating a module that can raise several distinct errors, a common practice is to create a base class for exceptions defined by that module and subclass it to create specific exception classes for different error conditions." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class FuliError(Exception):\n", " \"\"\"Base class for our exceptions.\"\"\"\n", " pass\n", "\n", "\n", "class NumberError(FuliError):\n", " \"\"\"Exception raised when a not wanted number entered.\"\"\"\n", "\n", " def __init__(self, number, explanation):\n", " self.number = number\n", " self.exp = explanation\n", "\n", " \n", "class CharacterError(FuliError):\n", " \"\"\"Exception raised when a not wanted character entered.\"\"\"\n", "\n", " def __init__(self, character):\n", " self.character = character\n", " self.exp = \"You messed with the wrong character, buddy!\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Let's practice exception handling - write the missing code snippets!\n", "\n", "#### 1. Write a \"Guess the number\" game class which handle erroneous inputs" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# import random module\n", "import random\n", "\n", "# create a class\n", "class GuessANumber(object):\n", "\n", " # init with a random number\n", " def __init__(self, limit=10):\n", " pass # write your code here\n", " \n", " # write a respond method, which returns 'Win', 'Lower', 'Higher' words as response to it's argument.\n", " # in case of errors, inform the user.\n", " def guess(self, guess):\n", " pass # write your code here\n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "inputs = ['valami', 0.3, 5, 'a']\n", "for inp in inputs:\n", " print('game init...', end='')\n", " game = GuessANumber(inp)\n", " print('done. Target:', game.number)\n", " for guess in inputs:\n", " print('- guess:', guess)\n", " game.guess(guess)\n", " print '-'*30" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 2. RPS class with error handling" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "inputs = ['valami', 0.3, 5, 'r']\n", "rps = RPS()\n", "for inp in inputs:\n", " rps.play(inp)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 3. Count the files in a given directory.\n", "- Count them by extensions. (eg: {\"ipynb\": 6, \"py': 1})\n", "- hint(s):\n", " - use `os.listdir` to list everything in a directory\n", " - use `os.path.isfile` to determine if the item in the given path is a file\n", " - use `os.path.join` to join the directory and the filename together\n", " - there is a `Counter` class in the `collections` standard library - you can use it in this case" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 4. Write a basic calculator\n", "With the following features:\n", "- only two numbers and an operation allowed\n", "- operation can be: __`+`__, __`-`__, __`*`__, __`/`__, __`^`__, __`&`__ (and), __`|`__ (or), __`=`__ (equality check), __`~`__ (negation, the second number is ignored)\n", "- be careful to handle exceptions!" ] }, { "cell_type": "raw", "metadata": {}, "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### 5. Save/load your work!\n", "Create a loader/saver class, which can save variables to files and then load from them.\n", "- saving should have two parameters: target filename, and `**kwargs`\n", "- `kwargs` will now contains every given variables in a **dictionary** in the following format: `{variable_name: value, ...}`\n", "- saving is pretty easy: use the `dump()` function from the `json` library to create a string representation of the variables and write it to the target file\n", "- saving shouldn't overwrite previous saves!\n", "- loading should have one parameter: source file name\n", "- to load the data, you should use the `json` library `load()` function on the lines readed from the save file\n", "- loading should return the result(s) of the `json.load()` function call\n", "- loading should load all of the save data, and remove the save file\n", "\n", "Do not forget about error handling!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import json" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class SaveLoader(object):\n", " pass # your code goes here" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sl = SaveLoader()\n", "sl.save('mylittlesave.sav', a=7, b=8, c={'a': 7, 'b': 8}, d=[])\n", "a = 7\n", "b = 8\n", "c = {'a': a, 'b': b}\n", "d = [a, b, c]\n", "sl.save('mylittlesave.sav', d=d)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sl.load('mylittlenonexistingsave.sav')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(sl.load('mylittlesave.sav'))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The result should be:\n", "\n", "`[{'a': 7, 'b': 8, 'c': {'a': 7, 'b': 8}, 'd': []}, \n", " {'d': [7, 8, {'a': 7, 'b': 8}]}]`" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.10" } }, "nbformat": 4, "nbformat_minor": 1 }