{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Data Science\n", "---\n", "\n", "Welcome to Data Science! In this notebook, you will learn how to use Jupyter Notebooks and the basics of programming in Python.\n", "\n", "*Estimated Time: 30 minutes*\n", "\n", "---\n", "\n", "**Topics Covered:**\n", "- Learn how to work with Jupyter notebooks.\n", "- Learn about variables in Python, including variable types, variable assignment, and arithmetic.\n", "- Learn about functions in Python, including defining and calling functions, as well as scope.\n", "\n", "**Parts:**\n", "- Jupyter Notebooks\n", "- Programming in Python\n", "- Variables\n", "- Functions\n", "- Scope" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jupyter Notebooks\n", "---\n", "In this section, we will learn the basics of how to work with Jupyter notebooks." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This Jupyter notebook is composed of 2 kinds of cells: markdown and code. A **markdown cell**, such as this one, contains text. A **code cell** contains code in Python, a programming language that we will be using for the remainder of this module.\n", "\n", "To run a code cell, press Shift-Enter or click Cell > Run Cells in the menu at the top of the screen. To edit a code cell, simply click in the cell and make your changes." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise\n", "\n", "Try running the code below. What happens?" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello World!\n" ] } ], "source": [ "# CODE\n", "print(\"Hello World!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's try editing the code. In the cell below, replace \"friend\" with your name for a more personalized message." ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Welcome to Jupyter notebooks, friend.\n" ] } ], "source": [ "print(\"Welcome to Jupyter notebooks, friend.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Programming in Python\n", "---\n", "Now that you are comfortable with using Jupyter notebooks, we can learn more about programming in this notebook.\n", "\n", "### What is Programming?\n", "**Programming** is giving the computer a set of step-by-step instructions to follow in order to execute a task. It's a lot like writing your own recipe book! For example, let's say you wanted to teach someone how to make a PB&J sandwich:\n", "1. Gather bread, peanut butter, jelly, and a spreading knife.\n", "2. Take out two slices of bread.\n", "3. Use the knife to spread peanut butter on one slice of bread.\n", "4. Use the knife to spread jelly on the other slice of bread.\n", "5. Put the two slices of bread together to make a sandwich.\n", "\n", "Just like that, programming is breaking up a complex task into smaller commands for the computer to understand and execute.\n", "\n", "In order to communicate with computers, however, we must talk to them in a way that they can understand us: via a **programming language**. \n", "\n", "There are many different kinds of programming languages, but we will be using **Python** because it is concise, simple to read, and applicable in a variety of projects - from web development to mobile apps to data analysis." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In programming, we often compute many values that we want to save so that we can use the result in a later step. For example, let's say that we want to find the number of seconds in a day. We can easily calculate this with the following:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
$60 * 60 * 24 = 86400$ seconds
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, let's say that your friend Alexander asked you how many seconds there are in three days. We could, of course, perform the calculation in a similar manner:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "$(60 * 60 * 24) * 3 = 259200$ seconds
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "But we see that we repeated the calculation in parentheses above. Instead of doing this calculation again, we could have saved the result from our first step (calculating the number of seconds in a day) as a variable." ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "86400" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# This is Python code that assigns variables.\n", "# The name to the left of the equals sign is the variable name.\n", "# The value to the right of the equals sign is the value of the variable.\n", "# Press Shift-Enter to run the code and see the value of our variable!\n", "\n", "seconds_in_day = 60 * 60 * 24 # This is equal to 86400.\n", "seconds_in_day" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, we can simply multiply this variable by three to get the number of seconds in *three* days:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "259200" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# The code below takes the number of seconds in a day (which we calculated in the previous code cell)\n", "# and multiplies it by 3 to find the number of seconds in 3 days.\n", "\n", "seconds_in_three_days = seconds_in_day * 3 # This is equal to 259200.\n", "seconds_in_three_days" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As you can see, variables can be used to simplify calculations, make code more readable, and allow for repetition and reusability of code. \n", "\n", "### Variable Types\n", "\n", "Next, we'll talk about a few types of variables that you'll be using. As we saw in the example above, one common type of variable is the *integer* (positive and negative whole numbers). You'll also be using decimal numbers in Python, which are called *doubles* (positive and negative decimal numbers). \n", "\n", "A third type of variable used frequently in Python is the *string*; strings are essentially sequences of characters, and you can think of them as words or sentences. We denote strings by surrounding the desired value with quotes. For example, \"Data Science\" and \"2017\" are strings, while `bears` and `2020` (both without quotes) are not strings.\n", "\n", "Finally, the last variable type we'll go over is the *boolean*. They can take on one of two values: `True` or `False`. Booleans are often used to check conditions; for example, we might have a list of dogs, and we want to sort them into small dogs and large dogs. One way we could accomplish this is to say either `True` or `False` for each dog after seeing if the dog weighs more than 15 pounds. \n", "\n", "Here is a table that summarizes the information in this section:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "|Variable Type|Definition|Examples|\n", "|-|-|-|\n", "|Integer|Positive and negative whole numbers|`42`, `-10`, `0`|\n", "|Double|Positive and negative decimal numbers|`73.9`, `2.4`, `0.0`|\n", "|String|Sequence of characters|`\"Go Bears!\"`, `\"variables\"`|\n", "|Boolean|True or false value|`True`, `False`|\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Arithmetic\n", "Now that we've discussed what types of variables we can use, let's talk about how we can combine them together. As we saw at the beginning of this section, we can do basic math in Python. Here is a table that shows how to write such operations:\n", "\n", "|Operation|Operator|Example|Value|\n", "|-|-|-|\n", "|Addition|+|`2 + 3`|`5`|\n", "|Subtraction|-|`2 - 3`|`-1`|\n", "|Multiplication|*|`2 * 3`|`6`|\n", "|Division|/|`7 / 3`|`2.66667`|\n", "|Remainder|%|`7 % 3`|`1`|\n", "|Exponentiation|**|`2 ** 0.5`|`1.41421`|\n", "\n", "In addition, you can use parentheses to denote priority, just like in math.\n", "\n", "As an exercise, try to predict what each of these lines below will print out. Then, run the cell and check your answers." ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.5\n", "5.0\n", "60\n", "0\n", "2017.0\n" ] } ], "source": [ "q_1 = (3 + 4) / 2\n", "print(q_1) # What prints here?\n", "\n", "q_2 = 3 + 4 / 2\n", "print(q_2) # What prints here?\n", "\n", "some_variable = 1 + 2 + 3 + 4 + 5\n", "q_3 = some_variable * 4\n", "print(q_3) # What prints here?\n", "\n", "q_4 = some_variable % 3\n", "print(q_4) # What prints here?\n", "\n", "step_1 = 6 * 5 - (6 * 3)\n", "step_2 = (2 ** 3) / 4 * 7\n", "q_5 = 1 + step_1 ** 2 * step_2\n", "print(q_5) # What prints here?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So far, you've learnt how to carry out basic operations on your inputs and assign variables to certain values.\n", "Now, let's try to be more efficient. \n", "\n", "Let's say we want to perform a certain operation on many different inputs that will produce distinct outputs. What do we do? We write a _**function**_.\n", "\n", "A function is a block of code which works a lot like a machine: it takes an input, does something to it, and produces an output. \n", "\n", "The input is put between brackets and can also be called the _argument_ or _parameter_. Functions can have multiple arguments.\n", "\n", "Try running the cell below after changing the variable _name_:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Edit this cell to your own name!\n", "name = \"John Doe\"\n", "\n", "# Our function\n", "def hello(name):\n", " return \"Hello \" + name + \"!\"\n", "\n", "hello(name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Interesting, right? Now, you don't need to write 10 different lines with 10 different names to print a special greeting for each person. All you need to is write one function that does all the work for you!\n", "\n", "Functions are very useful in programming because they help you write shorter and more modular code. A good example to think of is the _print_ function, which we've used quite a lot in this module. It takes many different inputs and performs the specified task, printing its input, in a simple manner.\n", "\n", "Now, let's write our own function. Let's look at the following rules: \n", "\n", "### Defining\n", "- All functions must start with the \"def\" keyword. \n", "- All functions must have a name, followed by parentheses, followed by a colon. Eg. def hello( ):\n", "- The brackets may have a variable that stores its arguments (inputs)\n", "- All functions must have a \"return\" statement which will return the output. Think of a function like a machine. When you put something inside, you want it to return something. Hence, this is very important.\n", "\n", "### Calling\n", "After you define a function, it's time to use it. This is known as _calling_ a function. \n", "\n", "To call a function, simply write the name of the function with your input variable in brackets (argument).\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Complete this function\n", "def #name(argument):\n", " return # function must return a value\n", "\n", "# Calling our function below...\n", "my_first_function(name)" ] }, { "cell_type": "markdown", "metadata": { "collapsed": true }, "source": [ "Great! Now let's do some math. Let's write a function that returns the square of the input.\n", "\n", "Try writing it from scratch!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# square function \n", "\n", "\n", "square(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Neat stuff! Try different inputs and check if you get the correct answer each time.\n", "\n", "You've successfully written your first function from scratch! Let's take this up one notch.\n", "\n", "#### The power function\n", "\n", "_pow_ is a function that takes in two numbers: x, which is the \"base\" and y, the \"power\". So when you write pow(3,2) the function returns 3 raised to the power 2, which is 3^2 = 9. \n", "\n", "Task: Write a function called _mulpowply_ which takes in three inputs (x, y, z) and returns the value of x multiplied by y to power z. Symbolically, it should return (xy)^z." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# mulpowply function\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Scope\n", "---\n", "Programming is great, but it can also be quite peculiar sometimes. For example, each variable defined outside of any functions by default, is **global**. \n", "\n", "Try executing the code below:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Global Variable - name\n", "name = \"Harry Potter\"\n", "\n", "# our function\n", "def salutation(name):\n", " return \"Hi \" + name + \", nice to meet you!\"\n", "\n", "# calling our function\n", "salutation(name)\n", "\n", "# un-comment the line below\n", "#salutation(\"Roonald Wazlib\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Even though your argument was called _name_, it didnt output Harry Potter, which was the **global** value of the variable called name. Instead, it gave preference to the **local** value which was given to the function as an argument, Roonald Wazlib. \n", "\n", "Think of it as filling your coffeemaker (function) up with coffee (variable). If you have a variable with **global** access called _name_ which is filled with coffee called Harry Potter, you can choose to either:\n", "\n", "1) Not input another value in your function. (Use the same name of the **global** variable as your argument)\n", "\n", "In this case, the **global** type of coffee will still be used. \n", "\n", "2) Choose to fill another value. In this case, your function will assign the value you pass as the argument to the “variable” which **is** the argument.\n", "\n", "Think of it as overriding your **global** coffee and putting a new type of coffee into your coffeemaker.\n", "\n", "### Activity\n", "\n", "Using the rules of scope you've learned so far, complete the function _puzzle_ to output the value **35**." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Scope Puzzle!\n", "x = 5\n", "y = 6\n", "z = 7\n", "\n", "def puzzle(x, y):\n", " return x * y\n", "\n", "# fill in this function call\n", "puzzle()\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Control\n", "---\n", "Sometimes, we want to manipulate the flow of our code. For example, we might want our code to make decisions on its own or repeat itself a certain amount of times. By implementing control structures, we can avoid redundant code and make processes more efficient.\n", "\n", "### Conditionals\n", "We use **conditionals** to run certain pieces of code _if_ something is true. For example, we should only go to the grocery store _if_ we are out of peanut butter!\n", "\n", "We use **comparators** to determine whether an expression is _true_ or _false_. There are six comparators to be aware of:\n", "1. Equal to: ==\n", "2. Not equal to: !=\n", "3. Greater than: >\n", "4. Greater than or equal to: >=\n", "5. Less than: <\n", "6. Less than or equal to: <=\n", "\n", "Let's try it out!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# EXERCISE 1\n", "# Determine whether the following will print true or false\n", "# Run the code to check your answers!\n", "\n", "print(10 == 10)\n", "\n", "print(2016 < 2017)\n", "\n", "print(\"foo\" != \"bar\")\n", "\n", "print( (1+2+3+4+5) <= (1*2*3))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# EXERCISE 2\n", "\n", "# Write an expression that evaluates to True\n", "expression1 = # YOUR CODE HERE\n", "\n", "# Write an expression that evaluates to False\n", "expression2 = # YOUR CODE HERE\n", "\n", "print(expression1)\n", "print(expression2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we know how to compare values, we can tell our computer to make decisions using the **if statement**.\n", "\n", "### If Statements\n", "An **if statement** takes the following form:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Please do not run this code, as it will error. It is provided as a skeleton.\n", "\n", "if (condition1):\n", " # code to be executed if condition1 is true\n", "elif (condition2):\n", " # code to be executed if condition2 is true\n", "else:\n", " # code to be executed otherwise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "With if statements, we can control which code is executed. Check out how handy this can be in the activity below!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# We want to make a PB&J sandwich, but things keep going wrong!\n", "\n", "# Modify the variables below so that you go grocery shopping \n", "# with no mishaps and successfully purchase some peanut butter.\n", "\n", "# Run the code when you're done to see the results.\n", "\n", "print(\"Let's make a PB&J sandwich!\")\n", "peanut_butter = 10\n", "jelly = 100\n", "gas = 60\n", "flat_tire = True\n", "\n", "if (peanut_butter < 50):\n", " print(\"Uh oh! We need more peanut butter. Must go grocery shopping...\")\n", " if (gas < 75):\n", " print(\"Oops! Your car is out of gas :(\")\n", " elif (flat_tire):\n", " print(\"Oh no! You have a flat tire :'(\")\n", " else:\n", " print(\"You made it to the grocery store and succesfully got peanut butter!\")\n", " peanut_butter = # reset the value of peanut_butter so it is 100% full again\n", "else:\n", " print(\"We have all the ingredients we need! Yummy yummy yay!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### For Loops\n", "We can also regulate the flow of our code by repeating some action over and over. Say that we wanted to greet ten people. Instead of copying and pasting the same call to _print_ over and over again, it would be better to use a **for loop**.\n", "\n", "A basic **for loop** is written in the following order:\n", "- The word \"for\"\n", "- A name we want to give each item in a sequence\n", "- The word \"in\"\n", "- A sequence (i.e. \"range(100)\" to go through numbers 0-99\n", "\n", "For example, to greet someone ten times, we could write:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Run me to see \"hello!\" printed ten times!\n", "for i in range(10):\n", " print(\"hello!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this way, for loops help us avoid redundant code and have useful capabilities.\n", "\n", "**Exercise:** Write a function that returns the sum of the first _n_ numbers, where _n_ is the input to the function. Use a for loop!" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def sum_first_n(n):\n", " # YOUR CODE HERE\n", "\n", "sum_first_n(5) # should return 1+2+3+4+5 = 15" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conclusion\n", "---\n", "Congratulations! You've successfully learnt the basics of programming: creating your own variables, writing your own functions, and controlling the flow of your code! You will apply the concepts learnt throughout this notebook in class. After delving into this notebook, you are only just getting started!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "## Bibliography" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some examples adapted from the UC Berkeley Data 8 textbook, *Inferential Thinking*.\n", "\n", "Authors:\n", "- Shriya Vohra\n", "- Scott Lee\n", "- Pancham Yadav" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python [conda root]", "language": "python", "name": "conda-root-py" }, "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.5.2" } }, "nbformat": 4, "nbformat_minor": 1 }