{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Dealing with exceptions\n", "Fill `____` parts of the implementation below. `sum_of_list` function takes a list as argument and calculates the sum of values in the list. If some element in the list can not be converted to a numeric value, it should be ignored from the sum." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def sum_of_list(values):\n", " ____ = 0\n", " for val in values:\n", " ____:\n", " numeric_val = float(val)\n", " ____ ____ as e:\n", " ____\n", " ____ += numeric_val\n", " return ____" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "editable": false }, "outputs": [], "source": [ "list1 = [1, 2, 3]\n", "list2 = [\"1\", 2.5, \"3.0\"]\n", "list3 = [\"\", \"1\"]\n", "list4 = []\n", "list5 = [\"John\", \"Doe\", \"was\", \"here\"]\n", "nasty_list = [KeyError(), [], dict()]\n", "\n", "assert sum_of_list(list1) == 6\n", "assert sum_of_list(list2) == 6.5\n", "assert sum_of_list(list3) == 1\n", "assert sum_of_list(list4) == 0\n", "assert sum_of_list(list5) == 0\n", "assert sum_of_list(nasty_list) == 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 2. Using custom exceptions\n", "Implement `verify_short_string` function which takes a single string as argument. If the length of the input string is more than ten characters, the function should raise `TooLongString` exception (note: you have to create `TooLongString` yourself). The function does not have to return anything. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Your implementation here" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "editable": false }, "outputs": [], "source": [ "# These should not raise\n", "verify_short_string(\"short\")\n", "verify_short_string(\"10 chars\")\n", "\n", "# This should raise\n", "try:\n", " verify_short_string(\"this is long\")\n", "except TooLongString as e:\n", " # This is ok\n", " pass\n", "else:\n", " # This means that there was no exception\n", " assert False" ] } ], "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.11.0" } }, "nbformat": 4, "nbformat_minor": 2 }