{"cells":[{"cell_type":"markdown","id":"12b02b53","metadata":{},"source":["<h2>Libraries and Packages</h2>\n","<hr>\n","<p>One of the most powerful parts of Python is the fact that there is so many libraries to import. We'll look at a few basic ones here and later we'll dig into a couple of more competent ones later; Matplotlib, Numpy and Pandas</p>\n","A quite commonly used one is <code>random</code>"]},{"cell_type":"code","execution_count":1,"id":"c913485b","metadata":{"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["HomePod\n","HomePod, AppleTV, Airpods, iPhone, iPad, Apple Watch, \n","1.840643423811781\n","A random number: 12\n"]}],"source":["#Simple random pick\n","import random\n","gadgets = [\"iPhone\",\"Apple Watch\",\"iPad\",\"AppleTV\",\"HomePod\",\"Airpods\"]\n","print(random.choice(gadgets))\n","randomGadgets = random.shuffle(gadgets)\n","for g in gadgets:\n","    print(g,end=\", \")\n","print(\"\\n\", end=\"\")\n","\n","print(random.uniform(1.2,3.7))\n","\n","print(f\"A random number: {random.randint(1,20)}\")"]},{"cell_type":"markdown","id":"3286d2ae","metadata":{},"source":["Sometimes we only need special parts of a library. When doing this, one can use the functions directly without reffering to the library."]},{"cell_type":"code","execution_count":2,"id":"598343a9","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["A random number in a Gauss Distribution with mu=5 and sigma=1.0: 4.489098359471905\n"]}],"source":["from random import gauss\n","print(f\"A random number in a Gauss Distribution with mu=5 and sigma=1.0: {gauss(5.0,2.0)}\")"]},{"cell_type":"markdown","id":"9619ef6a","metadata":{},"source":["Another really handy library is <code>statistics</code>. This time we'll set a shorter name on the library."]},{"cell_type":"code","execution_count":1,"id":"8136b7ac","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["Mean: 3.6923076923076925, Standard dev: 1.7974340685458343\n"]}],"source":["import statistics as stat\n","values = [1,4,3,5,6,7,3,4,5,2,1,3,4]\n","print(f\"Mean: {stat.mean(values)}, Standard dev: {stat.stdev(values)}\")"]},{"cell_type":"markdown","id":"1b6c9c1d","metadata":{},"source":["And why not some fractions"]},{"cell_type":"code","execution_count":1,"id":"59dccb8b","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["-8/5\n","123\n","0\n","3/7\n","-3/7\n","-1/8\n","7/1000000\n","13/24\n"]}],"source":["#Using fractions\n","from fractions import Fraction\n","print(Fraction(16, -10))\n","print(Fraction(123))\n","print(Fraction())\n","print(Fraction('3/7'))\n","print(Fraction(' -3/7 '))\n","print(Fraction('-.125'))\n","print(Fraction('7e-6'))\n","print(Fraction('3/8')+Fraction('1/6'))"]},{"cell_type":"code","execution_count":11,"id":"24637f24","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["1/2\n"]}],"source":["#Using fractions\n","from fractions import Fraction as bråk\n","print(bråk(4,8))\n"]},{"cell_type":"markdown","id":"97a1528d","metadata":{},"source":["Sometimes it's convinient to get values from the list <code>argv</code> that we find in the sys library. This is the arguments you give at the end when running the script from the terminal.\n","<br>\n","<b>One name:</b><br>\n","<img src=\"media/sysimg2.png\" width=70%>\n","<br>\n","<b>More names:</b><br>\n","<img src=\"media/sysimg1.png\" width=70%>"]},{"cell_type":"markdown","id":"656e11fb","metadata":{},"source":["<h3>Packages</h3>\n","These are libraries that are available online from third party developers. A fun one is <code>cowsay</code>. Normally this has to be installed:<br>\n","<ul>\n","<li>In normal Python: <code>pip install cowsay</code>\n","<li>In conda: <code>conda install cowsay</code>\n","</ul>"]},{"cell_type":"code","execution_count":6,"id":"41f47a2c","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["  _____\n","| Hello |\n","  =====\n","     \\\n","      \\\n","        ^__^\n","        (oo)\\_______\n","        (__)\\       )\\/\\\n","            ||----w |\n","            ||     ||\n","  _____\n","| Hello |\n","  =====\n","       \\\n","        \\\n","         \\\n","          \\\n","                                     ___-------___\n","                                 _-~~             ~~-_\n","                              _-~                    /~-_\n","            /^\\__/^\\         /~  \\                   /    \\\n","          /|  O|| O|        /      \\_______________/        \\\n","         | |___||__|      /       /                \\          \\\n","         |          \\    /      /                    \\          \\\n","         |   (_______) /______/                        \\_________ \\\n","         |         / /         \\                      /            \\\n","          \\         \\^\\\\         \\                  /               \\     /\n","            \\         ||           \\______________/      _-_       //\\__//\n","              \\       ||------_-~~-_ ------------- \\ --/~   ~\\    || __/\n","                ~-----||====/~     |==================|       |/~~~~~\n","                 (_(__/  ./     /                    \\_\\      \\.\n","                        (_(___/                         \\_____)_)\n"]}],"source":["import cowsay\n","\n","out = input(\"The cow says: \")\n","cowsay.cow(out)\n","cowsay.turtle(out)"]},{"cell_type":"markdown","id":"84604f0d","metadata":{},"source":["<h3>Application Program Interface - API, using <code>request</code></h3>\n","<p>This allows you to connect to code from others, to install this:</p>\n","<ul>\n","<li>In normal Python: <code>pip install requests</code>\n","<li>In conda: <code>conda install requests</code>\n","</ul>\n","<p>Lets try this with iTunes"]},{"cell_type":"code","execution_count":2,"id":"6623bb44","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["{'resultCount': 1, 'results': [{'wrapperType': 'track', 'kind': 'song', 'artistId': 15201848, 'collectionId': 405926181, 'trackId': 405926184, 'artistName': 'Martin Solveig & Dragonette', 'collectionName': 'Hello - Single', 'trackName': 'Hello', 'collectionCensoredName': 'Hello - Single', 'trackCensoredName': 'Hello', 'artistViewUrl': 'https://music.apple.com/us/artist/martin-solveig/15201848?uo=4', 'collectionViewUrl': 'https://music.apple.com/us/album/hello/405926181?i=405926184&uo=4', 'trackViewUrl': 'https://music.apple.com/us/album/hello/405926181?i=405926184&uo=4', 'previewUrl': 'https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview126/v4/f5/57/2a/f5572a43-d254-80f1-edd8-1051a232d64d/mzaf_4083906122883221109.plus.aac.p.m4a', 'artworkUrl30': 'https://is1-ssl.mzstatic.com/image/thumb/Music125/v4/89/77/46/897746b8-3d89-c551-4359-7aa440b67b69/mzi.clkeppje.jpg/30x30bb.jpg', 'artworkUrl60': 'https://is1-ssl.mzstatic.com/image/thumb/Music125/v4/89/77/46/897746b8-3d89-c551-4359-7aa440b67b69/mzi.clkeppje.jpg/60x60bb.jpg', 'artworkUrl100': 'https://is1-ssl.mzstatic.com/image/thumb/Music125/v4/89/77/46/897746b8-3d89-c551-4359-7aa440b67b69/mzi.clkeppje.jpg/100x100bb.jpg', 'collectionPrice': 1.29, 'trackPrice': 1.29, 'releaseDate': '2010-09-06T07:00:00Z', 'collectionExplicitness': 'notExplicit', 'trackExplicitness': 'notExplicit', 'discCount': 1, 'discNumber': 1, 'trackCount': 1, 'trackNumber': 1, 'trackTimeMillis': 281430, 'country': 'USA', 'currency': 'USD', 'primaryGenreName': 'Dance', 'isStreamable': True}]}\n"]}],"source":["import requests\n","\n","song = input(\"Enter the song you want to search for: \")\n","\n","response = requests.get(\"https://itunes.apple.com/search?entity=song&limit=1&term=\" + song)\n","print(response.json())"]},{"cell_type":"markdown","id":"8b582480","metadata":{},"source":["Lets try to make som sense of the JSON data we just got using <code>json.dumps</code>"]},{"cell_type":"code","execution_count":3,"id":"bc012588","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["{\n","  \"resultCount\": 1,\n","  \"results\": [\n","    {\n","      \"wrapperType\": \"track\",\n","      \"kind\": \"song\",\n","      \"artistId\": 15201848,\n","      \"collectionId\": 405926181,\n","      \"trackId\": 405926184,\n","      \"artistName\": \"Martin Solveig & Dragonette\",\n","      \"collectionName\": \"Hello - Single\",\n","      \"trackName\": \"Hello\",\n","      \"collectionCensoredName\": \"Hello - Single\",\n","      \"trackCensoredName\": \"Hello\",\n","      \"artistViewUrl\": \"https://music.apple.com/us/artist/martin-solveig/15201848?uo=4\",\n","      \"collectionViewUrl\": \"https://music.apple.com/us/album/hello/405926181?i=405926184&uo=4\",\n","      \"trackViewUrl\": \"https://music.apple.com/us/album/hello/405926181?i=405926184&uo=4\",\n","      \"previewUrl\": \"https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview126/v4/f5/57/2a/f5572a43-d254-80f1-edd8-1051a232d64d/mzaf_4083906122883221109.plus.aac.p.m4a\",\n","      \"artworkUrl30\": \"https://is1-ssl.mzstatic.com/image/thumb/Music125/v4/89/77/46/897746b8-3d89-c551-4359-7aa440b67b69/mzi.clkeppje.jpg/30x30bb.jpg\",\n","      \"artworkUrl60\": \"https://is1-ssl.mzstatic.com/image/thumb/Music125/v4/89/77/46/897746b8-3d89-c551-4359-7aa440b67b69/mzi.clkeppje.jpg/60x60bb.jpg\",\n","      \"artworkUrl100\": \"https://is1-ssl.mzstatic.com/image/thumb/Music125/v4/89/77/46/897746b8-3d89-c551-4359-7aa440b67b69/mzi.clkeppje.jpg/100x100bb.jpg\",\n","      \"collectionPrice\": 1.29,\n","      \"trackPrice\": 1.29,\n","      \"releaseDate\": \"2010-09-06T07:00:00Z\",\n","      \"collectionExplicitness\": \"notExplicit\",\n","      \"trackExplicitness\": \"notExplicit\",\n","      \"discCount\": 1,\n","      \"discNumber\": 1,\n","      \"trackCount\": 1,\n","      \"trackNumber\": 1,\n","      \"trackTimeMillis\": 281430,\n","      \"country\": \"USA\",\n","      \"currency\": \"USD\",\n","      \"primaryGenreName\": \"Dance\",\n","      \"isStreamable\": true\n","    }\n","  ]\n","}\n"]}],"source":["import requests\n","import json\n","\n","song = input(\"Enter the song you want to search for: \")\n","\n","response = requests.get(\"https://itunes.apple.com/search?entity=song&limit=1&term=\" + song)\n","print(json.dumps(response.json(), indent=2))"]},{"cell_type":"markdown","id":"bccd217e","metadata":{},"source":["Hmmm... lets narrow it a bit more by just getting the trackname, but also enable the user to choose number of results"]},{"cell_type":"code","execution_count":4,"id":"df4325d8","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["Martin Solveig & Dragonette :  Hello\n","Karmin :  Brokenhearted\n","Karmin :  Hello\n","Zooey Deschanel :  Hello\n","Kelly Clarkson :  Hello\n"]}],"source":["import requests\n","import json\n","\n","song = input(\"Enter the song you want to search for: \")\n","count = input(\"How nay results: \")\n","\n","response = requests.get(\"https://itunes.apple.com/search?entity=song&limit=\" + count +\"&term=\" + song)\n","tracks = response.json()\n","for result in tracks[\"results\"]:\n","    print(result[\"artistName\"],\": \",result[\"trackName\"])"]},{"cell_type":"markdown","id":"19a34a0d","metadata":{},"source":["<h3>Creating your own <code>libraries</code> </h3>\n","<p>This is a great feature for sving usable code for later use. Just create an external file(in this case mylib.py) and enter the code you want to use</p>\n","<hr>\n","<code>\n","#This is the code I've saved in the external file mylib.py:\n","</code>\n","<img src=\"media/code.png\" width=70%>\n","<hr>\n","<p>Lets try to use this by importing the library/file</p>"]},{"cell_type":"code","execution_count":16,"id":"ba71bff8","metadata":{"trusted":false},"outputs":[{"name":"stdout","output_type":"stream","text":["Hi there Pelle\n","Bye bye Pelle\n"]}],"source":["import mylib\n","person = input(\"Who are you: \")\n","mylib.hello(person)\n","mylib.bye(person)"]},{"cell_type":"markdown","id":"1738ab2a","metadata":{},"source":["We could also just import a separate function, and this way we don't need to tell the name of the library when we use the function. If we instead use <code>from mylib import *</code>. This is a bit dangerous though, it can lead to redefiniton of built in function for instance"]},{"cell_type":"code","execution_count":null,"id":"38bb5e05","metadata":{"trusted":false},"outputs":[],"source":[]},{"cell_type":"code","execution_count":17,"id":"8f73e4e2","metadata":{"trusted":false},"outputs":[],"source":["from mylib import hello, bye\n","person = input(\"Who are you: \")\n","hello(person)\n","bye(person)"]}],"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.11.4"}},"nbformat":4,"nbformat_minor":5}
