{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Assignment work SW07 - PYTHON BASICS \n", "\n", "These are the self-study tasks for the semester week, which you will solve within a week in your JupyterHub environment. After completing your work, download a copy of the Jupyter notebook file locally to your laptop (right-click on the file in the JupyterHub file browser -> Download).\n", "\n", "On ILIAS you will find the corresponding scheduled work assignments every week, where you will upload your solved Jupyter notebook file. After you have submitted your work, you will receive a corresponding sample solution for the work assignment. Your submission will not be corrected. Although the work assignments are marked \"mandatory\", there are no tests in the module. The grades from the tests during the semester count.\n", "\n", "We wish you much success!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "## Task 1 - Product of digits \n", "\n", "Write a program that reads an N-digit integer from the console and returns the product of the digits as an integer.\n", "To do this, implement a function that you call with the number input.\n", "\n", "The output on the console after entering e.g. **1234** should look something like this:\n", "\n", "```\n", "the product of the digits of the number 1234 is: 24\n", "```" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The product of the digits of the number -1234 is: -24\n" ] } ], "source": [ "nr = input(\"Write any number: \")\n", "\n", "def reader(nr):\n", " res = 1\n", " if nr[0] == \"-\":\n", " is_negative = True\n", " nr = nr[1:]\n", " else:\n", " is_negative = False\n", "\n", " nr_splitted = list(nr)\n", " for j in nr_splitted:\n", " res *= int(j)\n", "\n", " if is_negative:\n", " res *= -1\n", "\n", " return res\n", "\n", "print(f\"The product of the digits of the number {nr} is: {reader(nr)}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "## Task 2 - Lotto numbers \n", "\n", "Write a function ```gen_lottonumbers(low:int, high:int, numbers:int)->list:``` in Python, which returns a list of 6 different lottery numbers sorted in the range 1 to 42. Then call this function and return the list on the console\n", "\n", "*Tip: Use the sample function (or alternatively the randrange function) from the random module*\n", "\n", "The output on the console should appear as follows (with randomly generated numbers):\n", "```python\n", "[8, 17, 22, 29, 39, 41]\n", "```" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 15, 17, 21, 35, 37]\n" ] } ], "source": [ "from random import sample\n", "\n", "numbers = int(input(\"Amount of numbers to be extracted: \"))\n", "\n", "def gen_lottonumbers(low:int,high:int,numbers:int)->list:\n", " i = sample(range(low,high+1), k=numbers)\n", " print(sorted(i))\n", " \n", "gen_lottonumbers(1,42,numbers)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "## Task 3 - simplest password generator \n", "\n", "You write a simple password generation function ```def gen_password(word:str)->str:```, which replaces all vowels in the parameter ```word``` with a randomly chosen special character from the list ```special_chars = ['@', '#', '$', '%', '&', '*', '!', '?', '~']```. To do this, use the function ```random.choice()```. At the end, return the newly generated word. Call the function with different words and return these new words on the console.\n", "\n", "A call with **ThomaS** could look like this on the console:\n", "```\n", "ThomaS -> Th@m%S\n", "```\n", "\n", "*Note: this password generation function is only of didactic value ;-)*" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Th$m?S\n" ] } ], "source": [ "from random import choice\n", "\n", "special_chars = ['@', '#', '$', '%', '&', '*', '!', '?', '~']\n", "word = input(\"Write a password: \")\n", "\n", "def gen_password(word:str)->str:\n", " vowels = [\"a\",\"e\",\"i\",\"o\",\"u\"]\n", " psw_list,psw_string = [],str()\n", " for i in word:\n", " if i in vowels:\n", " i = choice(special_chars)\n", " psw_list.append(i)\n", " final = psw_string.join(psw_list)\n", " return final\n", "\n", "print(gen_password(word))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "## Task 4 - Request UV Index \n", "\n", "The following Python code is given, which retrieves the current weather data from a city - here London - and returns it as JSON or a dictionary.\n", "\n", "Write a program based on the code specification that asks the user to enter a city and outputs the city name with the current temperature, the sky coverage in % and the UV index on the console, such as:\n", "\n", "```\n", "In Stans the temperature is 24°, the sky is covered with 0% of clouds and UV index: 6\n", "```\n" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{ 'current_condition': [ { 'FeelsLikeC': '11',\n", " 'FeelsLikeF': '53',\n", " 'cloudcover': '50',\n", " 'humidity': '77',\n", " 'localObsDateTime': '2024-11-04 04:23 PM',\n", " 'observation_time': '04:23 PM',\n", " 'precipInches': '0.0',\n", " 'precipMM': '0.0',\n", " 'pressure': '1024',\n", " 'pressureInches': '30',\n", " 'temp_C': '12',\n", " 'temp_F': '54',\n", " 'uvIndex': '0',\n", " 'visibility': '10',\n", " 'visibilityMiles': '6',\n", " 'weatherCode': '116',\n", " 'weatherDesc': [...],\n", " 'weatherIconUrl': [...],\n", " 'winddir16Point': 'E',\n", " 'winddirDegree': '83',\n", " 'windspeedKmph': '8',\n", " 'windspeedMiles': '5'}],\n", " 'nearest_area': [ { 'areaName': [...],\n", " 'country': [...],\n", " 'latitude': '51.517',\n", " 'longitude': '-0.106',\n", " 'population': '7421228',\n", " 'region': [...],\n", " 'weatherUrl': [...]}],\n", " 'request': [{'query': 'Lat 51.51 and Lon -0.13', 'type': 'LatLon'}],\n", " 'weather': [ { 'astronomy': [...],\n", " 'avgtempC': '11',\n", " 'avgtempF': '53',\n", " 'date': '2024-11-04',\n", " 'hourly': [...],\n", " 'maxtempC': '14',\n", " 'maxtempF': '58',\n", " 'mintempC': '9',\n", " 'mintempF': '49',\n", " 'sunHour': '9.3',\n", " 'totalSnow_cm': '0.0',\n", " 'uvIndex': '0'},\n", " { 'astronomy': [...],\n", " 'avgtempC': '12',\n", " 'avgtempF': '54',\n", " 'date': '2024-11-05',\n", " 'hourly': [...],\n", " 'maxtempC': '16',\n", " 'maxtempF': '60',\n", " 'mintempC': '10',\n", " 'mintempF': '50',\n", " 'sunHour': '8.8',\n", " 'totalSnow_cm': '0.0',\n", " 'uvIndex': '0'},\n", " { 'astronomy': [...],\n", " 'avgtempC': '13',\n", " 'avgtempF': '55',\n", " 'date': '2024-11-06',\n", " 'hourly': [...],\n", " 'maxtempC': '16',\n", " 'maxtempF': '61',\n", " 'mintempC': '11',\n", " 'mintempF': '51',\n", " 'sunHour': '9.0',\n", " 'totalSnow_cm': '0.0',\n", " 'uvIndex': '0'}]}\n" ] } ], "source": [ "# this code is given\n", "import requests\n", "import pprint\n", "pp = pprint.PrettyPrinter(depth=3, indent = 3)\n", "\n", "# Stadtname\n", "city = \"London\"\n", "# URL des Webservices, der das Wetter liefert\n", "url = f\"https://wttr.in/{city}?format=j1\"\n", "\n", "# Anfrage an den Webservice senden\n", "response = requests.get(url)\n", "\n", "# Überprüfen, ob die Anfrage erfolgreich war\n", "if response.status_code == 200:\n", " # JSON-Antwort parsen\n", " data = response.json()\n", "else:\n", " print(\"Fehler bei der Anfrage:\", response.status_code)\n", "\n", "pp.pprint(data)" ] }, { "cell_type": "code", "execution_count": 137, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "In Bellinzona the temperature is 9°C, the sky is covered with 0% of clouds and UV index: 0\n" ] } ], "source": [ "city = input(\"Insert a city: \")\n", "url = f\"https://wttr.in/{city}?format=j1\"\n", "response = requests.get(url)\n", "\n", "if response.status_code == 200:\n", " # JSON-Antwort parsen\n", " data = response.json()\n", "\n", " temp = data[\"current_condition\"][0][\"temp_C\"]\n", " cloudcover = data[\"current_condition\"][0][\"cloudcover\"]\n", " uvIndex = data[\"current_condition\"][0][\"uvIndex\"]\n", "\n", " print(f\"In {city} the temperature is {temp}°C, the sky is covered with {cloudcover}% of clouds and UV index: {uvIndex}\")\n", "else:\n", " print(\"Fehler bei der Anfrage:\", response.status_code)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*** \n", "end " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{ 'age': 21,\n", " 'education': {'degree': 'Engineering', 'university': 'HSLU'},\n", " 'hobbies': ['drums', 'rock music'],\n", " 'name': 'Matteo'}\n" ] } ], "source": [ "import pprint\n", "\n", "# Sample nested data structure\n", "data = {\n", " \"name\": \"Matteo\",\n", " \"age\": 21,\n", " \"hobbies\": [\"drums\", \"rock music\"],\n", " \"education\": {\n", " \"degree\": \"Engineering\",\n", " \"university\": \"HSLU\"\n", " }\n", "}\n", "\n", "# Creating a PrettyPrinter object\n", "pp = pprint.PrettyPrinter(indent=1)\n", "pp.pprint(data)" ] } ], "metadata": { "kernelspec": { "display_name": "base", "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.4" } }, "nbformat": 4, "nbformat_minor": 4 }