{ "cells": [ { "cell_type": "markdown", "id": "1148fa22", "metadata": {}, "source": [ "\n", "\n", "
\n", " \n", " \"QuantEcon\"\n", " \n", "
" ] }, { "cell_type": "markdown", "id": "af050c11", "metadata": {}, "source": [ "# Getting Started\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "c8d0c3c3", "metadata": {}, "source": [ "## Contents\n", "\n", "- [Getting Started](#Getting-Started) \n", " - [Overview](#Overview) \n", " - [Python in the Cloud](#Python-in-the-Cloud) \n", " - [Local Install](#Local-Install) \n", " - [Jupyter Notebooks](#Jupyter-Notebooks) \n", " - [Installing Libraries](#Installing-Libraries) \n", " - [Working with Python Files](#Working-with-Python-Files) \n", " - [Exercises](#Exercises) " ] }, { "cell_type": "markdown", "id": "892b73fc", "metadata": {}, "source": [ "## Overview\n", "\n", "In this lecture, you will learn how to\n", "\n", "1. use Python in the cloud \n", "1. get a local Python environment up and running \n", "1. execute simple Python commands \n", "1. run a sample program \n", "1. install the code libraries that underpin these lectures " ] }, { "cell_type": "markdown", "id": "a717ba84", "metadata": {}, "source": [ "## Python in the Cloud\n", "\n", "The easiest way to get started coding in Python is by running it in the cloud.\n", "\n", "(That is, by using a remote server that already has Python installed.)\n", "\n", "One option that’s both free and reliable is [Google Colab](https://colab.research.google.com/).\n", "\n", "Colab also has the advantage of providing GPUs, which we will make use of in\n", "more advanced lectures.\n", "\n", "Tutorials on how to get started with Google Colab can be found by web and video searches.\n", "\n", "Most of our lectures include a “Launch notebook” button (with a play icon) on the top\n", "right connects you to an executable version on Colab." ] }, { "cell_type": "markdown", "id": "3f5376b3", "metadata": {}, "source": [ "## Local Install\n", "\n", "Local installs are preferable if you have access to a suitable machine and\n", "plan to do a substantial amount of Python programming.\n", "\n", "At the same time, local installs require more work than a cloud option like Colab.\n", "\n", "The rest of this lecture runs you through the some details associated with local installs." ] }, { "cell_type": "markdown", "id": "d41e9398", "metadata": {}, "source": [ "### The Anaconda Distribution\n", "\n", "The [core Python package](https://www.python.org/downloads/) is easy to install but *not* what you should choose for these lectures.\n", "\n", "These lectures require the entire scientific programming ecosystem, which\n", "\n", "- the core installation doesn’t provide \n", "- is painful to install one piece at a time. \n", "\n", "\n", "Hence the best approach for our purposes is to install a Python distribution that contains\n", "\n", "1. the core Python language **and** \n", "1. compatible versions of the most popular scientific libraries. \n", "\n", "\n", "The best such distribution is [Anaconda Python](https://www.anaconda.com/).\n", "\n", "Anaconda is\n", "\n", "- very popular \n", "- cross-platform \n", "- comprehensive \n", "- completely unrelated to the [Nicki Minaj song of the same name](https://www.youtube.com/watch?v=LDZX4ooRsWs) \n", "\n", "\n", "Anaconda also comes with a package management system to organize your code libraries.\n", "\n", "**All of what follows assumes that you adopt this recommendation!**\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "e616f72d", "metadata": {}, "source": [ "### Installing Anaconda\n", "\n", "\n", "\n", "To install Anaconda, [download](https://www.anaconda.com/download/) the binary and follow the instructions.\n", "\n", "Important points:\n", "\n", "- Make sure you install the correct version for your OS. \n", "- If you are asked during the installation process whether you’d like to make Anaconda your default Python installation, say yes. " ] }, { "cell_type": "markdown", "id": "03b75102", "metadata": {}, "source": [ "### Updating Anaconda\n", "\n", "Anaconda supplies a tool called `conda` to manage and upgrade your Anaconda packages.\n", "\n", "One `conda` command you should execute regularly is the one that updates the whole Anaconda distribution.\n", "\n", "As a practice run, please execute the following\n", "\n", "1. Open up a terminal \n", "1. Type `conda update anaconda` \n", "\n", "\n", "For more information on conda, type conda help in a terminal.\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "2e1082b4", "metadata": {}, "source": [ "## Jupyter Notebooks\n", "\n", "\n", "\n", "[Jupyter](http://jupyter.org/) notebooks are one of the many possible ways to interact with Python and the scientific libraries.\n", "\n", "They use a *browser-based* interface to Python with\n", "\n", "- The ability to write and execute Python commands. \n", "- Formatted output in the browser, including tables, figures, animation, etc. \n", "- The option to mix in formatted text and mathematical expressions. \n", "\n", "\n", "Because of these features, Jupyter is now a major player in the scientific computing ecosystem.\n", "\n", "Here’s an image showing execution of some code (borrowed from [here](http://matplotlib.org/examples/pylab_examples/hexbin_demo.html)) in a Jupyter notebook\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/jp_demo.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/jp_demo.png)\n", "\n", " \n", "While Jupyter isn’t the only way to code in Python, it’s great for when you wish to\n", "\n", "- start coding in Python \n", "- test new ideas or interact with small pieces of code \n", "- use powerful online interactive environments such as [Google Colab](https://research.google.com/colaboratory/) \n", "- share or collaborate scientific ideas with students or colleagues \n", "\n", "\n", "These lectures are designed for executing in Jupyter notebooks." ] }, { "cell_type": "markdown", "id": "4fcdf747", "metadata": {}, "source": [ "### Starting the Jupyter Notebook\n", "\n", "\n", "\n", "Once you have installed Anaconda, you can start the Jupyter notebook.\n", "\n", "Either\n", "\n", "- search for Jupyter in your applications menu, or \n", "- open up a terminal and type `jupyter notebook` \n", " - Windows users should substitute “Anaconda command prompt” for “terminal” in the previous line. \n", "\n", "\n", "If you use the second option, you will see something like this\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/starting_nb.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/starting_nb.png)\n", "\n", " \n", "The output tells us the notebook is running at `http://localhost:8888/`\n", "\n", "- `localhost` is the name of the local machine \n", "- `8888` refers to [port number](https://en.wikipedia.org/wiki/Port_%28computer_networking%29) 8888 on your computer \n", "\n", "\n", "Thus, the Jupyter kernel is listening for Python commands on port 8888 of our local machine.\n", "\n", "Hopefully, your default browser has also opened up with a web page that looks something like this\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb.png)\n", "\n", " \n", "What you see here is called the Jupyter *dashboard*.\n", "\n", "If you look at the URL at the top, it should be `localhost:8888` or similar, matching the message above.\n", "\n", "Assuming all this has worked OK, you can now click on `New` at the top right and select `Python 3` or similar.\n", "\n", "Here’s what shows up on our machine:\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb2.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb2.png)\n", "\n", " \n", "The notebook displays an *active cell*, into which you can type Python commands." ] }, { "cell_type": "markdown", "id": "6d8032e8", "metadata": {}, "source": [ "### Notebook Basics\n", "\n", "\n", "\n", "Let’s start with how to edit code and run simple programs." ] }, { "cell_type": "markdown", "id": "914c0eeb", "metadata": {}, "source": [ "#### Running Cells\n", "\n", "Notice that, in the previous figure, the cell is surrounded by a green border.\n", "\n", "This means that the cell is in *edit mode*.\n", "\n", "In this mode, whatever you type will appear in the cell with the flashing cursor.\n", "\n", "When you’re ready to execute the code in a cell, hit `Shift-Enter` instead of the usual `Enter`.\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb3.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb3.png)\n", "\n", " \n", ">**Note**\n", ">\n", ">There are also menu and button options for running code in a cell that you can find by exploring." ] }, { "cell_type": "markdown", "id": "e3fcc0bf", "metadata": {}, "source": [ "#### Modal Editing\n", "\n", "The next thing to understand about the Jupyter notebook is that it uses a *modal* editing system.\n", "\n", "This means that the effect of typing at the keyboard **depends on which mode you are in**.\n", "\n", "The two modes are\n", "\n", "1. Edit mode \n", " - Indicated by a green border around one cell, plus a blinking cursor \n", " - Whatever you type appears as is in that cell \n", "1. Command mode \n", " - The green border is replaced by a blue border \n", " - Keystrokes are interpreted as commands — for example, typing `b` adds a new cell below the current one \n", "\n", "\n", "To switch to\n", "\n", "- command mode from edit mode, hit the `Esc` key or `Ctrl-M` \n", "- edit mode from command mode, hit `Enter` or click in a cell \n", "\n", "\n", "The modal behavior of the Jupyter notebook is very efficient when you get used to it." ] }, { "cell_type": "markdown", "id": "5d58944e", "metadata": {}, "source": [ "#### Inserting Unicode (e.g., Greek Letters)\n", "\n", "Python supports [unicode](https://docs.python.org/3/howto/unicode.html), allowing the use of characters such as $ \\alpha $ and $ \\beta $ as names in your code.\n", "\n", "In a code cell, try typing `\\alpha` and then hitting the tab key on your keyboard.\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "761c67cc", "metadata": {}, "source": [ "#### A Test Program\n", "\n", "Let’s run a test program.\n", "\n", "Here’s an arbitrary program we can use: [http://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/polar_bar.html](http://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/polar_bar.html).\n", "\n", "On that page, you’ll see the following code" ] }, { "cell_type": "code", "execution_count": null, "id": "d6394008", "metadata": { "hide-output": false }, "outputs": [], "source": [ "import numpy as np\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline\n", "plt.rcParams['figure.figsize'] = (10,6)\n", "\n", "# Fixing random state for reproducibility\n", "np.random.seed(19680801)\n", "\n", "# Compute pie slices\n", "N = 20\n", "θ = np.linspace(0.0, 2 * np.pi, N, endpoint=False)\n", "radii = 10 * np.random.rand(N)\n", "width = np.pi / 4 * np.random.rand(N)\n", "colors = plt.cm.viridis(radii / 10.)\n", "\n", "ax = plt.subplot(111, projection='polar')\n", "ax.bar(θ, radii, width=width, bottom=0.0, color=colors, alpha=0.5)\n", "\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "7ec76136", "metadata": {}, "source": [ "Don’t worry about the details for now — let’s just run it and see what happens.\n", "\n", "The easiest way to run this code is to copy and paste it into a cell in the notebook.\n", "\n", "Hopefully you will get a similar plot." ] }, { "cell_type": "markdown", "id": "cd980cdc", "metadata": {}, "source": [ "### Working with the Notebook\n", "\n", "Here are a few more tips on working with Jupyter notebooks." ] }, { "cell_type": "markdown", "id": "51546c3c", "metadata": {}, "source": [ "#### Tab Completion\n", "\n", "In the previous program, we executed the line `import numpy as np`\n", "\n", "- NumPy is a numerical library we’ll work with in depth. \n", "\n", "\n", "After this import command, functions in NumPy can be accessed with `np.function_name` type syntax.\n", "\n", "- For example, try `np.random.randn(3)`. \n", "\n", "\n", "We can explore these attributes of `np` using the `Tab` key.\n", "\n", "For example, here we type `np.random.r` and hit Tab\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb6.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb6.png)\n", "\n", " \n", "Jupyter offers several possible completions for you to choose from.\n", "\n", "In this way, the Tab key helps remind you of what’s available and also saves you typing.\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "8f321e00", "metadata": {}, "source": [ "#### On-Line Help\n", "\n", "\n", "\n", "To get help on `np.random.randn`, we can execute `np.random.randn?`.\n", "\n", "Documentation appears in a split window of the browser, like so\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb6a.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb6a.png)\n", "\n", " \n", "Clicking on the top right of the lower split closes the on-line help.\n", "\n", "We will learn more about how to create documentation like this [later](https://python-programming.quantecon.org/python_essentials.html#docstrings)!" ] }, { "cell_type": "markdown", "id": "145d6ebf", "metadata": {}, "source": [ "#### Other Content\n", "\n", "In addition to executing code, the Jupyter notebook allows you to embed text, equations, figures and even videos in the page.\n", "\n", "For example, we can enter a mixture of plain text and LaTeX instead of code.\n", "\n", "Next we `Esc` to enter command mode and then type `m` to indicate that we\n", "are writing [Markdown](http://daringfireball.net/projects/markdown/), a mark-up language similar to (but simpler than) LaTeX.\n", "\n", "(You can also use your mouse to select `Markdown` from the `Code` drop-down box just below the list of menu items)\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb7.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb7.png)\n", "\n", " \n", "Now we `Shift+Enter` to produce this\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb8.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/nb8.png)" ] }, { "cell_type": "markdown", "id": "6138c74d", "metadata": {}, "source": [ "### Debugging Code\n", "\n", "\n", "\n", "Debugging is the process of identifying and removing errors from a program.\n", "\n", "You will spend a lot of time debugging code, so it is important to [learn how to do it effectively](https://www.freecodecamp.org/news/what-is-debugging-how-to-debug-code/).\n", "\n", "If you are using a newer version of Jupyter, you should see a bug icon on the right end of the toolbar.\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/debug.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/debug.png)\n", "\n", " \n", "Clicking this icon will enable the Jupyter debugger.\n", "\n", ">**Note**\n", ">\n", ">You may also need to open the Debugger Panel (View -> Debugger Panel).\n", "\n", "You can set breakpoints by clicking on the line number of the cell you want to debug.\n", "\n", "When you run the cell, the debugger will stop at the breakpoint.\n", "\n", "You can then step through the code line by line using the buttons on the “Next” button on the CALLSTACK toolbar (located in the right hand window).\n", "\n", "![https://python-programming.quantecon.org/_static/lecture_specific/getting_started/debugger_breakpoint.png](https://python-programming.quantecon.org/_static/lecture_specific/getting_started/debugger_breakpoint.png)\n", "\n", " \n", "You can explore more functionality of the debugger in the [Jupyter documentation](https://jupyterlab.readthedocs.io/en/latest/user/debugger.html)." ] }, { "cell_type": "markdown", "id": "ec144a80", "metadata": {}, "source": [ "### Sharing Notebooks\n", "\n", "\n", "\n", "Notebook files are just text files structured in [JSON](https://en.wikipedia.org/wiki/JSON) and typically ending with `.ipynb`.\n", "\n", "You can share them in the usual way that you share files — or by using web services such as [nbviewer](http://nbviewer.jupyter.org/).\n", "\n", "The notebooks you see on that site are **static** html representations.\n", "\n", "To run one, download it as an `ipynb` file by clicking on the download icon at the top right.\n", "\n", "Save it somewhere, navigate to it from the Jupyter dashboard and then run as discussed above.\n", "\n", ">**Note**\n", ">\n", ">If you are interested in sharing notebooks containing interactive content, you might want to check out [Binder](https://mybinder.org/).\n", "\n", "To collaborate with other people on notebooks, you might want to take a look at\n", "\n", "- [Google Colab](https://colab.research.google.com/) \n", "- [Kaggle](https://www.kaggle.com/kernels) \n", "\n", "\n", "To keep the code private and to use the familiar JupyterLab and Notebook interface, look into the [JupyterLab Real-Time Collaboration extension](https://jupyterlab-realtime-collaboration.readthedocs.io/en/latest/)." ] }, { "cell_type": "markdown", "id": "efcdf1c3", "metadata": {}, "source": [ "### QuantEcon Notes\n", "\n", "QuantEcon has its own site for sharing Jupyter notebooks related\n", "to economics – [QuantEcon Notes](http://notes.quantecon.org/).\n", "\n", "Notebooks submitted to QuantEcon Notes can be shared with a link, and are open\n", "to comments and votes by the community." ] }, { "cell_type": "markdown", "id": "a86b0c68", "metadata": {}, "source": [ "## Installing Libraries\n", "\n", "\n", "\n", "Most of the libraries we need come in Anaconda.\n", "\n", "Other libraries can be installed with `pip` or `conda`.\n", "\n", "One library we’ll be using is [QuantEcon.py](http://quantecon.org/quantecon-py).\n", "\n", "\n", "\n", "You can install [QuantEcon.py](http://quantecon.org/quantecon-py) by\n", "starting Jupyter and typing" ] }, { "cell_type": "markdown", "id": "6ff38e63", "metadata": { "hide-output": false }, "source": [ "```ipython3\n", "!conda install quantecon\n", "```\n" ] }, { "cell_type": "markdown", "id": "af7788d5", "metadata": {}, "source": [ "into a cell.\n", "\n", "Alternatively, you can type the following into a terminal" ] }, { "cell_type": "markdown", "id": "67200422", "metadata": { "hide-output": false }, "source": [ "```bash\n", "conda install quantecon\n", "```\n" ] }, { "cell_type": "markdown", "id": "4667799b", "metadata": {}, "source": [ "More instructions can be found on the [library page](http://quantecon.org/quantecon-py).\n", "\n", "To upgrade to the latest version, which you should do regularly, use" ] }, { "cell_type": "markdown", "id": "000234d1", "metadata": { "hide-output": false }, "source": [ "```bash\n", "conda upgrade quantecon\n", "```\n" ] }, { "cell_type": "markdown", "id": "1866cddd", "metadata": {}, "source": [ "Another library we will be using is [interpolation.py](https://github.com/EconForge/interpolation.py).\n", "\n", "This can be installed by typing in Jupyter" ] }, { "cell_type": "markdown", "id": "be124346", "metadata": { "hide-output": false }, "source": [ "```ipython3\n", "!conda install -c conda-forge interpolation\n", "```\n" ] }, { "cell_type": "markdown", "id": "56416c86", "metadata": {}, "source": [ "## Working with Python Files\n", "\n", "So far we’ve focused on executing Python code entered into a Jupyter notebook\n", "cell.\n", "\n", "Traditionally most Python code has been run in a different way.\n", "\n", "Code is first saved in a text file on a local machine\n", "\n", "By convention, these text files have a `.py` extension.\n", "\n", "We can create an example of such a file as follows:" ] }, { "cell_type": "code", "execution_count": null, "id": "0e663b30", "metadata": { "hide-output": false }, "outputs": [], "source": [ "%%writefile foo.py\n", "\n", "print(\"foobar\")" ] }, { "cell_type": "markdown", "id": "a5e305ba", "metadata": {}, "source": [ "This writes the line `print(\"foobar\")` into a file called `foo.py` in the local directory.\n", "\n", "Here `%%writefile` is an example of a [cell magic](http://ipython.readthedocs.org/en/stable/interactive/magics.html#cell-magics)." ] }, { "cell_type": "markdown", "id": "11dcc7ae", "metadata": {}, "source": [ "### Editing and Execution\n", "\n", "If you come across code saved in a `*.py` file, you’ll need to consider the\n", "following questions:\n", "\n", "1. how should you execute it? \n", "1. How should you modify or edit it? " ] }, { "cell_type": "markdown", "id": "9da660ff", "metadata": {}, "source": [ "#### Option 1: JupyterLab\n", "\n", "\n", "\n", "[JupyterLab](https://github.com/jupyterlab/jupyterlab) is an integrated development environment built on top of Jupyter notebooks.\n", "\n", "With JupyterLab you can edit and run `*.py` files as well as Jupyter notebooks.\n", "\n", "To start JupyterLab, search for it in the applications menu or type `jupyter-lab` in a terminal.\n", "\n", "Now you should be able to open, edit and run the file `foo.py` created above by opening it in JupyterLab.\n", "\n", "Read the docs or search for a recent YouTube video to find more information." ] }, { "cell_type": "markdown", "id": "b90ac0ea", "metadata": {}, "source": [ "#### Option 2: Using a Text Editor\n", "\n", "One can also edit files using a text editor and then run them from within\n", "Jupyter notebooks.\n", "\n", "A text editor is an application that is specifically designed to work with text files — such as Python programs.\n", "\n", "Nothing beats the power and efficiency of a good text editor for working with program text.\n", "\n", "A good text editor will provide\n", "\n", "- efficient text editing commands (e.g., copy, paste, search and replace) \n", "- syntax highlighting, etc. \n", "\n", "\n", "Right now, an extremely popular text editor for coding is [VS Code](https://code.visualstudio.com/).\n", "\n", "VS Code is easy to use out of the box and has many high quality extensions.\n", "\n", "Alternatively, if you want an outstanding free text editor and don’t mind a seemingly vertical learning curve plus long days of pain and suffering while all your neural pathways are rewired, try [Vim](http://www.vim.org/)." ] }, { "cell_type": "markdown", "id": "66452b62", "metadata": {}, "source": [ "## Exercises" ] }, { "cell_type": "markdown", "id": "4191a178", "metadata": {}, "source": [ "## Exercise 2.1\n", "\n", "If Jupyter is still running, quit by using `Ctrl-C` at the terminal where\n", "you started it.\n", "\n", "Now launch again, but this time using `jupyter notebook --no-browser`.\n", "\n", "This should start the kernel without launching the browser.\n", "\n", "Note also the startup message: It should give you a URL such as `http://localhost:8888` where the notebook is running.\n", "\n", "Now\n", "\n", "1. Start your browser — or open a new tab if it’s already running. \n", "1. Enter the URL from above (e.g. `http://localhost:8888`) in the address bar at the top. \n", "\n", "\n", "You should now be able to run a standard Jupyter notebook session.\n", "\n", "This is an alternative way to start the notebook that can also be handy.\n", "\n", "This can also work when you accidentally close the webpage as long as the kernel is still running." ] } ], "metadata": { "date": 1714691698.363284, "filename": "getting_started.md", "kernelspec": { "display_name": "Python", "language": "python3", "name": "python3" }, "title": "Getting Started" }, "nbformat": 4, "nbformat_minor": 5 }