{ "cells": [ { "cell_type": "markdown", "id": "start", "metadata": {}, "source": [ "# Labs 1 and 2: Python, Jupyter, DataHub, NumPy, SciPy, and Matplotlib\n", "\n", "## Lab 01: Python, Jupyter, and DataHub\n", "\n", "- **Get your own copy running**\n", "- **Change a number; run it again**\n", "\n", "Open your own copy of this notebook so you can change the code.\n", "\n", "**Start from the website:** [open the lab page (https://jduarte.physics.ucsd.edu/phys142/labs/lab01_lab02.html)](https://jduarte.physics.ucsd.edu/phys142/labs/lab01_lab02.html), or scan this QR code. You can click it too.\n", "\n", "\"QR\n", "\n", "On that page, click the **rocket icon** at the top right. The box below marks it and the menu it opens.\n", "\n", "- **JupyterHub** opens the notebook on UCSD DataHub. Sign in with your UCSD email and select the course environment. If it isn't listed, ask me.\n", "- **Colab** opens it with your Google account. Choose **File → Save a copy in Drive** so you can keep your edits, then click **Connect**. You don't need a GPU.\n", "\n", "\"Rocket\n", "\n", "**Upload it yourself instead:** if you already downloaded the `.ipynb`, either of these works:\n", "\n", "- **DataHub:** go to [datahub.ucsd.edu](https://datahub.ucsd.edu/), sign in, and select the course environment. Use the upload button in the file browser on the left, then double-click the notebook. Rename your copy and save it.\n", "- **Colab:** go to [colab.research.google.com](https://colab.research.google.com/), choose **File → Upload notebook**, and select the file. Save a copy to Drive and click **Connect**.\n", "\n", "Click the cell below and press **Shift+Enter**. Then change one of the numbers and run it again." ] }, { "cell_type": "code", "execution_count": null, "id": "first-cell", "metadata": {}, "outputs": [], "source": [ "2 + 3" ] }, { "cell_type": "markdown", "id": "cells", "metadata": {}, "source": [ "### Code cells and text cells\n", "\n", "- **Double-click this cell**\n", "- **Text cells versus code cells**\n", "\n", "The cell you just ran is a **code cell**. This one is **Markdown**: text with formatting.\n", "Double-click it to see how it's written, then press Shift+Enter to render it again.\n", "Use the toolbar to add a cell and choose Code or Markdown. Colab calls Markdown cells Text.\n", "\n", "Add a Markdown cell with a heading and a sentence. You can use this as a starting point:\n", "\n", "```markdown\n", "### My notes\n", "This is **bold**, and this is `code`.\n", "```\n", "\n", "A notebook saves the code, text, and displayed results together. The **kernel** is the\n", "Python process running your code; Colab calls it a runtime. If a cell is still running,\n", "you'll see a spinner or `[*]`. The stop button interrupts it." ] }, { "cell_type": "markdown", "id": "variables", "metadata": {}, "source": [ "### Variables and arithmetic\n", "\n", "- **Assignment stores a value**\n", "- **Print versus the last expression**\n", "\n", "`=` assigns a value to a name. Once we've defined `temperature_c`, we can use it in\n", "another calculation. Here we're converting Celsius to Fahrenheit.\n", "\n", "Python runs each line in order. `print` shows a value; an expression on the last line\n", "of a cell also displays its result." ] }, { "cell_type": "code", "execution_count": null, "id": "arithmetic", "metadata": {}, "outputs": [], "source": [ "temperature_c = 20.0\n", "temperature_f = temperature_c * 9 / 5 + 32\n", "print(temperature_f)" ] }, { "cell_type": "markdown", "id": "arithmetic-try", "metadata": {}, "source": [ "- **Predict it, then run it**\n", "- **Parentheses change what happens first**\n", "\n", "Change `temperature_c` to `0` and run the cell again. You should get `32`.\n", "\n", "`+`, `-`, `*`, and `/` do arithmetic. `**` raises a number to a power; `^` doesn't.\n", "Parentheses control the order, and `1e-3` means 0.001. Try `2**3`, `(2 + 3) * 4`,\n", "and `2 + 3 * 4` in a new code cell." ] }, { "cell_type": "markdown", "id": "state", "metadata": {}, "source": [ "#### The order you run cells matters\n", "\n", "- **Change the input; leave the output**\n", "- **Now rerun the second cell**\n", "\n", "Run the next two cells. Then change `number` in the first cell and run **only that cell**.\n", "The second cell's old output doesn't update on its own. Run the second cell again to\n", "use the new value." ] }, { "cell_type": "code", "execution_count": null, "id": "state-input", "metadata": {}, "outputs": [], "source": [ "number = 5" ] }, { "cell_type": "code", "execution_count": null, "id": "state-output", "metadata": {}, "outputs": [], "source": [ "print(number * 2)" ] }, { "cell_type": "markdown", "id": "state-explain", "metadata": {}, "source": [ "- **Old output can still be visible**\n", "- **Restarting clears the variables**\n", "\n", "The kernel remembers variables from cells you've already run. Saving the notebook doesn't\n", "save that running Python session. After a restart, you'll need to run the definitions again.\n", "\n", "If you get `NameError`, check the spelling and whether you've run the cell that defines\n", "the name. Don't assume that visible output means the variable still exists." ] }, { "cell_type": "markdown", "id": "types", "metadata": {}, "source": [ "#### Numbers, text, and comparisons\n", "\n", "- **Same digits, different types**\n", "- **Ask Python what type it is**\n", "\n", "Python distinguishes integers (`int`), decimal numbers (`float`), text (`str`), and\n", "true/false values (`bool`). `type` tells you which one you have.\n", "Quotation marks make text: `\"20\"` and `20` aren't the same thing." ] }, { "cell_type": "code", "execution_count": null, "id": "types-code", "metadata": {}, "outputs": [], "source": [ "count = 6\n", "reading = 20.5\n", "sensor_name = \"Sensor A\"\n", "above_limit = reading > 20\n", "\n", "print(type(count), type(reading), type(sensor_name), type(above_limit))" ] }, { "cell_type": "markdown", "id": "comparison-result-cue", "metadata": {}, "source": [ "- **A comparison gives `True` or `False`.**" ] }, { "cell_type": "code", "execution_count": null, "id": "comparison-result", "metadata": {}, "outputs": [], "source": [ "print(above_limit)" ] }, { "cell_type": "markdown", "id": "text-addition-cue", "metadata": {}, "source": [ "- **Predict: what does adding text do?**" ] }, { "cell_type": "code", "execution_count": null, "id": "text-addition", "metadata": {}, "outputs": [], "source": [ "print(\"20\" + \"5\")" ] }, { "cell_type": "markdown", "id": "text-conversion-cue", "metadata": {}, "source": [ "- **Convert first. Then add.**" ] }, { "cell_type": "code", "execution_count": null, "id": "text-conversion", "metadata": {}, "outputs": [], "source": [ "print(float(\"20\") + 5)" ] }, { "cell_type": "markdown", "id": "formatted-text-cue", "metadata": {}, "source": [ "- **Put values into a sentence.**" ] }, { "cell_type": "code", "execution_count": null, "id": "formatted-text", "metadata": {}, "outputs": [], "source": [ "print(f\"{sensor_name}: {reading:.1f} degrees C\")" ] }, { "cell_type": "markdown", "id": "types-followup", "metadata": {}, "source": [ "- **Printing fewer decimals changes the display**\n", "- **Assignment and comparison use different operators**\n", "\n", "The `f` before the last string lets us insert values inside `{...}`. `:.1f` displays\n", "one decimal place. It only changes how the number looks when printed.\n", "\n", "`float(\"20\")` converts text to a number, so `+` does addition instead of joining text.\n", "Text after `#` is a comment; Python doesn't run it.\n", "\n", "Use `==` to compare values, and `=` to assign them. Other comparisons are `!=`, `<`,\n", "`<=`, `>`, and `>=`. Try `reading == 20.5` and `reading < 20`." ] }, { "cell_type": "markdown", "id": "lists", "metadata": {}, "source": [ "### Lists\n", "\n", "- **Count indices from zero**\n", "- **The slice stops before that index**\n", "\n", "A list holds several values. Indexing starts at **0**, so `readings[0]` is the first\n", "entry. `[-1]` is the last. A slice like `[1:4]` takes entries 1, 2, and 3; the stop\n", "index is excluded." ] }, { "cell_type": "code", "execution_count": null, "id": "lists-code", "metadata": {}, "outputs": [], "source": [ "readings = [20.0, 21.1, 21.8, 23.2, 23.9, 25.1]\n", "readings" ] }, { "cell_type": "markdown", "id": "list-first-last-cue", "metadata": {}, "source": [ "- **First is `0`. Last is `-1`.**" ] }, { "cell_type": "code", "execution_count": null, "id": "list-first-last", "metadata": {}, "outputs": [], "source": [ "print(\"First:\", readings[0])\n", "print(\"Last:\", readings[-1])" ] }, { "cell_type": "markdown", "id": "list-slice-cue", "metadata": {}, "source": [ "- **Predict which entries survive the slice.**" ] }, { "cell_type": "code", "execution_count": null, "id": "list-slice", "metadata": {}, "outputs": [], "source": [ "print(\"Slice:\", readings[1:4])" ] }, { "cell_type": "markdown", "id": "list-length-cue", "metadata": {}, "source": [ "- **Count the entries.**" ] }, { "cell_type": "code", "execution_count": null, "id": "list-length", "metadata": {}, "outputs": [], "source": [ "len(readings)" ] }, { "cell_type": "markdown", "id": "list-mean-cue", "metadata": {}, "source": [ "- **Add them up. Divide by the count.**" ] }, { "cell_type": "code", "execution_count": null, "id": "list-mean", "metadata": {}, "outputs": [], "source": [ "sum(readings) / len(readings)" ] }, { "cell_type": "markdown", "id": "lists-try", "metadata": {}, "source": [ "- **Six entries, indices zero through five**\n", "- **Rerun the definition to restore it**\n", "\n", "Try `readings[:3]` and `readings[3:]`. What happens if you ask for `readings[6]`?\n", "There are six readings, but their indices are 0 through 5.\n", "After seeing the error, remove that trial line or put `#` in front of it so Run All can finish.\n", "\n", "You can replace an entry with `readings[0] = 19.8`, or add one with\n", "`readings.append(26.0)`. Try both, then rerun the cell that defines `readings` to restore the list." ] }, { "cell_type": "markdown", "id": "loops", "metadata": {}, "source": [ "### Loops and conditions\n", "\n", "- **Trace one reading at a time**\n", "- **Point out the colon and indentation**\n", "\n", "A `for` loop repeats its indented lines for each value. Here we use an `if` statement\n", "to print only the readings above 23. The colon and indentation are part of the syntax." ] }, { "cell_type": "code", "execution_count": null, "id": "loop-code", "metadata": {}, "outputs": [], "source": [ "readings = [20.0, 21.1, 21.8, 23.2, 23.9, 25.1]\n", "for reading in readings:\n", " if reading > 23:\n", " print(reading)" ] }, { "cell_type": "markdown", "id": "loop-try", "metadata": {}, "source": [ "- **Flip the condition**\n", "- **Build a new list with `append`**\n", "\n", "Change the condition to print readings at or below 23. You can add an `else:` at the\n", "same indentation as `if` to do something when the condition is false.\n", "\n", "Here's a loop that builds a new list. `append` adds each converted value to the end." ] }, { "cell_type": "code", "execution_count": null, "id": "loop-convert", "metadata": {}, "outputs": [], "source": [ "fahrenheit_readings = []\n", "for reading in readings:\n", " converted = reading * 9 / 5 + 32\n", " fahrenheit_readings.append(converted)" ] }, { "cell_type": "markdown", "id": "loop-result-cue", "metadata": {}, "source": [ "- **Look at what the loop built.**" ] }, { "cell_type": "code", "execution_count": null, "id": "loop-result", "metadata": {}, "outputs": [], "source": [ "fahrenheit_readings" ] }, { "cell_type": "markdown", "id": "range", "metadata": {}, "source": [ "- **Where does the sequence stop?**\n", "- **Four values, starting at zero**\n", "\n", "Use `range` when you want a sequence of integers. `range(4)` gives 0, 1, 2, 3.\n", "It excludes the stop value, just like a slice." ] }, { "cell_type": "code", "execution_count": null, "id": "range-code", "metadata": {}, "outputs": [], "source": [ "for index in range(4):\n", " print(index, index**2)" ] }, { "cell_type": "markdown", "id": "functions", "metadata": {}, "source": [ "### Functions\n", "\n", "- **Define once; call with different inputs**\n", "- **Return a value you can reuse**\n", "\n", "We've written the temperature conversion twice. Put it in a function so we can call it\n", "with different inputs. `def` defines the function; `return` gives its result back to\n", "the code that called it." ] }, { "cell_type": "code", "execution_count": null, "id": "function-code", "metadata": {}, "outputs": [], "source": [ "def to_fahrenheit(celsius):\n", " return celsius * 9 / 5 + 32" ] }, { "cell_type": "markdown", "id": "function-zero-cue", "metadata": {}, "source": [ "- **Define once. Call with different inputs.**" ] }, { "cell_type": "code", "execution_count": null, "id": "function-zero", "metadata": {}, "outputs": [], "source": [ "to_fahrenheit(0)" ] }, { "cell_type": "code", "execution_count": null, "id": "function-hundred", "metadata": {}, "outputs": [], "source": [ "to_fahrenheit(100)" ] }, { "cell_type": "markdown", "id": "function-returned-cue", "metadata": {}, "source": [ "- **Keep the returned value.**" ] }, { "cell_type": "code", "execution_count": null, "id": "function-returned", "metadata": {}, "outputs": [], "source": [ "converted = to_fahrenheit(20)\n", "print(converted)" ] }, { "cell_type": "markdown", "id": "function-task", "metadata": {}, "source": [ "- **Write the reverse conversion**\n", "- **Check both known temperatures**\n", "\n", "Write `to_celsius(fahrenheit)` below. Subtract 32, then multiply by 5/9. Check that\n", "32 °F gives 0 °C and 212 °F gives 100 °C.\n", "\n", "Use `return`, not just `print`: we want to use the result in another calculation." ] }, { "cell_type": "code", "execution_count": null, "id": "function-practice", "metadata": {}, "outputs": [], "source": [ "# Write your to_celsius function here, then call it with 32 and 212." ] }, { "cell_type": "markdown", "id": "function-answer", "metadata": {}, "source": [ "
\n", "One way to write it\n", "\n", "```python\n", "def to_celsius(fahrenheit):\n", " return (fahrenheit - 32) * 5 / 9\n", "\n", "print(to_celsius(32))\n", "print(to_celsius(212))\n", "```\n", "\n", "
" ] }, { "cell_type": "markdown", "id": "debugging", "metadata": {}, "source": [ "### When a cell fails\n", "\n", "- **Read the last error line first**\n", "- **Check the indicated line**\n", "\n", "Read the last line of the error first, then look at the line it points to.\n", "\n", "- `NameError`: the name hasn't been defined in this session, or it's misspelled.\n", "- `TypeError`: check what kinds of values you're combining. Text plus a number is a common one.\n", "- `IndexError`: the list or array doesn't have the entry you requested.\n", "- `SyntaxError` or `IndentationError`: check brackets, colons, and indentation.\n", "\n", "Python decimal arithmetic also has rounding error. Run the next two cells and compare the results." ] }, { "cell_type": "code", "execution_count": null, "id": "roundoff", "metadata": {}, "outputs": [], "source": [ "0.1 + 0.2" ] }, { "cell_type": "markdown", "id": "roundoff-equality-cue", "metadata": {}, "source": [ "- **Predict: will exact equality pass?**" ] }, { "cell_type": "code", "execution_count": null, "id": "roundoff-equality", "metadata": {}, "outputs": [], "source": [ "0.1 + 0.2 == 0.3" ] }, { "cell_type": "markdown", "id": "lab1-finish", "metadata": {}, "source": [ "- **Small rounding differences are expected**\n", "- **Restart, then run from the top**\n", "\n", "Most decimals aren't represented exactly in binary. The small difference here isn't a\n", "reason to round every calculation. Below we'll use NumPy's `isclose` when comparing numbers.\n", "\n", "Save your notebook. Restart the kernel from the **Kernel** menu in JupyterLab, or restart\n", "the session from **Runtime** in Colab. Run the Lab 01 cells from the top. If a name is\n", "missing, find where it should have been defined." ] } ], "metadata": { "colab": { "name": "lab01.ipynb", "provenance": [] }, "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.12.3" }, "title": "Lab 01: Python, Jupyter, and DataHub" }, "nbformat": 4, "nbformat_minor": 5 }