{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "Lesson7-Python For Datascience-Execution-Control.ipynb", "version": "0.3.2", "provenance": [], "collapsed_sections": [ "pA8QZjLiaFqL" ], "include_colab_link": true }, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "view-in-github", "colab_type": "text" }, "source": [ "\"Open" ] }, { "metadata": { "colab_type": "text", "id": "spdivf2TMnGC" }, "cell_type": "markdown", "source": [ "# Lesson 7 Execution Control" ] }, { "metadata": { "id": "c_Id55m6Jsbu", "colab_type": "text" }, "cell_type": "markdown", "source": [ "## Pragmatic AI Labs\n", "\n" ] }, { "metadata": { "id": "e5p96AqpSDZa", "colab_type": "text" }, "cell_type": "markdown", "source": [ "![alt text](https://paiml.com/images/logo_with_slogan_white_background.png)\n", "\n", "This notebook was produced by [Pragmatic AI Labs](https://paiml.com/). You can continue learning about these topics by:\n", "\n", "* Buying a copy of [Pragmatic AI: An Introduction to Cloud-Based Machine Learning](http://www.informit.com/store/pragmatic-ai-an-introduction-to-cloud-based-machine-9780134863917)\n", "* Reading an online copy of [Pragmatic AI:Pragmatic AI: An Introduction to Cloud-Based Machine Learning](https://www.safaribooksonline.com/library/view/pragmatic-ai-an/9780134863924/)\n", "* Watching video [Essential Machine Learning and AI with Python and Jupyter Notebook-Video-SafariOnline](https://www.safaribooksonline.com/videos/essential-machine-learning/9780135261118) on Safari Books Online.\n", "* Watching video [AWS Certified Machine Learning-Speciality](https://learning.oreilly.com/videos/aws-certified-machine/9780135556597)\n", "* Purchasing video [Essential Machine Learning and AI with Python and Jupyter Notebook- Purchase Video](http://www.informit.com/store/essential-machine-learning-and-ai-with-python-and-jupyter-9780135261095)\n", "* Viewing more content at [noahgift.com](https://noahgift.com/)\n" ] }, { "metadata": { "id": "pBTeTbnRKG_k", "colab_type": "code", "colab": {} }, "cell_type": "code", "source": [ "" ], "execution_count": 0, "outputs": [] }, { "metadata": { "colab_type": "text", "id": "pA8QZjLiaFqL" }, "cell_type": "markdown", "source": [ "## 7.1 Learn to loop with for loops" ] }, { "metadata": { "colab_type": "text", "id": "kkrALu_wvRMQ" }, "cell_type": "markdown", "source": [ "### Using Loops\n", "\n", "The for loop is one of the most fundamental control structures in Python.\n", "One common pattern is to use the range function to generate a range of values, then to iterate on them." ] }, { "metadata": { "colab_type": "text", "id": "w-jc1fbg9p9q" }, "cell_type": "markdown", "source": [ "#### Using a Simple For Loop\n", "\n", "built in range() function creates an iterable" ] }, { "metadata": { "colab_type": "code", "id": "abHaxRTlth7c", "outputId": "82c8779b-8a91-428f-903f-97f2022a05a2", "colab": { "base_uri": "https://localhost:8080/", "height": 34 } }, "cell_type": "code", "source": [ "res = range(3)\n", "res" ], "execution_count": 0, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "range(0, 3)" ] }, "metadata": { "tags": [] }, "execution_count": 11 } ] }, { "metadata": { "colab_type": "code", "id": "tnUuKBtlvWz5", "outputId": "32f9f15f-2f04-4aa5-9913-4bf2a692bf4a", "colab": { "base_uri": "https://localhost:8080/", "height": 102 } }, "cell_type": "code", "source": [ "for i in range(1,6):\n", " print(i)" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n" ], "name": "stdout" } ] }, { "metadata": { "colab_type": "text", "id": "ANmx4hYRvdXF" }, "cell_type": "markdown", "source": [ "#### For loop over an iterable (list)\n", "\n", "Another common pattern is to iterate on a list (or any iterable)" ] }, { "metadata": { "colab_type": "code", "id": "K_XrmKB6vYHw", "outputId": "fb9ec401-2f76-4e22-8168-994b76f292aa", "colab": { "base_uri": "https://localhost:8080/", "height": 68 } }, "cell_type": "code", "source": [ "friends = [\"Moby\", \"Ahab\", \"Stubb\"]\n", "for friend in friends:\n", " print(f\"With friends like {friend} who needs a Yelp review?\")" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "With friends like Moby who needs a Yelp review?\n", "With friends like Ahab who needs a Yelp review?\n", "With friends like Stubb who needs a Yelp review?\n" ], "name": "stdout" } ] }, { "metadata": { "colab_type": "text", "id": "bBzfSYvQaLUk" }, "cell_type": "markdown", "source": [ "## 7.2 Repeat with while loops" ] }, { "metadata": { "colab_type": "text", "id": "UMsckwkIivgc" }, "cell_type": "markdown", "source": [ "### While Loops\n" ] }, { "metadata": { "colab_type": "code", "id": "XA-2E-uNvhUK", "outputId": "eeab10d9-78f7-452f-ea6c-6b411acf15ee", "colab": { "base_uri": "https://localhost:8080/", "height": 102 } }, "cell_type": "code", "source": [ "def sea_life():\n", " animals = [\"whale\", \"orca\",\"porpoise\", \"moby_dick\"]\n", " print(f\"There are many creatures in the sea: {len(animals)}\")\n", " for animal in animals:\n", " yield animal\n", "\n", "animals = sea_life()\n", "count = 0\n", "\n", "while next(animals) != \"moby_dick\":\n", " count +=1\n", " print(f\"hold your fire #{count}, it is just a common sea creature\")\n", "else:\n", " count +=1\n", " print(f\"Fire the harpoon, we spotted Moby Dick #{count}\")" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "There are many creatures in the sea: 4\n", "hold your fire #1, it is just a common sea creature\n", "hold your fire #2, it is just a common sea creature\n", "hold your fire #3, it is just a common sea creature\n", "Fire the harpoon, we spotted Moby Dick #4\n" ], "name": "stdout" } ] }, { "metadata": { "colab_type": "text", "id": "O4LapCrFbex3" }, "cell_type": "markdown", "source": [ "## 7.3 Learn to handle exceptions" ] }, { "metadata": { "colab_type": "text", "id": "9wWsG9Cdwme0" }, "cell_type": "markdown", "source": [ "### Try/Except\n", "\n", "There is an expression in sports, \"Always be prepared to do your best on your worst day\". Try/Except statements are similar. It is always a good idea to think about what happens when something goes wrong in code that is written. Try/Except blocks allow for this." ] }, { "metadata": { "colab_type": "text", "id": "1vlb0DVAHVHC" }, "cell_type": "markdown", "source": [ "#### Using try/except\n", "\n", "Catching a specific exception" ] }, { "metadata": { "colab_type": "code", "id": "G94tPojywjkt", "outputId": "497be1ae-13cf-413a-c810-36678758289a", "colab": { "base_uri": "https://localhost:8080/", "height": 85 } }, "cell_type": "code", "source": [ "whales = [\"Keiko\", \"Shamu\", \"Moby Dick\"]\n", "while True:\n", " try:\n", " whale = whales.pop()\n", " print(f\"I want this whale {whale}!\")\n", " except IndexError:\n", " print(\"There are no more whales to be had\")\n", " break" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "I want this whale Moby Dick!\n", "I want this whale Shamu!\n", "I want this whale Keiko!\n", "There are no more whales to be had\n" ], "name": "stdout" } ] }, { "metadata": { "colab_type": "text", "id": "YXDgzYG_H1Ke" }, "cell_type": "markdown", "source": [ "#### Logging exceptions\n", "\n", "It is a best practice to log exception blocks" ] }, { "metadata": { "id": "O9mOcKsU5EAU", "colab_type": "code", "outputId": "30bba4f9-e692-40a6-de1c-a76a3ca7415b", "colab": { "base_uri": "https://localhost:8080/", "height": 170 } }, "cell_type": "code", "source": [ "import logging\n", "\n", "whales = [\"Keiko\", \"Shamu\", \"Moby Dick\"]\n", "while True:\n", " try:\n", " whale = whales.pop()\n", " print(f\"I want this whale {whale}!\")\n", " except IndexError:\n", " logging.exception(f\"Exception Logged: There are no more tournaments\")\n", " print(\"There are no more whales to be had\")\n", " break" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "ERROR:root:Exception Logged: There are no more tournaments\n", "Traceback (most recent call last):\n", " File \"\", line 6, in \n", " whale = whales.pop()\n", "IndexError: pop from empty list\n" ], "name": "stderr" }, { "output_type": "stream", "text": [ "I want this whale Moby Dick!\n", "I want this whale Shamu!\n", "I want this whale Keiko!\n", "There are no more whales to be had\n" ], "name": "stdout" } ] }, { "metadata": { "colab_type": "text", "id": "EXsL-XdRhiQ4" }, "cell_type": "markdown", "source": [ "## 7.4 Use conditionals" ] }, { "metadata": { "colab_type": "text", "id": "88ORBTOPvyKy" }, "cell_type": "markdown", "source": [ "### Using if/else/break/continue/pass statements \n" ] }, { "metadata": { "colab_type": "text", "id": "e4RVlT2_-4Tj" }, "cell_type": "markdown", "source": [ "#### Using if/elif/else blocks\n", "If/Else statements are a common way to branch between decisions. In the example below if/elif are used to match a branch. If there are no matches, the last \"else\" statement is run." ] }, { "metadata": { "colab_type": "code", "id": "4rPN8VYgvvsL", "colab": {} }, "cell_type": "code", "source": [ "def recommended_whale(emotion):\n", " \"\"\"Recommends a whale based on emotion\"\"\"\n", " \n", " if emotion == \"angry\":\n", " print(f\"You seem very {emotion}, I have just the whale for you: Moby Dick!\")\n", " elif emotion == \"happy\":\n", " print(f\"You seem very {emotion}, I have just the whale for you: Shamu!\")\n", " else:\n", " print(f\"You seem very {emotion}, I have no whale to recommend: How about a Crocodile instead?\")" ], "execution_count": 0, "outputs": [] }, { "metadata": { "colab_type": "code", "id": "liJPIg7dv4kq", "outputId": "e3bd7464-0e5c-4fcd-d770-8abb5f66d6e3", "colab": { "base_uri": "https://localhost:8080/", "height": 34 } }, "cell_type": "code", "source": [ "recommended_whale(\"sad\")" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "You seem very sad, I have no whale to recommend: How about a Crocodile instead?\n" ], "name": "stdout" } ] }, { "metadata": { "id": "Cex2V7WFN9dz", "colab_type": "text" }, "cell_type": "markdown", "source": [ "#### Single line conditional asssigment" ] }, { "metadata": { "id": "pN0BSWFyOFNA", "colab_type": "code", "outputId": "61240197-9be2-4e41-e3cd-851cf232b8c2", "colab": { "base_uri": "https://localhost:8080/", "height": 34 } }, "cell_type": "code", "source": [ "happy = False\n", "cloudy = False\n", "\n", "happy = False if cloudy else True\n", " \n", "happy" ], "execution_count": 0, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "True" ] }, "metadata": { "tags": [] }, "execution_count": 6 } ] }, { "metadata": { "colab_type": "text", "id": "jYEv2fd4_BRO" }, "cell_type": "markdown", "source": [ "#### Using break" ] }, { "metadata": { "colab_type": "code", "id": "n6uxAIVc_B1F", "outputId": "9cb686c2-7a98-4587-f3b2-56f0ee4cf3b5", "colab": { "base_uri": "https://localhost:8080/", "height": 102 } }, "cell_type": "code", "source": [ "crew_members = 0\n", "while True:\n", " crew_members +=1\n", " print(f\"Moby Dick is attempting to eat crew member {crew_members}\")\n", " if crew_members > 3:\n", " print(f\"Moby Dick is very full, he ate {crew_members} and couldn't possibly eat any more\")\n", " break\n", " " ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "Moby Dick is attempting to eat crew member 1\n", "Moby Dick is attempting to eat crew member 2\n", "Moby Dick is attempting to eat crew member 3\n", "Moby Dick is attempting to eat crew member 4\n", "Moby Dick is very full, he ate 4 and couldn't possibly eat any more\n" ], "name": "stdout" } ] }, { "metadata": { "colab_type": "text", "id": "KB7SreVYAHsH" }, "cell_type": "markdown", "source": [ "#### Using continue" ] }, { "metadata": { "colab_type": "code", "id": "a56Y60MpAH1t", "outputId": "44c9934e-6b49-4c26-8331-395782d2cf4a", "colab": { "base_uri": "https://localhost:8080/", "height": 34 } }, "cell_type": "code", "source": [ "whales = [\"Keiko\", \"Shamu\", \"Moby Dick\"]\n", "for whale in whales:\n", " if not whale == \"Moby Dick\":\n", " continue\n", " print(f\"My favorite whale is {whale}\")" ], "execution_count": 0, "outputs": [ { "output_type": "stream", "text": [ "My favorite whale is Moby Dick\n" ], "name": "stdout" } ] }, { "metadata": { "colab_type": "text", "id": "PgcB-3dUB2I4" }, "cell_type": "markdown", "source": [ "#### Using pass\n", "\n", "The pass keyword is often a placeholder to define a class or function" ] }, { "metadata": { "colab_type": "code", "id": "SsucVX0JB2Pe", "outputId": "72578bae-e1d6-4935-befb-aa9580f102b9", "colab": { "base_uri": "https://localhost:8080/", "height": 130 } }, "cell_type": "code", "source": [ "def my_func(): pass\n", "\n", "\n", "my_func()" ], "execution_count": 0, "outputs": [ { "output_type": "error", "ename": "IndentationError", "evalue": "ignored", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m4\u001b[0m\n\u001b[0;31m my_func()\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n" ] } ] }, { "metadata": { "id": "nRn_iPJqNrFu", "colab_type": "code", "outputId": "bc55f73d-15de-4c50-c4a2-25c8b39d4d21", "colab": { "base_uri": "https://localhost:8080/", "height": 34 } }, "cell_type": "code", "source": [ "class SomeClass: pass\n", "\n", "some_class = SomeClass()\n", "\n", "some_class" ], "execution_count": 0, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "<__main__.SomeClass at 0x7fbdeb4e2a90>" ] }, "metadata": { "tags": [] }, "execution_count": 11 } ] } ] }