{ "cells": [ { "cell_type": "markdown", "metadata": { "hide_cell": true }, "source": [ "Make me look good. Click on the cell below and press Ctrl+Enter." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "hide_cell": true }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.core.display import HTML\n", "HTML(open('css/custom.css', 'r').read())" ] }, { "cell_type": "markdown", "metadata": { "hide_cell": true }, "source": [ "
SM286D · Introduction to Applied Mathematics with Python · Spring 2020 · Uhan
\n", "\n", "
Lesson 1.
\n", "\n", "

Introduction to Jupyter and Python

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## This lesson..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- The Jupyter environment\n", "- Variables and simple data types:\n", " - Variables\n", " - Comments\n", " - Numbers, strings (and f-strings), lists\n", " - Indexing strings and lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is Jupyter?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- __Jupyter__ is an interactive computational environment where you can combine code, text and graphs in __notebooks__.\n", "\n", "- You're looking at a Jupyter notebook right now!\n", "\n", "- Until recently, Jupyter was called __IPython Notebook__. This historical tidbit might help if you're looking for other references.\n", "\n", "- We'll be using Jupyter with the __Python__ programming langugage in this course." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Structure of a notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- A notebook consists of a sequence of __cells__ of different types.\n", "\n", "- We'll use these types of cells frequently:\n", " * code cells\n", " * Markdown cells\n", " \n", "- You can determine the type of a cell in the toolbar.\n", "\n", "- You can run a cell by:\n", " - clicking the Run button in the tool bar,\n", " - selecting __Cell → Run Cells__ in the menu bar,\n", " - pressing Shift+Enter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Code cells" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- In a __code cell__, you can edit and write Python code.\n", "\n", "- Let's write some Python code that prints a friendly message:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world!\n" ] } ], "source": [ "print('Hello world!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- The `print()` function prints to the screen whatever is inside the parentheses.\n", "\n", "- Note that a code cell has \n", " - an __input__ section containing your code, \n", " - an __output__ section after executing the cell." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Markdown cells" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- In a __Markdown cell__, you can enter text to write notes about your code and document your workflow.\n", "\n", "- For example, this cell is a Markdown cell.\n", "\n", "- The __Markdown__ language is a popular way to provide formatting (e.g. bold, italics, lists) to plain text. Use Google to find documentation and tutorials. [Here's a pretty good cheat sheet.](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet)\n", "\n", "- For now, here are a few basic, useful Markdown constructs:\n", "\n", "```\n", "You can format text as italic with *asterisks* or _underscores_.\n", "\n", "You can format text as bold with **double asterisks** or __double underscores__.\n", "\n", "To write an bulleted list, use *, -, or + as bullets, like this:\n", "\n", "* One\n", "* Two\n", "* Three\n", "```\n", "\n", "- To edit a Markdown cell, double-click it. When you're done editing it, run the cell. \n", "\n", "- Try it in the cell below:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*Double-click to edit this cell. Try out Markdown here.*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Manipulating cells" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- You can insert a new cell by selecting __Insert → Insert Cell Above/Below__ in the menu bar.\n", "\n", "- You can copy and paste cells using the __Edit__ menu.\n", "\n", "- You can also split, merge, move, and delete cells using the __Edit__ menu." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Saving your notebook" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Jupyter autosaves your notebook every few minutes.\n", "\n", "- To manually save, click the icon in the toolbar, or select __File → Save and Checkpoint__.\n", "\n", "- To close the notebook, select __File → Close and Halt__.\n", " - You should always close the notebook this way!\n", " - Just closing the tab/window will leave the notebook running in the background.\n", " - You can get a list of running notebooks in the __Running__ tab of the Jupyter dashboard (the main Jupyter screen)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Moving on..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- We'll go over some other features of Jupyter later.\n", "\n", "- [The official documentation is here.](http://jupyter-notebook.readthedocs.io/en/latest/)\n", "\n", "- There are many resources out there on using Jupyter — Google is your friend!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## First steps in Python: Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Up above, we wrote the following code:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world!\n" ] } ], "source": [ "print('Hello world!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- A __variable__ is a label that is assigned to a __value__, or some piece of information.\n", "\n", "- We can define a variable using the `=` sign.\n", "\n", "- Using variables, we can accomplish the same thing as the code above:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hello world!\n" ] } ], "source": [ "message = 'Hello world!'\n", "print(message)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Note that `print()` prints the value of a variable.\n", "\n", "- We can change the value of a variable at any time.\n", "\n", "- Variables are important because they allow us to represent information in a flexible way." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## An important aside: comments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- A __comment__ allows us to write notes to ourselves or others in our code.\n", "\n", "- As our code becomes more complicated, it'll be very useful to add comments that describe what our code is doing.\n", "\n", "- In Python, the hash mark (`#`) indicates a comment.\n", "\n", "- Anything following a hash mark in your code is ignored by Python." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is not a comment. Python will run this line of code.\n" ] } ], "source": [ "# This is a comment. Python will not try to run this line of code.\n", "print(\"This is not a comment. Python will run this line of code.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- An __integer__ is a whole number.\n", "\n", "- A __float__ is any number with a decimal point.\n", "\n", "- Python differentiates between integers and floats.\n", " - Every programming language must be carefully designed to properly manage decimal numbers.\n", " \n", "- We can use the `type()` function to check the type of a number." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# What is the type of 7?\n", "print(type(7))" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "# What is the type of 2.3?\n", "print(type(2.3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* We can perform basic arithmetic operations with numbers:\n", "\n", "| Symbol | Operation | Example |\n", "|--------|----------------|-------------|\n", "| * | Multiplication | `15 * 7` |\n", "| / | Division | `33 / 15` |\n", "| + | Addition | `3.7 + 4.4` |\n", "| - | Subtraction | `10 - 5` |\n", "| ** | Exponentiation | `2**4` |\n", "| % | Mod | `20 % 8` |" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "105\n" ] } ], "source": [ "# What is 15 times 7?\n", "print(15 * 7)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "8.100000000000001\n" ] } ], "source": [ "# What is 3.7 plus 4.4?\n", "print(3.7 + 4.4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Sometimes you get an arbitrary number of decimal places when doing math with floats.\n", " - Don't worry about this for now. It turns out that having computers properly manage decimal numbers is difficult.\n", "\n", "- Python defaults to a float in any operation that uses a float, even if the output is a whole number." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Using variables to represent numbers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- You can use variables to represent numbers, and then perform arithmetic operations on variables.\n", "\n", "- Let's find the area of a rectangle:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1200\n" ] } ], "source": [ "# Define dimensions of a rectangle\n", "length = 30\n", "width = 40\n", "\n", "# Compute area\n", "area = length * width\n", "\n", "# Print area\n", "print(area)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- If you try to access a variable you haven't yet defined, Python will complain." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'volume' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mvolume\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'volume' is not defined" ] } ], "source": [ "print(volume)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Let's define the height of a box, so we can compute volume." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "12000\n" ] } ], "source": [ "# Define height of box\n", "height = 10\n", "\n", "# Compute volume\n", "volume = length * width * height\n", "\n", "# Print volume\n", "print(volume)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Note that the __prompt numbers__ next to the code cells (e.g. `In [3]` and `Out [3]`) indicate which cells have been run and in which order. \n", "\n", "* This is very useful, especially if you are running cells out-of-sequence." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Quick check.__ What does the following code output?\n", "\n", "```\n", "print(type(volume))\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Write your notes here. Double-click to edit._" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- __Strings__ are lists of printable characters defined using either double quotes or single quotes.\n", "\n", "- For example:\n", "\n", "```\n", "\"This is a string.\"\n", "'This is also a string.'\n", "```" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is a string.\n", "This is also a string.\n" ] } ], "source": [ "# Define two variables assigned to strings\n", "test_string_1 = \"This is a string.\"\n", "test_string_2 = 'This is also a string.'\n", "\n", "# Print the type of these two variables\n", "print(test_string_1)\n", "print(test_string_2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* What do you think will happen if we add two strings, like this?\n", "\n", "```\n", "'Scooby Doo! ' + 'Where are you??'\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Write your notes here. Double-click to edit._" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Scooby Doo! Where are you??\n" ] } ], "source": [ "# Try it out!\n", "print('Scooby Doo! ' + 'Where are you??')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* A __method__ is an action that Python can perform on a piece of data.\n", "\n", "* Strings have many methods. For example, we can change the case of the words in a string:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "NELSON UHAN\n", "nelson uhan\n" ] } ], "source": [ "# Define a variable assigned to my name\n", "my_name = 'nelson uhan'\n", "\n", "# Make this string all uppercase\n", "print(my_name.upper())\n", "\n", "# Make this string all lowercase\n", "print(my_name.lower())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Another important aside: the Python documentation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- The official Python documentation is [here](https://docs.python.org/3.7).\n", " - You can also find this link on the [class website](https://www.usna.edu/users/math/uhan/sm286d).\n", "\n", "- The official documentation can be intimidating to read and navigate at first.\n", "\n", "- You may find your textbook easier to use, especially in the beginning.\n", "\n", "- Google can also be quite helpful 🙂" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- You can find the official Python documentation on string methods [here](https://docs.python.org/3.7/library/stdtypes.html#string-methods).\n", "\n", "- Click on the link. What does the `.title()` method do to a string?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Write your notes here. Double-click to edit._" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## f-strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- You can use insert the value of a variable into a string like this:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My neighbor is Nelson.\n" ] } ], "source": [ "# Define a variable for your neighbor's name\n", "neighbor = 'Nelson'\n", "\n", "# Print the value of the 'neighbor' variable\n", "print(f'My neighbor is {neighbor}.')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* To insert a variable's value into a string:\n", " - place the letter `f` immediatley before the opening quotation mark\n", " - put braces around the names of any variables you want to use inside the string\n", " \n", "* These strings are called __f-strings__" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Example.__ Define three variables, `left`, `right`, `me`, containing the names of your neighbors and yourself. Use the `print()` function to print the values of these variables in one line." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm Nelson, my neighbor to the left is Alice, and my neighbor to the right is Carol.\n" ] } ], "source": [ "# Define variables\n", "left = 'Alice'\n", "right = 'Carol'\n", "me = 'Nelson'\n", "\n", "# Print values of variables\n", "print(f\"I'm {me}, my neighbor to the left is {left}, and my neighbor to the right is {right}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- A __list__ is a collection of items that are organized in a particular order.\n", "\n", "- You can think of a list as an array or a vector.\n", "\n", "- A list is written as a sequence of comma-separated items between square brackets." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "# Define a list containing the first 5 square numbers\n", "squares = [0, 1, 4, 9, 16]\n", "\n", "# Define a list containing the days of the week\n", "days_of_the_week = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Lists have methods too. \n", "\n", "- What do you think the following code does?\n", "\n", "```\n", "squares.reverse()\n", "print(squares)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Write your notes here. Double-click to edit._" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[16, 9, 4, 1, 0]\n" ] } ], "source": [ "# Try it out!\n", "squares.reverse()\n", "print(squares)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* What do you think the following code does?\n", "\n", "```\n", "days_of_the_week.sort()\n", "print(days_of_the_week)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Write your notes here. Double-click to edit._" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['Fri', 'Mon', 'Sat', 'Sun', 'Thu', 'Tue', 'Wed']\n" ] } ], "source": [ "# Try it out!\n", "days_of_the_week.sort()\n", "print(days_of_the_week)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* You can find the length of a list with the `len()` function:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n" ] } ], "source": [ "# How many days of the week are there?\n", "print(len(days_of_the_week))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* You can also find the sum of a list of numbers with the `sum()` function:" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "30\n" ] } ], "source": [ "# What is the sum of the first 5 square numbers?\n", "print(sum(squares))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Indexing lists and stings\n", "\n", "* __In Python, indexing (that is, counting) starts at 0!__\n", "\n", "* Suppose we defined a variable assigned to a string like this:\n", "\n", "```\n", "x = 'Python'\n", "```\n", "\n", "* Then we can access the $n$th character of the string like this: \n", "\n", "| Index | 0 | 1 | 2 | 3 | 4 | 5 |\n", "|---------|--------|--------|--------|--------|--------|--------|\n", "| Value | `'P'` | `'y'` | `'t'` | `'h'` | `'o'` | `'n'` |\n", "| How to access | `x[0]` | `x[1]` | `x[2]` | `x[3]` | `x[4]` | `x[5]` |" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "P\n", "h\n" ] } ], "source": [ "# Define a variable assigned to a string\n", "x = 'Python'\n", "\n", "# Print the 1st character of the string\n", "print(x[0])\n", "\n", "# Print the 4th character of the string\n", "print(x[3])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Similarly, we can access the $n$th item of a list. For example:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Thu\n" ] } ], "source": [ "# Define (again) a list containing the days of the week\n", "days_of_the_week = [\"Sun\", \"Mon\", \"Tue\", \"Wed\", \"Thu\", \"Fri\", \"Sat\"]\n", "\n", "# Print the 5th day of the week\n", "print(days_of_the_week[4])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Yet another important aside: rules for naming variables\n", "\n", "- Variable names can only contain letters, numbers, and underscores.\n", "\n", "- Variable names cannot start with a number.\n", "\n", "- Spaces are not allowed! Use underscores instead.\n", "\n", "- Avoid using Python keywords and function names — these are words that Python has reserved for a particular programmatic purpose.\n", " - For example, don't define a variable called `print` — how will Python know if you want to use the `print()` function or your variable called `print`?\n", " - [List of Python keywords](https://www.w3schools.com/python/python_ref_keywords.asp)\n", "\n", "- Variable names should be short but descriptive.\n", " - `name` is better than `n`\n", " - `student_name` is better than `s_n`\n", " - `name_length` is better than `length_of_persons_name`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Classwork — on your own!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 1.__ (PCC 2-4: Name Cases) Store a person’s name in a variable, and then print that person’s\n", "name in lowercase, uppercase, and titlecase." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "nelson uhan\n", "NELSON UHAN\n", "Nelson Uhan\n" ] } ], "source": [ "# Write your code here\n", "my_name = 'nelson uhan'\n", "\n", "# Lowercase\n", "print(my_name.lower())\n", "\n", "# Uppercase\n", "print(my_name.upper())\n", "\n", "# Titlecase\n", "print(my_name.title())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 2.__ (PCC 2-7: Stripping Names) First, read about whitespace on page 22 of PCC.\n", "\n", "Store a person’s name, and include some whitespace characters at the beginning and end of the name. Make sure you use each character combination, `\\t` and `\\n`, at least once. Print the name once, so the whitespace around the name is displayed. Then print the name using each of the three stripping functions, `lstrip()`,\n", "`rstrip()`, and `strip()`." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "With all whitespace:\n", " Nelson\tUhan \n", "\n", "With lstrip():\n", "Nelson\tUhan \n", "\n", "With rstrip():\n", " Nelson\tUhan\n", "With strip():\n", "Nelson\tUhan\n" ] } ], "source": [ "# Write your code here\n", "my_name = ' Nelson\\tUhan \\n'\n", "\n", "# Print with whitespace\n", "print(\"With all whitespace:\")\n", "print(my_name)\n", "\n", "# Print with stripping functions\n", "print(\"With lstrip():\")\n", "print(my_name.lstrip())\n", "\n", "print(\"With rstrip():\")\n", "print(my_name.rstrip())\n", "\n", "print(\"With strip():\")\n", "print(my_name.strip())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 3.__ The drug company Mylan manufactures, markets, and sells EpiPens in the U.S. market. EpiPens, as displayed below, provide an easy-to-use auto-injector, which enables untrained staff or even children to deliver life-saving medicine in the event of a severe allergic reaction. \n", "\n", "In 2004, a pack of 2 EpiPens sold for \\\\$57. Mylan has been raising the price of EpiPens each year and in 2016, one purchaser paid \\\\$600 per pack. Congress is getting involved and public anger is being trained on Mylan, which seems to be profiteering from its position as the only U.S. provider of this kind of device.\n", "\n", "Find the change in price, the percentage increase in price, and compute the yearly rate of inflation (as percentage increase). What assumptions are you making in your calculation? \n", "\n", "" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Change in price = 543\n", "Percentage change in price = 852.6315789473686 %\n", "Yearly inflation rate = 65.58704453441297 %\n" ] } ], "source": [ "# Write your code here\n", "# Define variables for prices in 2004 and 2016\n", "price_2004 = 57\n", "price_2016 = 600\n", "\n", "# Change in price\n", "price_change = price_2016 - price_2004\n", "print(f'Change in price = {price_change}')\n", "\n", "# Percentage increase in price\n", "pct_price_change = ((price_2016 - price_2004) / price_2004 - 1) * 100\n", "print(f'Percentage change in price = {pct_price_change} %')\n", "\n", "# Yearly rate of inflation\n", "yearly_inflation_rate = pct_price_change / (2016 - 2004 + 1)\n", "print(f'Yearly inflation rate = {yearly_inflation_rate} %')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Write your assumptions here. Double-click to edit._\n", "\n", "In the above calculations, we are assuming that the price changes linearly from year-to-year." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 4.__ (Adapted from a problem due to John Dalbey at CalPoly) A cyclist is coasting on a level road. The cyclist's initial speed is 10 miles/hour. After coasting for 1 minute, the cyclist's final speed is 2.5 miles/hour. The rate of acceleration $a$ can be computed using the formula:\n", "\n", "\\begin{equation*}\n", "a = \\frac{V_\\text{final} -V_\\text{initial}}{\\text{duration}}.\n", "\\end{equation*}\n", "\n", "Compute the acceleration of the cyclist." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Acceleration = -450.0 miles / hour squared\n" ] } ], "source": [ "# Write your code here\n", "# Define problem data\n", "v_initial = 10\n", "v_final = 2.5\n", "duration = 1 / 60 # in hours\n", "\n", "# Compute acceleration\n", "acceleration = (v_final - v_initial) / duration\n", "print(f'Acceleration = {acceleration} miles / hour squared')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 5.__ (PCC 3-8: Seeing the World) \n", "\n", "First, read pages 43-45 in PCC to learn about sorting lists temporarily vs. permanently.\n", "\n", "Think of at least five places in the world you’d like to visit.\n", "\n", "- Store the locations in a list. Make sure the list is not in alphabetical order.\n", "- Print your list in its original order. Don’t worry about printing the list neatly, just print it as a raw Python list.\n", "- Use `sorted()` to print your list in alphabetical order without modifying the actual list.\n", "- Show that your list is still in its original order by printing it.\n", "- Use `sorted()` to print your list in reverse alphabetical order without changing the order of the original list.\n", "- Show that your list is still in its original order by printing it again.\n", "- Use `reverse()` to change the order of your list. Print the list to show that its order has changed.\n", "- Use `reverse()` to change the order of your list again. Print the list to show it’s back to its original order.\n", "- Use `sort()` to change your list so it’s stored in alphabetical order. Print the list to show that its order has been changed.\n", "- Use `sort()` to change your list so it’s stored in reverse alphabetical order. Print the list to show that its order has changed." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Original list:\n", "['Vietnam', 'New Zealand', 'Australia', 'India', 'Israel']\n", "Temporarily alphabetically sorted list:\n", "['Australia', 'India', 'Israel', 'New Zealand', 'Vietnam']\n", "Original list:\n", "['Vietnam', 'New Zealand', 'Australia', 'India', 'Israel']\n", "Temporarily reverse alphabetically ordered list:\n", "['Vietnam', 'New Zealand', 'Israel', 'India', 'Australia']\n", "Original list:\n", "['Vietnam', 'New Zealand', 'Australia', 'India', 'Israel']\n", "Permanently reverse list:\n", "['Israel', 'India', 'Australia', 'New Zealand', 'Vietnam']\n", "Permanently alphabetically sorted original list:\n", "['Australia', 'India', 'Israel', 'New Zealand', 'Vietnam']\n" ] } ], "source": [ "# Write your code here\n", "# List of places to visit\n", "places_to_visit = ['Vietnam', 'New Zealand', 'Australia', 'India', 'Israel']\n", "\n", "# Print original list\n", "print('Original list:')\n", "print(places_to_visit)\n", "\n", "# Temporarily alphabetically sorted list\n", "print('Temporarily alphabetically sorted list:')\n", "print(sorted(places_to_visit))\n", "print('Original list:')\n", "print(places_to_visit)\n", "\n", "# Temporarily reverse alphabetically ordered list\n", "print('Temporarily reverse alphabetically ordered list:')\n", "print(sorted(places_to_visit, reverse=True))\n", "print('Original list:')\n", "print(places_to_visit)\n", "\n", "# Permanently reverse list (not reverse alphabetically sorted)\n", "places_to_visit.reverse()\n", "print('Permanently reverse list:')\n", "print(places_to_visit)\n", "\n", "# Permanently alphabetically sorted list\n", "places_to_visit.sort()\n", "print('Permanently alphabetically sorted original list:')\n", "print(places_to_visit)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 6.__ Define a list `L = [1,4,7,10]`. Find the sum of the 2nd and 4th elements of `L`. Find the sum of all the elements of `L`. " ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Sum of 2nd and 4th elements of L = 14\n", "Sum of all elements of L = 22\n" ] } ], "source": [ "# Write your code here\n", "# Define given list\n", "L = [1, 4, 7, 10]\n", "\n", "# Sum of 2nd and 4th elements of L\n", "sum_2_4 = L[1] + L[3]\n", "print(f'Sum of 2nd and 4th elements of L = {sum_2_4}')\n", "\n", "# Sum of all elements of L\n", "sum_all = sum(L)\n", "print(f'Sum of all elements of L = {sum_all}')" ] } ], "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }