{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Lecture 2B—Logic flow" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this notebook, we learn to control the logic flow. We will use `if`, `while`, `for` to create condition and iteration." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Table of Content\n", "\n", "- [if-condition](#if-condition)\n", "- [while-loop](#while-loop)\n", "- [Exercise: while-loop](#Exercise:-while-loop)\n", "- [for-loop](#for-loop)\n", "- [Exercise: for-loop](#Exercise:-for-loop)\n", "- [Range(start, end, step)](#range(start,-end,-step))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## if-condition" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Pass\n" ] } ], "source": [ "score = 61\n", "\n", "if score >= 60:\n", " print(\"Pass\")\n", "else:\n", " print(\"Fail\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let’s take a deeper look of the above code block.\n", "\n", "![Explaining indentation](indentation.png)\n", "\n", "Whenever we have logic flow that have code only execute under certain condition, we add a `:` and **indent** the following block.\n", "\n", "The **indentation** means the code _belongs to_ the condition. In this example, the `print(\"Pass\")` only execute when the condition `score >=60` meets. We can tell from the code that the line of code has **4 leading spaces**.\n", "\n", "The `print(\"Fail\")` only execute when the condition `score >=60` fails. We can tell the line of code has **4 leading spaces** under `else:` block." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the following example, we take the input and compare the input. Remember that the input value is always string. We need to type cast the input value into `int` by using `int()` function." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your age? 23\n", "You may drink, a little bit.\n", "Good bye and have a nice day.\n" ] } ], "source": [ "age = input(\"What is your age? \")\n", "\n", "if int(age) >= 18:\n", " print(\"You may drink, a little bit.\")\n", "else:\n", " print(\"Please don’t drink.\")\n", " \n", "print(\"Good bye and have a nice day.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Putting logic into function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes, the conditional checking repeats for the whole data set. We can define function to reuse the same code. For example, the following code defines a function the _return_ either \"Pass\" or \"Fail\" based on the given _score_ value." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Function is a block of code that takes **parameters** and **return** calculation result. This block of code is executed only when other line of code calls it." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def is_student_pass(score):\n", " if score >= 60:\n", " return \"Pass\"\n", " else:\n", " return \"Fail\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note the **indentation** in the above code. The whole `if` block has at least **4 leading spaces** to indiciate that block of code is under the `def is_student_pass(score):` function. The two `return` statements has 4 further leading spaces to indicate that they are under the `if score>=60:` and `else:` statement.\n", "\n", "![Explaining indentation](indentation2.png)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Fail\n" ] } ], "source": [ "result_a = is_student_pass(59)\n", "print(result_a)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Pass\n" ] } ], "source": [ "result_b = is_student_pass(61)\n", "print(result_b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can think of function as a block of coded pre-defined and stored under a name. It is like variable for a list of \"procedures\". Every time we call the function, it executes the pre-defined lines of code and **return** the calculated result." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## while-loop vs. for-loop\n", "\n", "While-loop is usually used for iteration that we don’t know the total count.\n", "\n", "For-loop is when we know the iteration count. For example, we already have the list of items. Or we already know how many times to repeat.\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## for-loop" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Apple\n", "Banana\n", "Orange\n" ] } ], "source": [ "fruits = ['Apple', 'Banana', 'Orange']\n", "\n", "for fruit in fruits:\n", " print(fruit)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let’s bring back our `is_student_pass` function we defined. We can use a for loop to get a list of Pass/Fail result." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "80: Pass\n", "59: Fail\n", "62: Pass\n", "70: Pass\n", "99: Pass\n", "40: Fail\n", "51: Fail\n" ] } ], "source": [ "def is_student_pass(score):\n", " if score >= 60:\n", " return \"Pass\"\n", " else:\n", " return \"Fail\"\n", "\n", "scores = [80, 59, 62, 70, 99, 40, 51]\n", "\n", "for score in scores:\n", " result = is_student_pass(score)\n", " print(f\"{score}: {result}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise: for-loop\n", "\n", "In this exercise, we bring back the book lists and loop books to print each details." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "books = [\n", " {'title': 'Python Tricks', 'category': 'Programming', 'price': 240},\n", " {'title': 'Python Crash Course', 'category': 'Programming', 'price': 200},\n", " {'title': 'Getting Real', 'category': 'Startup', 'price': 200}\n", "]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try to loop the books and print the title and their price. We don’t need to print the category in this exercise." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n", "None\n", "None\n" ] } ], "source": [ "for book in books:\n", " # Your code here\n", " title = None\n", " price = None\n", " print(None)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "|Expected result|\n", "|---|\n", "|Python Tricks: \\$240|\n", "|Python Crash Course: \\$200|\n", "|Getting Real: \\$200|" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## range(start, end, step)\n", "\n", "Sometimes, we don’t have the list to iterate. But we know how many steps we want to loop. In this case, we can use `range`." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "source": [ "# print(\"0-9\")\n", "for i in range(10):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "10\n" ] } ], "source": [ "# print(\"1-10\")\n", "for i in range(1,11):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "3\n", "5\n", "7\n", "9\n" ] } ], "source": [ "# print(\"1,3,5,7,9\")\n", "for i in range(1,10,2):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n", "4\n", "6\n", "8\n", "10\n" ] } ], "source": [ "# print(\"2,4,6,8,10\")\n", "for i in range(2,11,2):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code example: while-loop\n", "\n", "By combining list and while loop, we can keep appending the value to the `tasks` list until the input is \"q\". The `break` command exits the while-loop." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Please input a to-do task, or 'q' to quit. q\n", "[]\n" ] } ], "source": [ "tasks = []\n", "\n", "while True:\n", " value = input(\"Please input a to-do task, or 'q' to quit. \")\n", "\n", " if value == 'q':\n", " break\n", " \n", " tasks.append(value)\n", " \n", "print(tasks)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can tell from the indentation that line 4—9 under the `while True:` loop. Line 7 is under the `if value=='q':` loop.\n", "\n", "Keep in mind that we need to be careful when using `while True:`. the condition is always true so the loop will run forever until we meet the `break` command. If the logic we designed has flaw, the loop may never end." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercise: while-loop\n", "\n", "In this exercise, we would like to create a guest list by modifying `while` loop example given above." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[]\n" ] } ], "source": [ "guests = []\n", "\n", "# Your code here\n", "while None:\n", " value = input(\"Your text here \")\n", " if value == 'q':\n", " break\n", " \n", " None # append the value to guests\n", " \n", "print(guests)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Summary\n", "\n", "In this lesson, we learned the basic logic flow. Specifically:\n", "\n", "- if-condition\n", "- loop with or without known iteration count\n", "- while-loop\n", "- for-loop\n", "- range" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.8.5" } }, "nbformat": 4, "nbformat_minor": 2 }