{ "cells": [ { "cell_type": "markdown", "metadata": { "colab_type": "text", "deletable": false, "editable": false, "id": "UHboGMaN-lUP", "nbgrader": { "checksum": "bb49bf176e542a22a73c154e2658d6ea", "grade": false, "grade_id": "cell-be04006a1edf3189", "locked": true, "schema_version": 1, "solution": false } }, "source": [ "# SSS1 | Python Basics" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "fAEzJgrrN9u9" }, "source": [ "\n", "
\n", "
\n", "

CONTENTS

\n", "
\n", "
\n", "\n", "\n", "
\n", "
\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "
\"...\"
\n", "
Hello, dear M23. Welcome to your first SSSsss!\n", "
\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Qbzsv2Cg-lUS" }, "source": [ "**Structured Study Sessions** (SSS) allow you to gain the Python skills you need for your Cornerstone courses. \n", "\n", "Every session will be divided into two sections: **Lab** (A) and **Exercise** (B). The purpose of the **Lab** section is to familiarize you with new Python skills that are needed for courses and assignments. The practice questions within the lab are your chance to experiment around to understand the material better. This portion will be usually sent out a few days earlier, so you have a chance to practice beforehand! By the end of the lab, you should have enough knowledge to complete the problems in the **Exercise** section easily.\n", "\n", "This session, you will learn basics in Python, including various data types, variables, functions. Mastery of these contents is critical for your understanding of next week's Formal Analyses in-class activities. \n", "\n", "Save your work as you go. At the end of the session, you will upload this Jupyter Notebook (a .ipynb file) to this folder [INSERT LINK]. It is not graded, simply checked for the level of completion.\n", "\n", "***Have fun and don't hesitate to ask questions!***\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Installation of required modules\n", "Run cell bellow to download and install required python module. Module will be installed automatically and you can go on next activity." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "!pip install miupload" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "bXtlsMjHG4GL" }, "source": [ "## Warm-up: Getting to know your Peer Tutors and SSS better!\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "v5HvEedkG4GL" }, "source": [ "It is time to get to know your tutors and classmates better! Throughout the semester Peer Tutors will do their best to ensure you get the most out of these sessions. \n", "
\n", "
\n", "TASK: Assign values to these variables by asking one of your tutors. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "l2VeMhAsG4GM" }, "outputs": [], "source": [ "tutor_name = \"write the name here\" \n", "tutor_country = \"\"\n", "tutor_shoe_size = 0\n", "tutor_OH_time = \"\" # Day and time when is your Peet Tutor having Office Hours" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "-155ePJn4BFg" }, "source": [ "In the next cell, assign values by referring to the SSS policies, or asking your Peer Tutors" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "z6OfK_LZNg0A" }, "outputs": [], "source": [ "undocumented_absences_allowed = 0\n", "min_late_time = 0 # How many minutes you can come late and not receive late arrival?\n", "max_late_time_allowed = 0 # How many minutes you can come late and not be marked as absent?\n", "makeup_work_needed_if_absent = None # write True or False\n", "makeup_work_due_by = 0 # How many days you have to submit makeup work?" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "qC7fey7Y4eFK" }, "source": [ "Can you guess the type of the variables above? Hint: there are integers, booleans, strings...\n", "
\n", "We will learn about variable types in this SSS. *Let's go!*" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "X-PD0Tbm-lUS" }, "source": [ "# A. Python Lab\n", "" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "ypNPy3hHG4GP" }, "source": [ "## 1. Python as a Calculator \n", " \n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "vbLFTwiZG4GQ" }, "source": [ "Python is perfect for basic calculations. Many people often use python as calculator. Apart from addition, subtraction, multiplication, and division, you can also do:\n", "
\n", "- Exponentiation: ** . This operator raises the number to its left to the power of the number to its right. For example\n", "```python\n", "print(2**5) # 2 ** 5 will give 32\n", "> 32\n", "```\n", "
\n", "- Modulo: %. This operator returns the remainder of the division of the number to the left by the number on its right. For example\n", "```python\n", "print(12 % 5) # 12 % 5 equals 2\n", "> 2\n", "```\n", "
\n", "- Integer division // This operator works like normal division but stops before decimal places. There is no rounding; decimal points are cut.\n", "For example\n", "```python\n", "print(2023 // 15) # 2023 / 15 = 13.466... \n", "> 13 # 2023 // 15 = 13\n", " # 2023 % 15 = 73\n", "```\n", "
\n", "In the cells below, try guessing the results first, and then run these cells to show the answer. You can note down your guess by commenting (#) in the cell.\n", "
\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "HBl4PZU1G4Ga" }, "source": [ "
\n", "
\"...\"
\n", " \n", "
SSSsss-tip: Use Shift + Enter to run a cell!\n", "
" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "0yZfjpyjG4GR" }, "outputs": [], "source": [ "print(10 - 2) # my guess is:\n", "print(8 + 2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "colab_type": "code", "executionInfo": { "elapsed": 802, "status": "ok", "timestamp": 1561575648341, "user": { "displayName": "Akmarzhan Abylay", "photoUrl": "", "userId": "02603803982187423252" }, "user_tz": -360 }, "id": "0uOs0oyaNg0G", "outputId": "fb8d10bd-441c-4423-a3ea-d4e0c1631e4f" }, "outputs": [], "source": [ "print(3 * 5) # my guess is:\n", "print(10 / 2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 68 }, "colab_type": "code", "executionInfo": { "elapsed": 733, "status": "ok", "timestamp": 1561575651004, "user": { "displayName": "Akmarzhan Abylay", "photoUrl": "", "userId": "02603803982187423252" }, "user_tz": -360 }, "id": "bL8tUKZcN23U", "outputId": "3482edf0-9653-4153-fa99-838a0f39e4d3" }, "outputs": [], "source": [ "print(2**5) # my guess is:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(3%2) # my guess is:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(14//5) # my guess is:" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "MmedrAY2Ng0H" }, "source": [ "#### Can you guess an output of these calculations? \n", "Do a guess before executing the cells below." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 836, "status": "ok", "timestamp": 1561575658176, "user": { "displayName": "Akmarzhan Abylay", "photoUrl": "", "userId": "02603803982187423252" }, "user_tz": -360 }, "id": "KOE1o7zyG4GV", "outputId": "934e14b4-e7f8-440d-bdb8-27f6b71819a4" }, "outputs": [], "source": [ "print(18%7) # my guess is:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 713, "status": "ok", "timestamp": 1561575660026, "user": { "displayName": "Akmarzhan Abylay", "photoUrl": "", "userId": "02603803982187423252" }, "user_tz": -360 }, "id": "CAFk80JjNg0K", "outputId": "738e24c9-b535-42d5-f000-08d778c98be1" }, "outputs": [], "source": [ "print(4**2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 729, "status": "ok", "timestamp": 1561575662061, "user": { "displayName": "Akmarzhan Abylay", "photoUrl": "", "userId": "02603803982187423252" }, "user_tz": -360 }, "id": "mPzdXPyANg0M", "outputId": "62f57433-c7df-42e8-b164-670fde2c755b" }, "outputs": [], "source": [ "print((2+3)*2)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "C2CLgzj9G4GX" }, "source": [ "Python's math **operators** follow some _order of precedence_. Parentheses () have the highest order of precedence, then exponentiation ** and then the usual mathematics order: division/multiplication --> addition/subtraction. If you are working with multiple operators, we recommend using parentheses () to make precedence explicit for your computer and other readers.\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "_d_7OS5_G4GY" }, "outputs": [], "source": [ "#Can you guess an output of these calculations? \n", "print(2*4**2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "k0C-h-zvNg0S" }, "outputs": [], "source": [ "print((3*1)**3)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "KSsfJV9rsmaf" }, "source": [ "What if some operations have the same order of precedence? Can you guess an output here?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "jSa5Qgo2smr3" }, "outputs": [], "source": [ "print(5 * 2 // 3)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "A3w3oxrPsz28" }, "source": [ "Multiplication and division have the same precedence. Simple rule to remember, if both of them are present in an expression, **left one is evaluated first** (left -> right). \n", "\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Sofw5WgDNg0U" }, "source": [ "Compared to other programming languages, Python can work with *extremely large numbers*. The only limit is the size of your RAM and probably your time.\n", "\n", "What is the largest number that you can calculate on your computer **in 10 seconds** using any math operation? **Try it and compare it with a classmate!:**\n", "\n", "To measure the time it takes to compute your number, we will use `%%time` magic command. Remember, if the code takes too much time to run, you can always click `Kernel -> Restart` in the top panel to Interrupt and Restart your notebook. Restart will keep your edits, but variables in the kernel will be cleared. Do not forget to run all cells from the top of the notebook.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%time # time will be printed after the small_number\n", "#demo calculation\n", "small_number= 2**10000\n", "print(small_number)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "eB-3hNS0Ng0U" }, "outputs": [], "source": [ "%%time\n", "\n", "my_large_num = #hint: you may want to try ** ;)\n", "print(my_large_num)\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "HWH5LBCsG4Gb" }, "source": [ "In all previous statements you also used the word `print`. These statements are called **print statements**. They print out whatever is inside the parentheses. \n", "\n", "---\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "jzuKj66B-lUU" }, "source": [ "## 2. DATA TYPES\n", "" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "CdEJLDJx-lUU" }, "source": [ "Python has some basic data types (you can also call them object types):\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "\n", "
NameTypeDescription
integersintwhole numbers, such as: 1, 20, 50
floating pointfloatdecimal point numbers: 5.1, 100.0, 9.8
stringsstrordered sequence of characters: \"hello\", \"10\"
listslistordered sequence of objects: [\"hello\", \"10\", 200.25]
dictionariesdictunordered (key:value) pairs: {'key1': value, 'name': 'peter'}
booleansboollogical value: True or False
tuplestupleordered sequence of objects (immutable): ('name', 20, 40.6)
\n", "\n", "\n", "\n", "\n", "In this lab, we will look into **strings** and **booleans**." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "2a3BbPTjG4Gd" }, "source": [ "### 2.1. Strings \n", "" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "tj9XgVWiG4Ge" }, "source": [ "In Python, a string is a sequence of characters inside quotes. The following cell prints a string:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "sR1x5IIMG4Ge" }, "outputs": [], "source": [ "print(\"Hello. This is the first SSS...\")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "vqZvXnUWG4Gh" }, "source": [ "You can also print multiple strings in a print statement" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "0YXC3KSmG4Gi" }, "outputs": [], "source": [ "print(\"1sr str\", \"\"\"2nd\"\"\", '3rd str')" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "bPhS7-KzG4Gl" }, "source": [ "It does not matter what's inside the quotes. If you see a number wrapped inside quotes, *it's still a string*. For example, the following cell prints 3 strings:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "F9x5GGDvG4Gl" }, "outputs": [], "source": [ "print(\"7\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "-ushrxPkNg0f" }, "outputs": [], "source": [ "print(\"12%\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "Hn6kCukCNg0i" }, "outputs": [], "source": [ "print(\"75.5/2\")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "0G_8uE8hPDNE" }, "source": [ "Can you guess what the following cells will print out?\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "5s5hpxwfNg0m" }, "outputs": [], "source": [ "print(\"7\" + \"Apples\" + \" + \" + \"30\" + \"Cherries\" + \" is marmalade\")\n", "#my guess is..." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "8LMn8FVIPJN5" }, "outputs": [], "source": [ "print(\"Narwhals ๐Ÿฌ\" * 3)\n", "#my guess is...." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "IVysQ2CmG4Gn" }, "source": [ "To check whether `\"7\"` is actually a string, we can use `type(\"7\")`. If it says `str` then `\"7\"` is a string indeed." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "3rOhG2O1G4Gn" }, "outputs": [], "source": [ "type(\"7\")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "HYhaVeJPGSgs" }, "source": [ "See [this DataCamp chapter](https://campus.datacamp.com/courses/data-types-for-data-science/fundamental-data-types) if you want to learn more about Python Data Types!" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Ir8Td_2z-lVG" }, "source": [ "### 2.2. Booleans\n", " \n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "Ns0SF4Ao-lVP" }, "source": [ "A **boolean expression** is an expression that evaluates to a boolean value, which can be either `True` or `False`. Python is _case-sensitive_ so make sure to capitalize these words whenever you want to use booleans!\n", "To check whether your datum is indeed boolean you can try `type(your datum)` and see!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "JaHBrUPNG4Gr" }, "outputs": [], "source": [ "type(True)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "RBKrALIKG4Gt" }, "outputs": [], "source": [ "my_decision = false\n", "type(my_decision) #can you guess a problem here? Correct it! \n", "#Remember to ask your tutors if you are stuck." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "gP1ifrhLG4Gx" }, "source": [ "The following cell prints boolean values by passing **boolean expressions** inside the parentheses. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "XiCzUhIm-lVP" }, "outputs": [], "source": [ "print(1==2) # to check whether 1 equals 2 \n", "print(1 != 2) # to check whether 1 is not equal to 2\n", "print(3<6) # to check whether 3 is less than 6 \n", "print(10>20) # to check whether 10 is larger than 20\n", "print(5<=7) # to check whether 5 is less than or equal 7\n", "print(1.5>=1.5)\n", "print(100<50)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "mgp_BoPiZE8N" }, "source": [ "This week's activity in FA class about logical equivalency introduced the `==` operator. We will build on this in next week's classes, so let's gain familiarity with these operators. Below you are given some lines of code. Guess what they print and explain your guesses. Give explanations as detailed as \"Line 1 will print True because it is true that 5 < 7\", or something like that. AFTER writing your explanations, proceed to code those lines to see if your guesses are correct. For the incorrect guesses, explain why the code printed otherwise.\n", "\n", "\n", "\n", "```python\n", "print(1 == 1)\n", "print((1+1)==2)\n", "print(15 != 4)\n", "print((100+1) != (1+100))\n", "print('monkey' == 'Monkey')\n", "print(1 != '1')\n", "print(0 == False)\n", "```\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "deletable": false, "id": "uMmHEoCtbCr9", "nbgrader": { "checksum": "032b9551934b202302bf64a3bb2da95b", "grade": true, "grade_id": "cell-3d6345851316650b", "locked": false, "points": 1, "schema_version": 1, "solution": true } }, "source": [ "YOUR ANSWER HERE" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "4FLhdVFdQ0uy" }, "outputs": [], "source": [ "#check your answers by copy-pasting these print statements here:" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "VM8erNg3-lVS" }, "source": [ "Which of the following will give `bool`? Guess, test (by coding), give your answer, and explain:\n", "```python\n", "type(true)\n", "type(4==4)\n", "type('false')\n", "type(1=3)\n", "```" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "deletable": false, "id": "hiNVzwr--lVT", "nbgrader": { "checksum": "b44351427504819c0d79a83b97f5814e", "grade": true, "grade_id": "cell-7972c8bb5fbebea4", "locked": false, "points": 1, "schema_version": 1, "solution": true } }, "source": [ "YOUR ANSWER HERE" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "1YD9hdsnQCqr" }, "outputs": [], "source": [ "#check your answers by copy-pasting these print statements here:" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "U9Y_pBCI-lVU" }, "source": [ "What will `print(type(True)==bool)` print? Explain and test out." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "deletable": false, "id": "8Ia2A3eZRAt1", "nbgrader": { "checksum": "3e6c924982e375fb3595937c24c7903b", "grade": true, "grade_id": "cell-6f94f3e758ec2d67", "locked": false, "points": 1, "schema_version": 1, "solution": true } }, "source": [ "YOUR ANSWER HERE" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "ZyxAEOkQQGXf" }, "outputs": [], "source": [ "#check your answers by copy-pasting this print statement here:" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "NK85HiZ8JIk8" }, "source": [ "---\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "dPH28kYAG4G8" }, "source": [ "## 3. LOGICAL OPERATORS: and, or, not\n", "" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "lqQIUQpR-lV-" }, "source": [ "This week you started learning formal logic in FA. Next week, you'll learn about the **logical operators** (or **\"connectives\"**) `and`, `or`, and `not`. For now, we'll briefly preview how these logical operators work in Python. Logical operators allow us to perform _boolean operations_ on values. \n", "\n", "Operator | Description\n", "--- | --- \n", "`Expression1 and Expression2` | True only if both Expressions1 and Expression2 are True\n", "`Expression1 or Expression2` | True only if at least one of the two expressions is True\n", "`not Expression` | Negate the boolean value of the expression. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "jX2KqyKL-lV-" }, "outputs": [], "source": [ "print(type('Python') == str and 5>3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "yuNuZ3IX-lWA" }, "outputs": [], "source": [ "print(False or False)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "UyPhmEbQ-lWD" }, "outputs": [], "source": [ "print(not True)" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "6M50mNwIFswe" }, "source": [ "See [this DataCamp resource](https://campus.datacamp.com/courses/intermediate-python-for-data-science/logic-control-flow-and-filtering?ex=1) if you want to learn more about Logic in Python.\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "yVEdIkSq-lWO" }, "source": [ " \n", "## 4. FUNCTIONS" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "mEKVywxDcqfO" }, "source": [ "Functions, roughly, are self-contained groups of statements that perform a single task. Functions usually take in some inputs, process them, and \"return\" a result. What's really neat about functions is that, once they are written, they can be reused over and over in a program so you won't need to rewrite your code every time! To create a function, we need the following syntax:\n", "\n", "```python\n", "def function_name(inputs): \n", " step(s) that process inputs to get desired output\n", " return output \n", "```" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "yWEWP3FzFEyb" }, "source": [ "Let's look at a simple *mathematical* function and see whether it can be implemented using a *programming* function! \n", "
\n", "Consider this simple math function: \n", "
\n", "\n", "\n", "$f(x) = 3 + x$\n", "
\n", "\n", "In the above *mathematical* function, `x` is an argument (or \"input\") that is being altered inside the function (added to 3). The key is that the function does not specify the argument just yet, it can be used with many different numerical inputs.\n", "\n", "
\n", "$f(2) = 5$\n", "
\n", "\n", "$f(100) = 103$\n", "\n", "
\n", "To translate this mathematical function into a programming function, we use the following code in Python:\n", "\n", "\n", "```python\n", "def add_three(x): \n", " result = x + 3 \n", " return result \n", "```\n", "\n", "Now, try running these cells:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "n0bjB0SEcxED" }, "outputs": [], "source": [ "def add_three(x):\n", " result = x + 3 \n", " return result" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "colab_type": "code", "executionInfo": { "elapsed": 588, "status": "ok", "timestamp": 1561793134877, "user": { "displayName": "Svitlana Midianko", "photoUrl": "https://lh3.googleusercontent.com/-t-dq6nfLiHU/AAAAAAAAAAI/AAAAAAAAABw/GS--JdaUd14/s64/photo.jpg", "userId": "08552425112971249762" }, "user_tz": -180 }, "id": "YVm_SLnpH8e7", "outputId": "2c79d35e-f822-4b01-81cf-9020f6b24600" }, "outputs": [], "source": [ "print(add_three(2))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "fVZlo8cFc3Wa" }, "source": [ "What do we mean by reusing a function? The following cells will compute new values for different arguments by reusing (or **calling**) the function `add_three`:\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "emWj_5MeIFXx" }, "outputs": [], "source": [ "print(add_three(100))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "YphMKyncIXD5" }, "outputs": [], "source": [ "print(add_three(3))" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "KzganHlqHKwD" }, "source": [ "This is your first introduction to functions, but we'll learn a lot more about functions in the coming weeks. They are used for much more than simple calculations! To get a head start, check out [this DataCamp resource](https://campus.datacamp.com/courses/python-data-science-toolbox-part-1/writing-your-own-functions?ex=1). \n", "\n", "Remember if you are stuck, don't hesitate to approach your peer tutors!" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "LfXCrY3O-lWQ" }, "source": [ "# B. Exercises\n", "\n", "\n", "## Exercise 1\n", "\n", "\n", "\n", "#### Part 1\n", "\n", "Try to **calculate** (approximately) how many seconds are left in this Minerva year (Apr 29 of 2020). Print the result. Check with your classmate the answer and discuss who may have gotten the better approximation!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "BLxTm0XcG4HY" }, "outputs": [], "source": [ "seconds = # fill in" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "8d266e8_G4Ha" }, "source": [ "#### Part 2\n", "Ask your classmate what is the temperature today. If he/she answers using Celsius degrees, convert it to Fahrenheit degrees and vice versa. Google the formula for converting it if needed! Print the result." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "kIIC-jlZG4Ha" }, "outputs": [], "source": [ "temp_celsius = # fill in\n", "\n", "temp_fahrenheit = # fill in\n", "\n", "print('Today is', temp_celsius, 'Celsius and it is equal to', temp_fahrenheit, 'Fahrenheit')" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "TPaCxcaSG4Hb" }, "source": [ "#### Part 3\n", "Search in Google how many miles away you are from your home. Then convert this number into kilometers. Print the result." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "o6oyK9r4G4Hc" }, "outputs": [], "source": [ "distance_miles = # fill in\n", "\n", "distance_kilometers = # fill in" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "E9o6OcmMG4Hd" }, "source": [ "## Exercise 2 \n", "\n", "\n", "Use Python to evaluate the following expressions. Print the results.\n", "
\n", "\n", "\n", "```\n", "- statement1: not(True and True)\n", "- statement2: True or False\n", "- statement3: not(False and True)\n", "- statement4: False and False\n", "```\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "MRnKAfvpG4He" }, "outputs": [], "source": [ "statement1 = # fill in\n", "statement2 = # fill in\n", "statement3 = # fill in\n", "statement4 = # fill in\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "OFR4jqT9K0cP" }, "source": [ "## Exercise 3" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "eUrNTqu6L6qZ" }, "source": [ "### Part 1 " ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "d5avVvA7LEJU" }, "source": [ "Write a function which would take `x` as an arument and will return the value of the following function $f(x) = 3x + 3$.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "XqPev_zRLUh0" }, "outputs": [], "source": [ "def my_function(x):\n", " # your answer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try to call (execute) your function and check the results on these inputs:\n", "```\n", "1. x = 5\n", "2. x = 3\n", "3. x = -10\n", "4. x = 16\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(my_function(5)) # should print 18\n", "print(my_function(3)) # should print 12\n", "# Fill the rest lines for x = -10 and x = 16\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "2FvYsTIbL_Th" }, "source": [ "### Part 2" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "hbxSlknlLmZe" }, "source": [ "Write a function which will take THREE numbers as arguments of the linear function $f(x) = ax + b$ and return the $f(x)$ value. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "8jsl0SJSL4Sh" }, "outputs": [], "source": [ "def linear_function(x, a, b):\n", " # your answer" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Try to call (execute) and print result of your function and check the results on these inputs:\n", "```\n", "1. x = 5; a = 10; b = 2\n", "2. x = -1; a = 5; b = 7\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Call your function and print the result\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "d_Lhcb5FD3Fy" }, "source": [ "## Reflection time!\n", "How did it go? Did you understand to all tasks easily? Do you have any questions that you are still confused about so we can help you? What are you going to ask your peer tutor about in office hours?" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "deletable": false, "id": "8FHxkpjOEZbp", "nbgrader": { "checksum": "61b4aa51acc860edea75bb5fda6e69a4", "grade": true, "grade_id": "cell-0235c9bc8594ee55", "locked": false, "points": 1, "schema_version": 1, "solution": true } }, "source": [ "YOUR ANSWER HERE" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", " Key Takeaways from Todayยดs SSS\n", "We love snakes, especially pythons! ๐Ÿ๐Ÿ๐Ÿ\n", " Python can replace your calculator. Use: + for addition, - for subtraction, * for multiplying, / for dividing, // for dividing without decimal places, % for reminder after division. \n", " Python's math operators follow some order of precedence.\n", " Python stores data in diffrent datatypes: Integers, Strings, Booleans, Lists, Tuples, Sets...\n", " String is a sequence of characters inside quotes(\" \" or ' ' or ''' ''' for multiline string)\n", " EDIT THIS CELL TO ADD YOUR TAKEAWAY!:)\n", " We use print() to display variable or result of function to user.\n", "
" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "_hCT3HhhAhhF" }, "source": [ "## Are you ready to submit your notebook?\n", "This part contains code that checks if your submission is corrected and ready to be graded by your peer tutors. Feel free to run the cell and check if everything is done. Peer tutors will run even more tests to check if your submissions are correct, but it will be very similar to this one. Remember, It is OK to submit an unfinished notebook if you worked hard during the SSS, but try to finish it in your free time or visit your peer tutor's Office Hours to get more up-to-speed and gain confidence in coding." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": {}, "colab_type": "code", "id": "At0lJe0yNg1V" }, "outputs": [], "source": [ "# PLEASE DO NOT EDIT THIS CELL\n", "\n", "# Pre-Lab Activity\n", "print (\"Testing Pre-Lab Acitivity...\")\n", "try:\n", " if (tutor_name != \"write the name here\" and tutor_country != \"\" and tutor_shoe_size > 0 and tutor_OH_time != \"\"):\n", " print(\"--->Peer Tutor Knowledge: Excelent!\")\n", " else:\n", " print(\"--->Peer Tutor Knowledge: Are your sure that you know your peer tutor?\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "try:\n", " if(makeup_work_needed_if_absent and undocumented_absences_allowed == 2 and min_late_time == 5 and max_late_time_allowed == 15):\n", " print(\"--->SSS Rules Knowledge: Very impressive!\")\n", " else:\n", " print(\"--->SSS Rules Knowledge: Please, ask your peer tutor for more details about the rules.\")\n", "\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", " # LAB Part\n", "print(\"Testing Lab Part\")\n", "try:\n", " if (my_large_num < 2**10000):\n", " print(\"--->Python as Calculator: Good job!\")\n", " else:\n", " print(\"--->Python as Calculator: Your Number could be even bigger!\")\n", "\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "try:\n", " if (not my_decision):\n", " print(\"--->Booleans: Good job!\")\n", " else:\n", " print(\"--->Booleans: You should look one more time\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "try:\n", " if (type(add_three) == function):\n", " print(\"--->Functions: Wonderful\")\n", " else:\n", " print(\"--->Functions: Please check the syntax of your function\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "# Exercises part\n", "print(\"Testing Exercises Part...\")\n", "try:\n", " if (seconds > 60*60*24*(20+31+30+31)):\n", " print(\"--->Exercise 1.1: Good Estimation\")\n", " else:\n", " print(\"--->Exercise 1.1: Your number is smaller then number of seconds in this semester, do not forget about the second semester!\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "try:\n", " if (temp_fahrenheit == ((temp_celsius * 1.8) +32)):\n", " print(\"--->Exercise 1.2: Good Conversion\")\n", " else:\n", " print(\"--->Exercise 1.2: Check your formula again!\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "try:\n", " if (distance_kilometers* 1.7 > distance_miles > distance_kilometers* 1.5):\n", " print(\"--->Exercise 1.3: Wonderful job again!\")\n", " else:\n", " print(\"--->Exercise 1.3: Check your formula one more time, maybe there is bug nearby.\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "\n", "try:\n", " if ((statement1 == False) and (statement2 == True) and (statement3 == True) and (statement4 == False)):\n", " print(\"--->Exercise 2: Good work with logic statements. In python, logic is easy, isn't it?\")\n", " else:\n", " print(\"--->Exercise 2: Please, check your logical expressions\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "\n", "try:\n", " if (my_function(0) == 3) and (my_function(100) == 303):\n", " print(\"--->Exercise 3: I like your my_function()\")\n", " else:\n", " print(\"--->Exercise 3: I double checked my calculation, but it do match with you function my_function\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")\n", "\n", "\n", "try:\n", " if (linear_function(5,10,2) == 52) and (linear_function(-1,5,7) == 2):\n", " print(\"--->Exercise 3.1: Nice linear function\")\n", " else:\n", " print(\"--->Exercise 3.1: Is your function really linear?\")\n", "except:\n", " print(\"ERROR: Have you run all cells without errors?\")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "4QYxR-sONg1X" }, "source": [ "### Thank you, now you are ready to submit!\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import miupload\n", "miupload.login_gui() # Please enter your Minerva email and activation code from email." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "miupload.submit_notebook(assignment = \"SSS1\")" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "qRedHX1GG4Hg" }, "source": [ "\n", "
\n", "
\"...\"
\n", "It was wonderful seeing you today! Come to the OH to learn more and just chat!\n", "
Also, Congrats on completing your SSS1! Do you have questions you astill confused about? Use the cell below to write any questions and we will try to address these on the next sessions or during OH.\n", "\n", "You can be as precise as you want, e.g. 'I did not why else statement should not be included'\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Use this cell to leave any comments" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "2f38b1d026f85ea511a504da619c84d1", "grade": true, "grade_id": "cell-e0b6e6863db74692", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "1968d3b2ea8071d245cb8e8dec66df7b", "grade": true, "grade_id": "cell-640fafa2c98ef67e", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "4d660372497fb14bb9bbb505db28a18a", "grade": true, "grade_id": "cell-4fd23dc7f2afb6f5", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "78f7866e6a429108131b3abc6ba9c467", "grade": true, "grade_id": "cell-36929f2b0bafc755", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "f65417d0bb412a30f7f0878945e15a09", "grade": true, "grade_id": "cell-02d336799feca0ae", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "4cb430c9f63c1f9fad8bb8486189d600", "grade": true, "grade_id": "cell-e9a2ab4db9fdea3e", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "7fc953e054c9730c887c4b13b80ffa5c", "grade": true, "grade_id": "cell-37c0f3085deac994", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "b3a99b1db93a24a3011887197a064cb9", "grade": true, "grade_id": "cell-009c7a3b936abc73", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "52ed7ea96a7708ba103d446e220f88e1", "grade": true, "grade_id": "cell-9415ea39ced078c7", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "1ec0cd9aeab67159d40de55289f17f5f", "grade": true, "grade_id": "cell-628123e2dc8ee4d9", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "deletable": false, "editable": false, "nbgrader": { "checksum": "dd3fe887332659fb3d50d24c3587db01", "grade": true, "grade_id": "cell-78b770cc28127741", "locked": true, "points": 1, "schema_version": 1, "solution": false } }, "outputs": [], "source": [] } ], "metadata": { "colab": { "collapsed_sections": [], "name": "SSS1.ipynb", "provenance": [], "version": "0.3.2" }, "kernelspec": { "display_name": "Python 3 (system-wide)", "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.6.8" }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }