{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# SW05 - Flipped Classroom \n", "\n", "*This JupyterNotebook is intended to practice the theory alongside the slides and is used as a \"practical check of the theory input\". There are no sample solutions and the file will not be corrected and does not have to be submitted.*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "# Tuples \n", "\n", "A tuple is an ordered sequence of elements that is immutable. - **non-mutable**. " ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "1\n", "2\n", "4\n", "word\n", "20\n", "True\n", "False\n" ] } ], "source": [ "x = 20\n", "my_tuple = (1, 2, 4, \"word\", x)\n", "\n", "print(my_tuple[0])\n", "\n", "for telement in my_tuple:\n", " print(telement)\n", "\n", "print(1 in my_tuple)\n", "print((1,2) in my_tuple)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n" ] } ], "source": [ "my_tuple = (1, 2)\n", "x, y = my_tuple\n", "\n", "print(x)\n", "print(y)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n" ] } ], "source": [ "# round brackets could be omitted but is not recommeded\n", "my_tuple = 1, 2, 3\n", "x, y, z = my_tuple\n", "\n", "print(x)\n", "print(y)\n", "print(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "# Sets \n", "\n", "Sets are unordered lists that contain each element **only once**." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'pear', 'apple', 'banana', 'pineapple'}\n", "{'pear', 'apple', 'banana', 'pineapple'}\n", "{'pear', 1, 'banana', 'pineapple', 'apple'}\n" ] } ], "source": [ "my_set = {\"apple\",\"banana\", \"pear\"}\n", "\n", "# add an item\n", "my_set.add(\"pineapple\")\n", "print(my_set)\n", "\n", "# Add same item again\n", "my_set.add(\"pineapple\")\n", "print(my_set)\n", "\n", "my_set.add(1)\n", "print(my_set)\n" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'apple', 'banana', 'pear', 'pineapple'}" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_set.remove(1)\n", "my_set" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"pear\" in my_set" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Superset und Subset " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "my_set is superset of my_set2: True\n", "my_set_2 is superset of my_set: True\n" ] } ], "source": [ "my_set = {'banana', 'pineapple', 'pear', 'apple'}\n", "my_set_2 = {'banana', 'pear', 'pineapple'}\n", "\n", "\n", "print(f\"my_set is superset of my_set2: {my_set.issuperset(my_set_2)}\")\n", "print(f\"my_set_2 is superset of my_set: {my_set_2.issubset(my_set)}\")\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "# Dictionaries \n", "\n", "A dictionary is a \"list\" of key-value-pairs. Like in a Set each key can only be in there once.\n" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "kv_dict = {\"key\":\"value\"}" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'value'" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "kv_dict[\"key\"]\n" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'key': 'value'}" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "kv_dict" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'joy'" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# create a dict with several key-value pairs\n", "\n", "my_dict = {\"b\": \"beauty\", \"j\": \"joy\"}\n", "my_dict\n", "\n", "my_dict[\"b\"]\n", "my_dict[\"j\"]" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'b': 'boy', 'j': 'joy', 'c': 'computing', 'd': 'dream'}" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# adding another key-value pair to my_dict\n", "my_dict[\"c\"] = \"computing\"\n", "\n", "# and another one\n", "my_dict[\"d\"] = \"dream\"\n", "\n", "# overwriting the old key \"b\"\n", "my_dict[\"b\"] = \"boy\"\n", "\n", "my_dict" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Dict in Dict" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'John': {'Age': 48, 'Gender': 'm', 'Profession': 'Carpenter'}, 'James': {'Age': 25, 'Gender': 'm', 'Profession': 'Student'}, 'Peter': {'Age': 35, 'Gender': 'm', 'Profession': 'Electrician', 'Family': {}}}\n" ] } ], "source": [ "# two elements in the dict. each one consisting of a dictionary for the key name\n", "my_family = {\"John\":{\n", " \"Age\": 48,\n", " \"Gender\": \"m\",\n", " \"Profession\":\"Carpenter\"\n", " },\n", " \"James\":{\n", " \"Age\": 25,\n", " \"Gender\": \"m\",\n", " \"Profession\":\"Student\",\n", "\n", " }\n", "}\n", "\n", "# adding another member\n", "my_family[\"Peter\"] = {\n", " \"Age\": 35,\n", " \"Gender\": \"m\",\n", " \"Profession\":\"Electrician\",\n", " \"Family\": {},\n", " }\n", "\n", "print(my_family)\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "35" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# accessing the value age\n", "my_family[\"Peter\"][\"Age\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "### Exercise with my_friends dictionary \n", "\n" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'Julia': {'age': 23,\n", " 'height': 1.68,\n", " 'gender': 'f',\n", " 'profession': 'nurse',\n", " 'relationship': 'girlfriend'},\n", " 'Maya': {'age': 27,\n", " 'height': 1.6,\n", " 'gender': 'd',\n", " 'profession': 'policewoman',\n", " 'relationship': 'bff'},\n", " 'Alex': {'age': 22,\n", " 'height': 1.79,\n", " 'gender': 'm',\n", " 'profession': 'priest',\n", " 'relationship': 'friend'}}" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# single entry in the dict\n", "my_friends = {\"Julia\": {\"age\": 23, \"height\": 1.68, \"gender\": \"f\", \"profession\": \"nurse\", \"relationship\": \"girlfriend\"}, \n", "\"Maya\": {\"age\": 27, \"height\": 1.60, \"gender\": \"d\", \"profession\": \"policewoman\", \"relationship\": \"bff\"}}\n", "\n", "# add another friend\n", "my_friends[\"Alex\"] = {\"age\": 22, \"height\": 1.79, \"gender\": \"m\", \"profession\": \"priest\", \"relationship\": \"friend\"}\n", "my_friends" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "23\n", "27\n", "22\n" ] } ], "source": [ "for friends in my_friends:\n", " print(my_friends[friends][\"age\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "### Dict Funktionen: len() and .items() \n", "\n" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n", "3\n" ] } ], "source": [ "# the \"length\" of a dictionary\n", "print(len(my_family))\n", "print(len(my_family[\"John\"]))" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'John': {'Age': 48, 'Gender': 'm', 'Profession': 'Carpenter'}, 'James': {'Age': 25, 'Gender': 'm', 'Profession': 'Student'}, 'Peter': {'Age': 35, 'Gender': 'm', 'Profession': 'Electrician', 'Family': {}}}\n" ] } ], "source": [ "# two elements in the dict. each one consisting of a dictionary for the key name\n", "my_family = {\"John\":{\n", " \"Age\": 48,\n", " \"Gender\": \"m\",\n", " \"Profession\":\"Carpenter\"\n", " },\n", " \"James\":{\n", " \"Age\": 25,\n", " \"Gender\": \"m\",\n", " \"Profession\":\"Student\",\n", "\n", " }\n", "}\n", "\n", "# adding another member\n", "my_family[\"Peter\"] = {\n", " \"Age\": 35,\n", " \"Gender\": \"m\",\n", " \"Profession\":\"Electrician\",\n", " \"Family\": {},\n", " }\n", "\n", "print(my_family)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "John\n", "James\n", "Peter\n" ] } ], "source": [ "for key in my_family:\n", " print(key)\n" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "John: {'Age': 48, 'Gender': 'm', 'Profession': 'Carpenter'}\n", "James: {'Age': 25, 'Gender': 'm', 'Profession': 'Student'}\n", "Peter: {'Age': 35, 'Gender': 'm', 'Profession': 'Electrician', 'Family': {}}\n" ] } ], "source": [ "# item() funktion to access key and value\n", "for key, value in my_family.items():\n", " print(f\"{key}: {value}\")" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "John: Age: 48\n", "John: Gender: m\n", "John: Profession: Carpenter\n", "James: Age: 25\n", "James: Gender: m\n", "James: Profession: Student\n", "Peter: Age: 35\n", "Peter: Gender: m\n", "Peter: Profession: Electrician\n", "Peter: Family: {}\n" ] } ], "source": [ "# loop in each dict\n", "for key, value in my_family.items():\n", " for k, v in value.items():\n", " print(f\"{key}: {k}: {v}\")" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{ 'James': {'Age': 25, 'Gender': 'm', 'Profession': 'Student'},\n", " 'John': {'Age': 48, 'Gender': 'm', 'Profession': 'Carpenter'},\n", " 'Peter': { 'Age': 35,\n", " 'Family': {},\n", " 'Gender': 'm',\n", " 'Profession': 'Electrician'}}\n" ] } ], "source": [ "import pprint\n", "\n", "pp = pprint.PrettyPrinter(indent=3, depth=3)\n", "\n", "pp.pprint(my_family)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "# JSON \n", "\n", "to save dictionaries, standard format for data exchange" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'John': {'Age': 48, 'Gender': 'm', 'Profession': 'Carpenter'}, 'James': {'Age': 25, 'Gender': 'm', 'Profession': 'Student'}, 'Peter': {'Age': 35, 'Gender': 'm', 'Profession': 'Electrician', 'Family': {}}}\n" ] } ], "source": [ "import json\n", "print(my_family)\n", "# öffnen eines Files\n", "with open(file=\"my_family.json\",mode = \"w+\") as fp:\n", "\n", " # speichen (schreiben) des Dicts in das File\n", " json.dump(obj = my_family,fp = fp, indent= 4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "reading a json file back into a dictionary" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{ 'James': {'Age': 25, 'Gender': 'm', 'Profession': 'Student'},\n", " 'John': {'Age': 48, 'Gender': 'm', 'Profession': 'Carpenter'},\n", " 'Peter': { 'Age': 35,\n", " 'Family': {},\n", " 'Gender': 'm',\n", " 'Profession': 'Electrician'}}\n" ] } ], "source": [ "# öffnen des JSON files\n", "import pprint\n", "pp = pprint.PrettyPrinter(depth=3, indent = 3)\n", "\n", "with open(file=\"my_family.json\", mode = \"r+\") as fp:\n", " # auslesen des Dicts\n", " my_read_dict = json.load(fp=fp)\n", "\n", "pp.pprint(my_read_dict)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "### JSON and API " ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "{ 'date': '2024-10-17',\n", " 'lat': 8.30635,\n", " 'lon': 47.05048,\n", " 'tz': '+03:00',\n", " 'units': 'metric',\n", " 'weather_overview': 'Currently, the weather is partly cloudy with a '\n", " 'temperature of 30°C and a slight breeze with a wind '\n", " 'speed of 4 meters per second. The humidity is at 40%, '\n", " 'and the visibility is at 10,000 meters. The '\n", " 'atmospheric pressure is at 1013 hPa with a dew point '\n", " 'of 15°C. The UV index is at a high level of 8, so it '\n", " 'is important to take precautions when spending time '\n", " 'outdoors. Overall, it is a pleasant day with '\n", " 'comfortable temperatures and some scattered clouds in '\n", " 'the sky. If you plan to be outside, be mindful of the '\n", " 'moderate wind speed and high UV index.'}\n", "\n", "Weather in Luzern: Currently, the weather is partly cloudy with a temperature of 30°C and a slight breeze with a wind speed of 4 meters per second. The humidity is at 40%, and the visibility is at 10,000 meters. The atmospheric pressure is at 1013 hPa with a dew point of 15°C. The UV index is at a high level of 8, so it is important to take precautions when spending time outdoors. Overall, it is a pleasant day with comfortable temperatures and some scattered clouds in the sky. If you plan to be outside, be mindful of the moderate wind speed and high UV index.\n" ] } ], "source": [ "import requests\n", "import pprint\n", "pp = pprint.PrettyPrinter(depth=3, indent = 3)\n", "\n", "# city Luzern\n", "city = \"Luzern\"\n", "lon = 47.05048 \n", "lat = 8.30635\n", "\n", "# more info under: www.openweathermap.org, the api_key is retrieved from the website after signing up\n", "api_key = \"f19b10b50f6eeed1504adad1b2a8982c\"\n", "url = f\"https://api.openweathermap.org/data/3.0/onecall/overview?lat={lat}&lon={lon}&appid={api_key}&units=metric\"\n", "\n", "response = requests.get(url)\n", "\n", "print(response)\n", "\n", "# Checking if the request was successful\n", "if response.status_code == 200:\n", " # Parsing the response as JSON\n", " data = response.json()\n", " pp.pprint(data) # Printing the response data\n", "else:\n", " print(f\"Error: {response.status_code}\")\n", "\n", "# printing the extracted text from the dictionary\n", "print(f\"\\nWeather in {city}: \", data[\"weather_overview\"])" ] } ], "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.12.7" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }