{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "BU5F7s4V4xGX" }, "source": [ "# HW01: Introduction to Python\n", "The first homework problem is solved with Python. You'll complete the below labeled actions. Look for places where an **Action** is required. The following topics are covered:\n", "\n", "* install Python\n", "* help, print, type\n", "* variable names\n", "* operators\n", "* import packages\n", "* introduction to numpy\n", "* introduction to matplotlib" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "The following code is to display YouTube videos and URL links in the Notebook. There is no need to modify this code." ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "id": "DRw1mEEy4xGZ" }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/var/folders/6d/1jr2w1qx1rnd2nkndlq4hc700000gn/T/ipykernel_13887/2426028648.py:3: DeprecationWarning: Importing display from IPython.core.display is deprecated since IPython 7.14, please import from IPython display\n", " from IPython.core.display import display, HTML\n" ] } ], "source": [ "# function to display YouTube videos and external web-pages\n", "import numpy as np\n", "from IPython.core.display import display, HTML\n", "def video(key):\n", " display(HTML(''))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "8UNhc9_64xGa" }, "source": [ "## Problem 1\n", "\n", "Install Python if you have a laptop computer. If not, then skip this step and use the CAEDM computer that already has Anaconda and Jupyter notebook. You can also use Google Colab." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "BQBHYBAJ4xGb" }, "source": [ "***Action 1a:*** Download and install Anaconda (Jupyter Notebook) from https://www.anaconda.com/distribution/" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "id": "U0o1ZZRx4xGb", "outputId": "8ef562e0-6803-40c3-b7cd-a8e619c32ef4" }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "video('LrMOrMb8-3s')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "YHnLBHoM4xGc" }, "source": [ "### Getting Started\n", "\n", "Some of the most useful things for getting started are to use ```print()```, ```help()```, and know how to search for answers online with Google, Bard, or ChatGPT and in forums such as StackOverflow.\n", "\n", "***Action 1b:*** Change ```'my message'``` to a different text message." ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "id": "CdgYggO34xGc", "outputId": "aa8b4b3b-c328-48b6-c991-1e406e19dbe9" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "my message\n" ] } ], "source": [ "print('my message')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "bfSGc_wo4xGc" }, "source": [ "***Action 1c:*** Show the help documentation for the ```max``` function instead of the ```print``` function. Based on the help, use the ```max``` function to find the highest value of two numbers: ```5``` and ```2```." ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "id": "MSpRKdf44xGc", "outputId": "c555b15f-83e2-42c7-adbf-3e40e2402c3b" }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on built-in function print in module builtins:\n", "\n", "print(...)\n", " print(value, ..., sep=' ', end='\\n', file=sys.stdout, flush=False)\n", " \n", " Prints the values to a stream, or to sys.stdout by default.\n", " Optional keyword arguments:\n", " file: a file-like object (stream); defaults to the current sys.stdout.\n", " sep: string inserted between values, default a space.\n", " end: string appended after the last value, default a newline.\n", " flush: whether to forcibly flush the stream.\n", "\n" ] } ], "source": [ "help(print)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "RJ3dhMP44xGd" }, "source": [ "### Variable Names\n", "\n", "There are three types of basic variables in Python. These are:\n", "\n", "* string (e.g. 'banana')\n", "* integer (e.g. 2)\n", "* float (e.g. 3.1415)\n", "\n", "A variable name must begin with a letter or underscore but not with a number or other special characters. A variable name must not have a space and lowercase or uppercase are permitted.\n", "\n", "***Action 1d:*** Correct the following errors in the variable names." ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "id": "rg7OuPr44xGd", "outputId": "2b891dff-1064-4ec3-cc84-322ca0ff5c29" }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (3901419262.py, line 2)", "output_type": "error", "traceback": [ "\u001b[0;36m Cell \u001b[0;32mIn[16], line 2\u001b[0;36m\u001b[0m\n\u001b[0;31m 1var = 1\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "# correct the variable name errors\n", "1var = 1\n", "my Var = 2\n", "test!Var = 3\n", "#myVar = 4" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "OjUHjOGJ4xGd" }, "source": [ "### Variable Types\n", "\n", "Every variable is stored as an object that is shown with the ```type``` function:\n", "\n", "```python\n", "myVar = 2\n", "print(type(myVar))\n", "```\n", "\n", "Produces ******, meaning that ```myVar``` is an integer type. Values can be converted to a different type such as with:\n", "\n", "* ```int```: convert to an integer\n", "* ```float```: convert to a floating point number with a decimal value\n", "* ```str```: convert to a string (sequence of characters)\n", "\n", "The type of the variable can change (mutable) in Python.\n", "\n", "***Action 1e:*** Print the variable value and type for ```x```, ```y```, and ```z```. Explain why ```x``` is 46 and not 10." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "QovShKKc4xGd" }, "outputs": [], "source": [ "x = int('2'+'3')*2\n", "y = x - 10.0\n", "z = str(4.0)\n", "\n", "# print the values of x, y, and z\n", "\n", "# determine the type for x, y, and z\n", "\n", "# explain why x is equal to 46, not 10\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "EXhGzi_l4xGd" }, "source": [ "### Functions of the str Object\n", "\n", "In addition to a value, the ```str``` object has useful functions such as ```lower``` and ```upper``` to convert to lower or upper case, respectively.\n", "\n", "```python\n", "myVar = 'my name'\n", "print(myVar.upper())\n", "```\n", "\n", "The result is ```'MY NAME'```.\n", "\n", "***Action 1f:*** Insert your name and then convert and print it in lower case with the str.lower() function." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "MaFnysmb4xGd" }, "outputs": [], "source": [ "myStr = 'Your Name'" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "With numpy, there are a number of other functions including ```sin```, ```cos```, ```exp```, ```log```, ```sqrt```, ```sum```, ```max```, ```min```, ```abs```, ```round```, ```floor```, ```ceil```, etc." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# for example you can take the exponential of 5:\n", "print(np.exp(5))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "You can also create you're own functions such as the volume of a sphere with radius ```r```:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "523.5987755982989\n" ] } ], "source": [ "def sphereVolume(r):\n", " return (4/3)*np.pi*r**3\n", "#for a sphere with radius 5, the volume is:\n", "print(sphereVolume(5))" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "**Action 1g**: Create a function for the volume of a cylinder with radius ```r``` and height ```h```. Then print the result of calling that function with ```r=2``` and ```h=5```." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "MNjjV_xH4xGe" }, "source": [ "### Operators\n", "\n", "Operators are used to transform, compare, join, substract, etc. Below is a list of operators in descending order of precedence when there are no parenthesis to guide the precedence." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "VU7zXXSM4xGe" }, "source": [ "| Operator | Description |\n", "| --- | --- |\n", "| ** | Exponent |\n", "| *, /, //, % | Multiplication, Division, Floor division, Modulus |\n", "| +, - | Addition, Subtraction |\n", "| <= < > >= | Comparison |\n", "| = %= /= //= -= += *= **= | Assignment |\n", "| is, is not | Identity |\n", "| in, not in | Membership |\n", "| not, or, and | Logical |" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "1pWkDczj4xGe" }, "source": [ "***Action 1h:*** Use the operator list to determine whether $5^5$ is greater than $2^{10}$." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "js-i0tjq4xGe" }, "outputs": [], "source": [ "# modify to determine whether 5^5 is greater than 2^10\n", "5 == 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Classes\n", "You'll use classes with dot notation throughout this course and throughout your time here using python for scientific computing. The following code is an example of a class that you'll use in this course." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import param\n", "class chair(param.Parameterized):\n", " legs = param.Integer(4, bounds=(1, 4))\n", " color = param.ObjectSelector(default=\"red\", objects=[\"red\", \"green\", \"blue\"])" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My chair has 3 legs and is blue.\n" ] } ], "source": [ "mychair = chair(legs=3, color=\"blue\") #instance of the chair class\n", "print(f'My chair has {mychair.legs} legs and is {mychair.color}.') #print the attributes of mychair" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "**Action 1g**: Define a class called molecule that has the following attributes: name, formula, and weight. The name and formula should be strings and the weight should be a float. Use the param package to automatically instantiate the object upon calling . Create an instance of the class called water that has the name 'water', the formula 'H2O', and the weight 18.01528. Print the name of the molecule. You can use the example code in the lecture to help you (or any other source) but please make sure you do all of the typing (no copy and paste)." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "gmahh0Kl4xGe" }, "source": [ "## Problem #2\n", "\n", "### Packages\n", "\n", "Python capabilities are extended with many useful packages. A few of the packages that we'll use in this class are:\n", "\n", "* NumPy (Numerical Python) as a base numerical package\n", "* Matplotlib for creating charts and visualizing data\n", "* SciPy (Scientific Python) as a base scientific package\n", "* Pandas data analysis library\n", "* Gekko for simulation and optimization\n", "\n", "Anaconda comes with many of the packages built-in but there are sometimes packages that you'll need to add. Below is a video tutorial on managing the packages in Python. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "fCY6Uwwi4xGe", "outputId": "ce68802b-6ab8-44af-89ad-b5ca7e9058d5" }, "outputs": [ { "data": { "text/html": [ "" ], "text/plain": [ "" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "video('Z_Kxg-EYvxM')" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "GzXrLbDQ4xGe" }, "source": [ "You can import a package with ```import **package** as **pk**``` where ```**package**``` is the package name and ```**pk**``` is the abbreviated name.\n", "\n", "***Action 2a:*** Import the ```numpy``` package as ```np``` (shortened name) and get help on the ```np.linspace``` function." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "rW7SLmHA4xGe" }, "outputs": [], "source": [] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "RS6f_oeq4xGf" }, "source": [ "***Action 2b:*** Use ```np.linspace``` to define 20 equally spaced values between $0$ and $2\\,\\pi$. Name the variable ```x``` and use the built-in ```np.pi``` constant for $\\pi$." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "TBG2JrhY4xGf" }, "outputs": [], "source": [] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "0T_TydjH4xGf" }, "source": [ "***Action 2c:*** Use ```np.sin``` to calculate a new variable ```y``` as $y=2\\,\\sin{\\left(\\frac{x}{2}\\right)}$." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "x-ArJyoW4xGf" }, "outputs": [], "source": [] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "ZQBN4WBX4xGf" }, "source": [ "***Action 2d:*** Import the ```matplotlib.pyplot``` package as ```plt``` (shortened name) and show the help on the ```plt.plot``` function. To show plots in an IPython notebook, the additional code ```%matplotlib inline``` is required." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "zzcQis8E4xGf" }, "outputs": [], "source": [] }, { "attachments": {}, "cell_type": "markdown", "metadata": { "id": "ukVKXsug4xGf" }, "source": [ "***Action 2e:*** Create a plot of ```x``` and ```y``` with the ```plt.plot``` function. Add an x-label with ```plt.xlabel``` and a y-label with ```plt.ylabel```. If you are not using an IPython notebook, include ```plt.show()``` to display the plot. You can also include it in an IPython notebook but it won't have any effect." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Problem #3\n", "Create an account on [Kaggle](https://www.kaggle.com/). Go to the Learn section, find the Python course, and complete the first lesson called \"Hello,Python\"." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Record here that you have completed this exercise and record the date and time in this cell.\n", "\n", "\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Problem #4\n", "**Action 4:** Describe which of the world problems highlighted in the [Motivation](https://clint-bg.github.io/comptools/lectures/01-Motive.html) lecture that most interest you in helping to solve." ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Problem #5\n", "Read the Deseret News article about energy ([DN Energy Article](https://www.deseret.com/utah/2023/6/28/23777165/rural-electric-provider-in-utah-impending-u-s-energy-crisis-moon-lake-coal-plants-mitt-romney))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "Credit to Dr. John Hedengren for many of these problems (see also [APMonitor.com](https://apmonitor.com/che263/))\n" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [] } ], "metadata": { "colab": { "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.9.16" } }, "nbformat": 4, "nbformat_minor": 0 }