├── .DS_Store ├── LICENSE ├── README.md ├── img └── afs-structure.png ├── incomplete ├── editors │ ├── IDLE.md │ ├── eclipse.md │ ├── emacs.md │ ├── sublime_text.md │ └── vim.md ├── getting_started.md └── repl │ ├── interpreter.md │ └── ipython.md ├── installing-python-linux.md ├── installing-python-macos.md ├── installing-python-windows.md ├── old ├── installing-python-brexton.md ├── installing-python.md ├── submitting-assignments.md └── virtualenv.md ├── submitting-assignments.md ├── term_example.png └── virtual-environments.md /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/.DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2019 Sam Redmond 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Handouts 2 | 3 | Assorted handouts from CS41, Stanford's introductory Python course covering the fundamentals of the Python programming language. 4 | 5 | You can learn more about this course at [the course website](https://stanfordpython.com/). 6 | 7 | ## Contributing 8 | 9 | While we try our best to make these handouts accurate, some of them might contain errors. Please feel free to let us know about any errors you see by filing an issue, or update some of our incomplete handouts via PR. -------------------------------------------------------------------------------- /img/afs-structure.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/img/afs-structure.png -------------------------------------------------------------------------------- /incomplete/editors/IDLE.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/incomplete/editors/IDLE.md -------------------------------------------------------------------------------- /incomplete/editors/eclipse.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/incomplete/editors/eclipse.md -------------------------------------------------------------------------------- /incomplete/editors/emacs.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/incomplete/editors/emacs.md -------------------------------------------------------------------------------- /incomplete/editors/sublime_text.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/incomplete/editors/sublime_text.md -------------------------------------------------------------------------------- /incomplete/editors/vim.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/incomplete/editors/vim.md -------------------------------------------------------------------------------- /incomplete/getting_started.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | Welcome to Python! 3 | 4 | By following the instructions in this document, you can get up and running with Python in no time. 5 | 6 | ## Table of Contents 7 | 8 | ## Mac OS X / Linux Setup 9 | 10 | ### Installing Python 11 | 12 | First, let's make sure Python is installed on your computer. On a command line, type `python --version` and then hit enter. The version of python installed 13 | Success!``` 14 | $ python --version 15 | ``` 16 | 17 | (with help from the [Python Docs](https://docs.python.org/2/using/)# Getting Started -------------------------------------------------------------------------------- /incomplete/repl/interpreter.md: -------------------------------------------------------------------------------- 1 | # Interactive Python -------------------------------------------------------------------------------- /incomplete/repl/ipython.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/incomplete/repl/ipython.md -------------------------------------------------------------------------------- /installing-python-linux.md: -------------------------------------------------------------------------------- 1 | # Installing Python on Linux 2 | 3 | Hello! 4 | 5 | This document provides a walkthrough to set up a Python development environment for [CS41](https://stanfordpython.com) on Linux. Alternate versions of this guide exist for [macOS](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-macos.md) and [Windows](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-windows.md) development. 6 | 7 | ## Overview 8 | 9 | In this course, you'll be writing lots of Python code, so it's important to get your development environment set up and ready-to-go. Moreover, we will sometimes need to install dependencies and packages, so we want to make sure that everything is installed to the right place as well. The tools we develop in this document will also be useful for any external development you might pursue in Python. 10 | 11 | Throughout this document, we will: 12 | 13 | 1. Install Python 3.10.3 14 | 2. Create a virtual environment using this version of Python. 15 | 3. Inside this environment, install useful packages. 16 | 17 | Let's get started! 18 | 19 | ## Prerequisite 20 | 21 | We assume that you have a basic familiarity with the command line. We understand that not everyone will feel comfortable with the command line, because it is covered starting in CS107. However, I highly recommend using Nick Troccoli's amazing [CS107 resources](https://web.stanford.edu/class/archive/cs/cs107/cs107.1214/resources/) for this quarter if you feel less experienced, particular the section titled "Common Unix Commands." 22 | 23 | ## Install Python 3.10.3 24 | 25 | On different Linux systems, there are a couple of different ways to install and manage packages. We'll cover `apt-get` here, as well as how you can install from source. 26 | 27 | ### Installing with `apt-get` (Ubuntu, Debian) 28 | 29 | `apt-get` is Linux's Advanced Package Tool, and is very useful for installing, managing, upgrading, and removing packages on Debian, Ubuntu, and a few other Linux distributions. We'll use [Felix Krull's PPA](https://launchpad.net/~deadsnakes/+archive/ubuntu/ppa) to install specific Python versions. 30 | 31 | ``` 32 | $ sudo add-apt-repository ppa:deadsnakes/ppa 33 | $ sudo apt-get update 34 | $ sudo apt-get install python3.10 35 | $ sudo apt-get install python3.10-venv 36 | ``` 37 | 38 | On Debian, we'll just have to `sudo apt-get install python3` and hope for the best. Also note that this might install a different version of Python 3.10, but we won't worry about that here. 39 | 40 | ### Installing with `yum` (RedHat, CentOS) 41 | 42 | Other Linux distributions use a different package manager, `yum`. We don't have any test devices with these Linux distributions, so you're on your own here. There is a reasonably good tutorial for CentOS [here](https://www.digitalocean.com/community/tutorials/how-to-install-python-3-and-set-up-a-local-programming-environment-on-centos-7). 43 | 44 | ### Other Linux package managers 45 | 46 | The world of Linux distributions is unfathomably large. If you can pull off a Python 3.10 install on your distribution of choice, more power to you. However, we recommend building from source. 47 | 48 | ### Installing from source 49 | 50 | Installing Python from source follows the same pattern as most other source installations. 51 | 52 | First, download the source tarball (either [gzipped](https://www.python.org/ftp/python/3.10.3/Python-3.10.3.tgz) or [XZ compressed](https://www.python.org/ftp/python/3.10.3/Python-3.10.3.tar.xz)). Unzip the files and `cd` into the unzipped directory. 53 | 54 | To build Python, just execute the usual commands: 55 | 56 | ``` 57 | $ ./configure 58 | $ make 59 | $ make test 60 | $ sudo make install 61 | ``` 62 | 63 | *Note: If you want to install Python to a non-standard location, you can `./configure --prefix=/some/other/directory` in order to, say, not overwrite a system-installed Python, which might be useful for distributions like CentOS* 64 | 65 | More information on the actual installation process can be found in the tarball's README. 66 | 67 | ## Follow the macOS Instructions 68 | 69 | From here, the instructions are almost exactly the same as the [macOS](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-macos.md) instructions. Follow those instructions, with the following differences. 70 | 71 | ## Credit 72 | Much of this handout was based on a similar handout written by Sam Redmond (@samredmond) 73 | -------------------------------------------------------------------------------- /installing-python-macos.md: -------------------------------------------------------------------------------- 1 | # Installing Python on macOS 2 | 3 | Hello! 4 | 5 | This document provides a walkthrough to set up a Python development environment for CS 41 on macOS. Alternate versions of this guide exist for [Linux](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-linux.md) and [Windows](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-windows.md) development. 6 | 7 | ## Overview 8 | 9 | In this course, you'll be writing lots of Python code, so it's important to get your development environment set up and ready-to-go. Moreover, we will sometimes need to install dependencies and packages, so we want to make sure that everything gets installed to the right place as well. The tools we learn about in this document will also be useful for any external development you might pursue in Python. 10 | 11 | Throughout this document, we will: 12 | 13 | 1. Install Python 3.10.3 14 | 2. Create a virtual environment using this version of Python. 15 | 3. Inside this environment, install useful packages. 16 | 4. (Optional) Modify the shell startup script to always activate our environment. 17 | 18 | Let's get started! 19 | 20 | ## Install Python 3.10.3 21 | 22 | *Note: If you use `brew` or another package manager for Python installations, see the note at the bottom of this section instead.* 23 | 24 | Navigate to the [Python 3.10.3 download page](https://www.python.org/downloads/) in a web browser. 25 | 26 | Navigate to the top of the page where it says "Looking for Python with a different OS? Python for..." and select your operating system/computer mode. 27 | 28 | After downloading, double-click the downloaded file, and follow the on-screen instructions to install Python 3.10.3 29 | 30 | Let's double check that Python 3.10.3 was installed correctly. 31 | 32 | For the remainder of this setup document, we assume that you have a basic familiarity with the command line. We understand that not everyone will feel comfortable with the command line, because it is usually covered starting in CS107. However, I highly recommend using Nick Troccoli's amazing [CS107 resources](https://web.stanford.edu/class/archive/cs/cs107/cs107.1214/resources/) for this quarter if you feel less experienced, particular the section titled "Common Unix Commands." 33 | 34 | The main takeaway is the following: If you something of the following form in this guide (you'll see this quite a few times!): 35 | 36 | ``` 37 | coopermj$ command 38 | ``` 39 | 40 | Then copy and paste the command into your command line prompt. 41 | 42 | Two quick notes: 43 | 44 | 1. The text before the `$` can vary. It is not necessarily your username. In this case, we are assuming that the username is `coopermj` and that is the text which is shown before the `$` at your command prompt. (On the terminal below, for example, the text before the prompt includes more than just the username, including the current directory). 45 | 2. Below is a quick example of how you may go about running the commands immediately following this list. This is designed to clear up any ambiguity related to running commands at the command line. 46 | 47 | 48 | Open up a command line prompt (likely using Terminal), and run the following commands: 49 | 50 | ``` 51 | coopermj$ which python3 52 | /Library/Frameworks/Python.framework/Versions/3.10/bin/python3 53 | coopermj$ python3 --version 54 | Python 3.10.3 55 | ``` 56 | 57 | If you see the output shown above, then Python 3.10.3 was installed correctly on your machine! 58 | 59 | Let's celebrate by writing some code! Run the following from a command prompt. You should see the following output, which leaves you at an interactive prompt, at which you can write Python code. 60 | 61 | ``` 62 | coopermj$ python3 63 | Python 3.10.3 (v3.10.3:a342a49189, Mar 16 2022, 09:34:18) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin 64 | Type "help", "copyright", "credits" or "license" for more information. 65 | >>> print("Hello world!") 66 | Hello world! 67 | >>> quit() 68 | coopermj$ 69 | ``` 70 | 71 | Try writing some Python (perhaps `print("Hello world!")`) in the interactive interpreter! When you're done, you can exit the interactive interpreter by entering `quit()` at the Python command prompt or by pressing CTRL+D. 72 | 73 | #### Other package managers: `brew` 74 | 75 | [Homebrew](https://brew.sh/) is "the missing package manager for macOS." It's a great way to install, upgrade, and manage many different types of packages on macOS, including Python. If you are not using `brew`, there is no requirement that you start for CS41. However, if you are already using `brew`, you might as well install Python through brew. 76 | 77 | Run `brew install python3`. This will fetch the latest version of Python (which might not be Python 3.10.3, but that's all we can do). 78 | 79 | Then, continue the process above, after the installation of Python 3.10.3. 80 | 81 | ### Troubleshooting 82 | 83 | #### `which python3` shows no output 84 | The `which` command searches your computer for a program matching a name. If `which python3` shows no output, it means that your computer can't find any appropriate `python3`. Pause and reach out to a member of the course staff to help you debug. Include as much detail as you can about the problem. 85 | 86 | #### `python3 --version` does not show `Python 3.10.3` 87 | In this case, the version of Python 3 your computer wants to run is not the Python 3.10.3 that we just downloaded. Pause and reach out to a member of the course staff to help you debug. Include as much detail as you can about the problem. 88 | 89 | ## Create a virtual environment 90 | 91 | We've correctly installed Python, so next we will create a virtual environment. You can learn more about virtual environments [here](https://github.com/stanfordpython/python-handouts/blob/master/virtual-environments.md) or at the end of our [lecture slides](https://stanfordpython.com/#lectures) on Python fundamentals, but for now it is sufficient to think of a virtual environment as an isolated sandbox for Python packages and dependencies. 92 | 93 | Specifically, we will create a folder named `cs41-env` in your computer's home folder. The configuration of our virtual environment will live entirely inside of this folder. 94 | 95 | ``` 96 | coopermj$ python3 --version 97 | Python 3.10.3 98 | coopermj$ python3 -m venv ~/cs41-env 99 | ``` 100 | 101 | If these two lines execute without error, you have successfully created a virtual environment named `cs41-env`. 102 | 103 | *Note: If you move the `cs41-env` folder, some of the internal structure of the virtual environment can break in unpredictable ways. This is one of the drawbacks of standard virtual environments that motivate our more advanced usage of `virtualenvwrapper` later in this document.* 104 | 105 | ### Activating a virtual environment 106 | 107 | For a given terminal session, a virtual environment is either active or inactive at any moment in time. To activate our virtual environment, you will need to run 108 | 109 | ``` 110 | coopermj$ source ~/cs41-env/bin/activate 111 | (cs41-env) coopermj$ 112 | ``` 113 | 114 | *Note: If your shell is `tcsh` or `csh`, you will have to run `source ~/cs41-env/bin/activate.csh` instead. If your shell is `fish`, you will have to run `. ~/cs41-env/bin/activate.fish` instead.* 115 | 116 | Observe that our command prompt, which previously was `coopermj$`, now is `(cs41-env) coopermj$`. This is one method by which you can see whether a virtual environment is activated. 117 | 118 | ### Deactivating a virtual environment 119 | 120 | Deactivating a virtual environment is easy. From an activated environment, simply run 121 | 122 | ``` 123 | (cs41-env) coopermj$ deactivate 124 | coopermj$ 125 | ``` 126 | 127 | Don't worry if you deactivate from an inactive environment. Nothing bad will happen, although you might see a `-bash: deactivate: command not found` error message, which you can safely ignore. 128 | 129 | ### Using an activated virtual environment. 130 | 131 | Let's reactivate our virtual environment to see what's different when a virtual environment is active. 132 | 133 | ``` 134 | coopermj$ source ~/cs41-env/bin/activate 135 | (cs41-env) coopermj$ which python3 136 | /Users/coopermj/cs41-env/bin/python3 137 | (cs41-env) coopermj$ which python 138 | /Users/coopermj/cs41-env/bin/python 139 | (cs41-env) coopermj$ which pip3 140 | /Users/coopermj/cs41-env/bin/pip3 141 | (cs41-env) coopermj$ which pip 142 | /Users/coopermj/cs41-env/bin/pip 143 | ``` 144 | 145 | It looks like all of our python-related commands are now located inside of the virtual environment. That's a good thing! You can confirm this by seeing that `/Users/coopermj/cs41-env/bin:` is the first entry of the string printed by running `echo $PATH`. 146 | 147 | Moreover, observe that: 148 | 149 | ``` 150 | (cs41-env) coopermj$ python3 --version 151 | Python 3.10.3 152 | (cs41-env) coopermj$ python --version 153 | Python 3.10.3 154 | (cs41-env) coopermj$ pip3 --version 155 | pip 21.0.1 from /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip (python 3.10) 156 | (cs41-env) coopermj$ pip --version 157 | pip 21.0.1 from /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pip (python 3.10) 158 | ``` 159 | 160 | The big takeaway is that, inside our active virtual environment, the commands `python` and `pip` now refer to Python 3.10.3 and it's associated package manager. 161 | 162 | For example, when the virtual environment is active, we can enter an interactive Python 3 prompt simply by running: 163 | 164 | ``` 165 | coopermj$ python 166 | Python 3.10.3 (v3.10.3:1a79785e3e, Feb 19 2021, 09:06:10) 167 | [Clang 6.0 (clang-600.0.57)] on darwin 168 | Type "help", "copyright", "credits" or "license" for more information. 169 | >>> 170 | ``` 171 | 172 | *As a reminder, you can quit the interactive Python prompt with `quit()` or CTRL+D.* 173 | 174 | ## Use `pip` to Install Useful Packages 175 | 176 | Next, we'll install useful Python packages that will serve us over the duration of this course. Let's first make sure that we're have activated the virtual environment. 177 | 178 | ``` 179 | coopermj$ source ~/cs41-env/bin/activate 180 | ``` 181 | 182 | Now, we'll update `pip`, Python's builtin package manager, just to make sure it's on the latest version (it should be). 183 | 184 | ``` 185 | (cs41-env) coopermj$ pip install --upgrade pip 186 | Requirement already up-to-date: pip in ./cs41-env/lib/python3.10/site-packages (21.0.1) 187 | ``` 188 | 189 | After, we'll install the suite of Jupyter tools and some additional useful packages. 190 | 191 | *Really, really make sure that you have activated `cs41-env` before running this line!* 192 | 193 | ``` 194 | (cs41-env) coopermj$ pip install "prompt-toolkit==2.0.10" "ipython[all]" jupyter jupyterlab numpy scipy matplotlib nltk scikit-learn requests flask pycodestyle autopep8 Pillow 195 | ``` 196 | 197 | This will produce a huge amount of output, as Python is downloading these third-party libraries and tools from the internet and storing them inside our virtual environment. These packages will be available when our virtual environment is active, but will not necessarily be available if our virtual environment is inactive. For this reason, it's important to always have an active virtual environment when working on code for this class. 198 | 199 | The last few lines of the output should look like the following. If your output is dramatically different from this or the installation failed with an error, pause and get a member of the course staff to help or post on Piazza. 200 | 201 | ``` 202 | Installing collected packages: wcwidth, prompt-toolkit, appnope, ptyprocess, pexpect, parso, jedi, pickleshare, pygments, ipython-genutils, traitlets, decorator, backcall, pytz, babel, sphinxcontrib-serializinghtml, snowballstemmer, urllib3, idna, certifi, chardet, requests, packaging, docutils, sphinxcontrib-jsmath, sphinxcontrib-devhelp, sphinxcontrib-qthelp, imagesize, sphinxcontrib-applehelp, MarkupSafe, jinja2, alabaster, sphinxcontrib-htmlhelp, Sphinx, entrypoints, pandocfilters, jupyterlab-pygments, testpath, mistune, webencodings, bleach, jupyter-core, attrs, pyrsistent, jsonschema, nbformat, defusedxml, pyzmq, tornado, jupyter-client, nest-asyncio, async-generator, nbclient, nbconvert, nose, pycparser, cffi, argon2-cffi, Send2Trash, terminado, ipykernel, prometheus-client, notebook, widgetsnbextension, jupyterlab-widgets, ipywidgets, qtpy, qtconsole, ipyparallel, ipython, jupyter-console, jupyter, sniffio, anyio, jupyter-server, nbclassic, jupyter-packaging, json5, jupyterlab-server, jupyterlab, scipy, click, joblib, regex, tqdm, nltk, threadpoolctl, scikit-learn, Werkzeug, itsdangerous, flask, toml, autopep8 203 | Running setup.py install for pandocfilters ... done 204 | Running setup.py install for pyrsistent ... done 205 | Running setup.py install for nltk ... done 206 | Successfully installed MarkupSafe-1.1.1 Send2Trash-1.5.0 Sphinx-3.5.3 Werkzeug-1.0.1 alabaster-0.7.12 anyio-2.2.0 appnope-0.1.2 argon2-cffi-20.1.0 async-generator-1.10 attrs-20.3.0 autopep8-1.5.6 babel-2.9.0 backcall-0.2.0 bleach-3.3.0 certifi-2020.12.5 cffi-1.14.5 chardet-4.0.0 click-7.1.2 decorator-4.4.2 defusedxml-0.7.1 docutils-0.16 entrypoints-0.3 flask-1.1.2 idna-2.10 imagesize-1.2.0 ipykernel-5.5.0 ipyparallel-6.3.0 ipython-7.22.0 ipython-genutils-0.2.0 ipywidgets-7.6.3 itsdangerous-1.1.0 jedi-0.18.0 jinja2-2.11.3 joblib-1.0.1 json5-0.9.5 jsonschema-3.2.0 jupyter-1.0.0 jupyter-client-6.1.12 jupyter-console-6.4.0 jupyter-core-4.7.1 jupyter-packaging-0.7.12 jupyter-server-1.5.1 jupyterlab-3.0.12 jupyterlab-pygments-0.1.2 jupyterlab-server-2.3.0 jupyterlab-widgets-1.0.0 mistune-0.8.4 nbclassic-0.2.6 nbclient-0.5.3 nbconvert-6.0.7 nbformat-5.1.2 nest-asyncio-1.5.1 nltk-3.5 nose-1.3.7 notebook-6.3.0 packaging-20.9 pandocfilters-1.4.3 parso-0.8.1 pexpect-4.8.0 pickleshare-0.7.5 prometheus-client-0.9.0 prompt-toolkit-2.0.10 ptyprocess-0.7.0 pycparser-2.20 pygments-2.8.1 pyrsistent-0.17.3 pytz-2021.1 pyzmq-22.0.3 qtconsole-5.0.3 qtpy-1.9.0 regex-2021.3.17 requests-2.25.1 scikit-learn-0.24.1 scipy-1.6.2 sniffio-1.2.0 snowballstemmer-2.1.0 sphinxcontrib-applehelp-1.0.2 sphinxcontrib-devhelp-1.0.2 sphinxcontrib-htmlhelp-1.0.3 sphinxcontrib-jsmath-1.0.1 sphinxcontrib-qthelp-1.0.3 sphinxcontrib-serializinghtml-1.1.4 terminado-0.9.3 testpath-0.4.4 threadpoolctl-2.1.0 toml-0.10.2 tornado-6.1 tqdm-4.59.0 traitlets-5.0.5 urllib3-1.26.4 wcwidth-0.2.5 webencodings-0.5.1 widgetsnbextension-3.5.1 207 | ``` 208 | 209 | We will learn more about each of these packages throughout this course. 210 | 211 | Importantly, you should now have access to `ipython`, an interactive Python interpreter that is (in our humble opinion) vastly superior to the default Python interpreter. You can read an overview [here](http://ipython.readthedocs.org/en/stable/overview.html) if you'd like. To make sure `ipython` is configured correctly, run it from a command prompt, and ensure that you get something similar to the below. 212 | 213 | ``` 214 | (cs41-env)$ ipython 215 | Python 3.10.3 (v3.10.3:1a79785e3e, Feb 19 2021, 09:06:10) 216 | Type 'copyright', 'credits' or 'license' for more information 217 | IPython 7.22.0 -- An enhanced Interactive Python. Type '?' for help. 218 | 219 | In [1]: 220 | ``` 221 | 222 | One helpful feature of `ipython` is that you can append a `'?'` to any symbol and Python will try to give you help for that symbol. For example: 223 | 224 | ``` 225 | In [1]: print? 226 | Docstring: 227 | print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) 228 | 229 | Prints the values to a stream, or to sys.stdout by default. 230 | Optional keyword arguments: 231 | file: a file-like object (stream); defaults to the current sys.stdout. 232 | sep: string inserted between values, default a space. 233 | end: string appended after the last value, default a newline. 234 | flush: whether to forcibly flush the stream. 235 | Type: builtin_function_or_method 236 | ``` 237 | 238 | And that's it! You are all done setting up your Python development environment for CS41. 239 | 240 | ## Summary 241 | 242 | First, we installed Python 3.10.3 from the Python website and checked that everything was installed correctly. Next, we used `python3` to create a virtual environment named `cs41-env`, and we learned how to activate and deactivate this virtual environment. Lastly, we activated the environment and installed lots of useful packages. 243 | 244 | **Reminder: Each time you create a new terminal session, you will need to run `source ~/cs41-env/bin/activate`.** 245 | 246 | ## IMPORTANT! Activating virtual environments 247 | 248 | One very important note is that our virtual environment will not be activated by default. This means that, for every new command line session you create (for example, by opening a new tab in Terminal.app or iTerm.app), you will need to run `source ~/cs41-env/bin/activate` to activate the `cs41-env` virtual environment. A good rule to remember is: if you don't see `(cs41-env)` at the start of the command prompt, then the virtual environment is not active! 249 | 250 | In this course, we always assume that you are operating in an active virtual environment. So, it's crucially important that you activate the `cs41-env` environment by running `source ~/cs41-env/bin/activate` in every terminal session you use for this class. 251 | 252 | ### Optional: Automatically enable `cs41-env` 253 | 254 | If you want to automatically enable the `cs41-env` virtual environment every time you start a new interactive session, you can add a command to your shell's startup script. In most cases, this will be `~/.bash_profile` or `~/.bashrc`, which are different but in ways that are not important to us right now. Run: 255 | 256 | ``` 257 | coopermj$ echo "# Activate virtual environment for CS41." >> ~/.bash_profile 258 | coopermj$ echo "source ~/cs41-env/bin/activate" >> ~/.bash_profile 259 | coopermj$ tail -n 2 ~/.bash_profile 260 | # Activate virtual environment for CS41. 261 | source ~/cs41-env/bin/activate 262 | ``` 263 | 264 | This will cause the command `source ~/cs41-env/bin/activate` to be executed every time you open a new terminal session. Since this script gets executed every time you create a new terminal session, the `cs41-env` will be automatically activated. It can still be deactivated by running `deactivate`. 265 | 266 | *Note: If you are using a different shell (`tcsh`, `zsh`, etc) than `bash`, you will need to place this startup command in your appropriate startup script, such as `~/.tcshrc` or `~/.zshrc`.* 267 | 268 | You did it! Celebrate with your friends. 269 | 270 | ## Credit 271 | Much of this handout was based on a similar handout written by Sam Redmond (@samredmond) 272 | -------------------------------------------------------------------------------- /installing-python-windows.md: -------------------------------------------------------------------------------- 1 | # Installing Python on Windows 2 | 3 | We provide three strategies for setting up a Python environment on windows. 4 | 5 | 1. Bash on Ubuntu on Windows 6 | 2. Running Directly on Windows 7 | 3. Using a VM 8 | 9 | We recommend Strategy 1, as it will give you a development environment that is similar enough to the macOS and Linux instructions that you will be able to act almost as if you have a Linux computer. 10 | 11 | We discourage Strategy 2, as it is the most complicated and hardest for us to debug. 12 | 13 | We are fine with Strategy 3, although it is essentially just avoiding the problem by throwing computational resources at it. 14 | 15 | If Strategy 1 or Strategy 2 fail horribly, Strategy 3 will definitely work, but is fairly resource intensive. 16 | 17 | So, we recommend trying out Strategy 1 first. If that fails, decide whether you are willing to allocate a nontrivial amount of computing resources to this course. If so, proceed with Strategy 3. If not, proceed with Strategy 2. 18 | 19 | ## (1) Bash on Ubuntu on Windows 20 | Requires: 64-bit Windows 10, updated to the 2016 Anniversary build or later. *If you regularly download updates, you'll be fine.* 21 | 22 | Windows 10 has added a Ubuntu subsystem which we will use for development in this class. In particular, we'll use the Ubuntu system to download Python and to create a virtual environment for this course. 23 | 24 | First, follow [these instructions](https://www.howtogeek.com/249966/how-to-install-and-use-the-linux-bash-shell-on-windows-10/) from HowToGeek in order to activate the "Windows Subsystem for Linux," get Ubuntu from the Microsoft Store, and launch a `bash` shell on Ubuntu. 25 | 26 | One quick note here: Your Windows file system is located at `/mnt/c` in the Bash shell environment. 27 | 28 | Once you're in the `bash` shell, you can follow the [Linux](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-linux.md) guide, which has more details. If you're just getting started, you may also need to run the following commands: 29 | 30 | ``` 31 | $ sudo add-apt-repository ppa:deadsnakes/ppa 32 | $ sudo apt-get update 33 | $ sudo apt-get install python3.10 34 | $ sudo apt-get install python3.10-venv 35 | ``` 36 | 37 | You can check which version of Python you've installed by running: 38 | 39 | ``` 40 | $ python3 --version 41 | Python 3.10.3 42 | ``` 43 | 44 | In broad strokes, you will need to run the following commands to set up a virtual environment. The Linux and macOS handouts contain more detailed information. 45 | 46 | ``` 47 | $ python3 -m venv "${HOME}/cs41-env" 48 | $ source "${HOME}/cs41-env/bin/activate" 49 | (cs41-env)$ pip install "prompt-toolkit==2.0.10" "ipython[all]" jupyter jupyterlab numpy scipy matplotlib nltk scikit-learn requests flask pycodestyle autopep8 Pillow 50 | (cs41-env)$ deactivate 51 | ``` 52 | 53 | The command `source "${HOME}/cs41-env/bin/activate"` is especially important. **Every time you open a new bash shell, you will need to run `source "${HOME}/cs41-env/bin/activate"` in order to activate your virtual environment.** The `deactivate` command deactivates an active virtual environment. 54 | 55 | You can tell if a virtual environment is active by looking for the parenthesized `(cs41-env)` prefix. 56 | 57 | Working with Windows is complicated enough, so we're going to omit the instructions for how to use `virtualenvwrapper` to set up managed virtual environments. If you're really interested, you can follow the macOS instructions for `virtualenvwrapper`. 58 | 59 | ## (2) Running Directly on Windows 60 | 61 | Recall that we discourage this option as it is very complex and hard for us to debug. Only use this option if the above fails and you don't want to use a VM (Strategy 3) for some reason. 62 | 63 | You will need Windows 8.1 or newer to use Python 3.10.3 on Windows. 64 | 65 | When in doubt, the source of truth for Windows commands is [included in the Python documentation](https://docs.python.org/3/using/windows.html), and you can find more details on using virtual environments [here](https://docs.python.org/3/library/venv.html#module-venv). 66 | 67 | The rough outline is: 68 | 69 | 1. Install Python 3 and sanity check the installation. 70 | 2. Create a virtual environment. 71 | 3. Use `pip` to install useful packages. 72 | 73 | First, download the web-based installer from the [Python 3.10.3 releases page](https://www.python.org/downloads/release/python-392/), either for [x86-64](https://www.python.org/ftp/python/3.10.3/python-3.10.3-amd64-webinstall.exe) or [x86](https://www.python.org/ftp/python/3.10.3/python-3.10.3-webinstall.exe). The web-based installer is a small download which will connect to the internet to download any additional required components, so make sure that you are connected to the internet for the remainder of these installation instructions. 74 | 75 | Start the installer. You will see two options: "Install launcher for all users (recommended)" and "Add Python 3.10 to PATH". Make sure both are selected, and then click "Install Now." 76 | 77 | *Note: Technically, you should also [remove the MAX_PATH limitation](https://docs.python.org/3/using/windows.html#removing-the-max-path-limitation), but we'll skip that for now.* 78 | 79 | Follow the on-screen instructions to finish installing Python. When you are given the option of unchecking any 'optional' components, do not uncheck any. In particular, if there is an option called "Add python.exe to search path" on the "Customize Python 3.10" screen, make sure that box is checked! You should also see that `pip` is being installed by default. 80 | 81 | Let's check to see that everything was installed correctly. 82 | 83 | Open up PowerShell or `cmd.exe` and run the following from a command prompt: 84 | 85 | ``` 86 | > python3 87 | ``` 88 | 89 | You should see something like the following: 90 | 91 | ``` 92 | Python 3.10.3 (v3.10.3:1a79785e3e, Feb 19 2021, 09:06:10) 93 | [Clang 6.0 (clang-600.0.57)] on darwin 94 | Type "help", "copyright", "credits" or "license" for more information. 95 | >>> 96 | ``` 97 | 98 | Ensure that the Python version above looks like 3.10.3. 99 | 100 | If that doesn't work, try running: 101 | 102 | ``` 103 | > python 104 | ``` 105 | 106 | If this drops you into a Python 3.10.3 interactive interpreter, great! In this case, everywhere you see `python3` below, replace it with the command `python`. 107 | 108 | If this didn't work, try running: 109 | 110 | ``` 111 | > py -3 112 | ``` 113 | 114 | If this worked, then everywhere you see `python3` below, replace it with the command `py -3`. 115 | 116 | Try writing some Python in the interactive interpreter! When you're done, you can exit the interactive interpreter with `CTRL+C` or by entering `quit()` at the Python command prompt. 117 | 118 | ### Checking `pip` 119 | First, let's check that we have `pip` installed. For CS41, we'll be using a package manager called `pip` to install and manage Python software packages. By default, Python 3.10.3 ships with a version of `pip` prebuilt. `pip` interacts very well with PyPI (the Python Package Index), so we'll be using `pip` extensively this quarter. 120 | 121 | At a command prompt, run the following code. You should see something like the following output: 122 | 123 | ``` 124 | > python3 -m pip --version 125 | pip 21.0.1 from /pip 21.0.1 from C:\Users\Parth\AppData\Local\Programs\Python\Python38\lib\site-packages (python 3.10) 126 | ``` 127 | 128 | Problems might arise if you had a different version of Python 3 already installed, but if you added Python 3.10 to your PATH, this should work. 129 | 130 | ### Create a Virtual Environment 131 | 132 | Great! Now, let's run the following commands: 133 | 134 | ``` 135 | > python3 -m venv ~\cs41-env 136 | ``` 137 | 138 | If you were having trouble with finding your Python executable in the previous section, you should be able to instead run the following, in which you specify the full path to all arguments: 139 | 140 | ``` 141 | c:\> c:\Python38\python -m venv c:\path\to\myenv 142 | ``` 143 | 144 | This will create a virtual environment in a folder named `cs41-env` inside your home folder. 145 | 146 | To activate the virtual environment, you must run one of the following two commands. If you are using `cmd.exe`, you must run: 147 | 148 | ``` 149 | C:\> ~\cs41-env\Scripts\activate.bat 150 | ``` 151 | 152 | If you are using PowerShell, you should run: 153 | 154 | ``` 155 | PS C:\> ~\cs41-env\Scripts\Activate.ps1 156 | ``` 157 | 158 | As with other OSes, you can deactivate the virtual environment by running `deactivate` in your shell. 159 | 160 | ### Installing packages with `pip` 161 | 162 | Go ahead and activate your virtual environment, using the appropriate command above for either `cmd.exe` or PowerShell. Next, install the following packages into your virtual environment using `pip`: 163 | 164 | ``` 165 | (cs41-env) > pip install "prompt-toolkit==2.0.10" "ipython[all]" jupyter jupyterlab numpy scipy matplotlib nltk scikit-learn requests flask pycodestyle autopep8 Pillow 166 | ``` 167 | 168 | When you're done with that, `deactivate` the virtual environment. 169 | 170 | You're all set! Give yourself a pat on the back. Remember that every time you open a new shell, you will need to activate your virtual environment. 171 | 172 | ## (3) Use a Virtual Machine 173 | 174 | It can be very hard to properly set up development environments on Windows. We're going to give up on Windows, and instead we'll use VirtualBox to run an entire Linux operating system on your Windows computer. First, [download VirtualBox 6.1.0](https://download.virtualbox.org/virtualbox/6.1.0/VirtualBox-6.1.0-135406-Win.exe). Make sure you know where you have downloaded this file. 175 | 176 | Great! We're halfway there. 177 | 178 | Next, you'll need to download a Unix OS. We recommend using [Ubuntu 18.04](https://www.ubuntu.com/download/desktop/thank-you?version=18.04.1&architecture=amd64). Now, 179 | 180 | 1. Launch VirtualBox by double-clicking on the downloaded executable. 181 | 2. Create a new VM instance and point the prompt to the Ubuntu ISO you just downloaded. 182 | 3. VirtualBox will prompt you to configure lots of settings for your new virtual machine. You can use the defaults, or you can adjust the settings if you know what you are doing. Roughly speaking, the more resources you give to your VM, the fewer your normal non-VM computer has. 183 | a. You can name your virtual machine something like `cs41-vm` 184 | 4. Click through the on-screen instructions to finish setting up Ubuntu. 185 | 186 | Ubuntu is a Linux distribution, so from here you should follow the [Linux](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-linux.md) guide that has already been posted. 187 | 188 | If you'd like to be oriented to VirtualBox itself, they have posted [a manual](https://www.virtualbox.org/manual/ch01.html) (warning: it's pretty long) that covers First Steps with VirtualBox. If you only read one section, we recommend "Section 1.9: Running Your Virtual Machine." 189 | 190 | # Credit 191 | Much of this handout was based on a similar handout written by Sam Redmond (@samredmond) 192 | -------------------------------------------------------------------------------- /old/installing-python-brexton.md: -------------------------------------------------------------------------------- 1 | # Installing A Virtual Environment (Mac OS X and Linux) 2 | 3 | Hi there! 4 | 5 | This is a quick tutorial on how to set up pip and virtual environments on your local computer. These are crucial to have at the beginning of the quarter so you are able to install the appropriate dependencies and packages into your computer and also properly install them in the right places. Along with this, these are genuinely useful (& arguably necessary) for any external Python development that you will pursue. So, what are they? 6 | 7 | ## Pip 8 | Pip is a package management system used to install and manage software packages written in Python. You will most likely use pip to install most of your dependencies for your projects. To install pip on your system, open up your terminal, and type in and enter: 9 | 10 | ``` 11 | sudo easy_install pip 12 | ``` 13 | 14 | This will prompt your terminal to ask you for your system password, enter it, and then pip should be installed on your computer. To install any package on your computer globally, just use: 15 | 16 | ``` 17 | pip install some-package-name 18 | ``` 19 | 20 | You can easily remove the package by using: 21 | 22 | ``` 23 | pip uninstall some-package-name 24 | ``` 25 | 26 | But, before you install any more packages globally, let's talk about virtual environments. 27 | 28 | ## Virtual Environments 29 | A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the "Project X depends on version 1.x but, Project Y needs 4.x" dilemma, and keeps your global site-packages directory clean and manageable. 30 | 31 | What does this mean? Well, when you install different libraries and software packages, you are constantly installing specific versions of those packages. If you install it straight on your terminal (globally) without a virtual environment, then your global system will have specific versions that might conflict with a project you might have that might require another version of the same package. 32 | 33 | What do Virtual Environments do? They create folders that contain all the necessary executabels to use the packages that a Python project would need (yes, they are just normal folders found in either Finder or terminal). Virtualenv is a tool to create such isolated Python environments. 34 | 35 | Install virtualenv via pip: 36 | 37 | ``` 38 | $ pip install virtualenv 39 | ``` 40 | 41 | Basic Usage 42 | 1. Create a virtual environment for a project: 43 | 44 | ``` 45 | $ cd my_project_folder 46 | $ virtualenv my_project 47 | ``` 48 | 49 | `virtualenv my_project` will create a folder in the current directory which will contain the Python executable files, and a copy of the pip library which you can use to install other packages. The name of the virtual environment (in this case, it was `my_project`) can be anything; omitting the name will place the files in the current directory instead. 50 | 51 | This creates a copy of Python in whichever directory you ran the command in, placing it in a folder named `my_project`. 52 | 53 | You can also use the Python interpreter of your choice (like python3) 54 | 55 | ``` 56 | $ virtualenv -p my_project 57 | ``` 58 | 59 | 2. To begin using the virtual environment, it needs to be activated: 60 | 61 | ``` 62 | $ source my_project/bin/activate 63 | ``` 64 | 65 | The name of the current virtual environment will now appear on the left of the prompt to let you know that it's active. From now on, any package that you install using pip will be placed in the my_project folder, isolated fromt he global Python installation. 66 | Install packages as usual, for example 67 | 68 | ``` 69 | $ pip install requests 70 | ``` 71 | 3. If you are done working in the virtual environment for the moment, you can deactivate it: 72 | 73 | ``` 74 | $ deactivate 75 | ``` 76 | 77 | This puts you back to the system's default Python interpreter with all its installed libraries. To delete a virtual environment, just delete its folder. 78 | 79 | ## Virtual Environment Wrappers 80 | Next, we'll install virtual environment wrappers. `virtualenvwrapper` provides a set of commands which makes working with virtual environments much more pleasant. It also places all your virtual environments in one place. 81 | 82 | To install (make sure you do this AFTER virtualenv is already installed): 83 | 84 | ``` 85 | $ pip install virtualenvwrapper 86 | $ export WORKON_HOME=$HOME/.virtualenvs 87 | $ source /usr/local/bin/virtualenvwrapper.sh 88 | ``` 89 | 90 | Make sure the third line is the correct path to the virtualenvwrapper.sh on your computer. Run a simple "find" command or search within your Finder if you are not sure what the path is! 91 | 92 | ### Shell Startup File 93 | Add three lines to your shell startup file (.bashrc, .profile, etc.) to set the location where the virtual environments should live, the location of your development project directories, and the location of the script installed with this package: 94 | 95 | ``` 96 | export WORKON_HOME=$HOME/.virtualenvs 97 | export PROJECT_HOME=$HOME/Devel 98 | source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh 99 | ``` 100 | 101 | To make sure that your .bashrc looks like the above, run this command in your terminal: vim ~/.bashrc 102 | After editing it, reload the startup file (e.g., run source ~/.bashrc in your terminal window). 103 | 104 | virtualenvwrapper Quick-Start 105 | 1. Run: `workon` 106 | 2. A list of environments, empty, is printed. 107 | 3. Run: `mkvirtualenv cs41` 108 | 4. A new environment, `cs41` is created and activated. 109 | 5. Run: `workon` 110 | 6. This time, the temp environment is included. 111 | 112 | References: 113 | - [The Hitchhiker's Guide to Python](http://python-guide-pt-br.readthedocs.io/en/latest/dev/virtualenvs/) 114 | - [Pip (package manager)](https://en.wikipedia.org/wiki/Pip_(package_manager)) 115 | -------------------------------------------------------------------------------- /old/installing-python.md: -------------------------------------------------------------------------------- 1 | # Installing Python 3 with Virtual Environments (Mac/Linux) 2 | 3 | In CS41, you'll be writing lots of Python code! Therefore, it's important that you get your development environment ready-to-go as soon as possible. 4 | 5 | These instructions are only for Mac OS X and Linux. If you are developing on a Windows computer, see the [Installing Python for Windows](https://docs.google.com/document/d/1tlARF6fipUhwmMru-hdL-avxLrYwPg1KVEIE3L73S48/edit?usp=sharing) setup guide. 6 | 7 | ## Short Version 8 | 9 | 1. Install Python 3.4.3 10 | 2. Configure `pip` 11 | 3. Create a virtual environment 12 | 4. Install useful packages 13 | 14 | *Disclaimer: These installation instructions have only been tested on Mac OS X - if you find any errors on Linux, please let us know!* 15 | 16 | 17 | ## Installing Python 3.4.3 18 | 19 | Navigate to the [Python 3.4.3 download page](https://www.python.org/downloads/release/python-343/), scroll to the bottom (where it says `Files`) and install the most appropriate distribution of Python. 20 | 21 | --- 22 | ### Mac OS X 23 | If you're running OS X 10.6 or higher, you want the [Mac OS X 64-bit/32-bit installer](https://www.python.org/ftp/python/3.4.3/python-3.4.3-macosx10.6.pkg). After downloading, double-click the downloaded file, and follow the on-screen instructions. 24 | 25 | --- 26 | ### Linux 27 | If you're on Linux, you'll have to build Python from source. Download the source tarball (either [gzipped](https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tgz) or [XZ compressed](https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tar.xz)). Unzip the files and `cd` into the unzipped directory. To build Python, just execute the usual commands: 28 | 29 | ``` 30 | $ ./configure 31 | $ make 32 | $ make test 33 | $ sudo make install 34 | ``` 35 | 36 | *More information on the Linux installation process can be found in the README included in the tarball.* 37 | 38 | --- 39 | 40 | Let's check to see if Python is installed correctly! 41 | 42 | Run the following from a command prompt: 43 | 44 | ``` 45 | $ python3 46 | ``` 47 | 48 | You should see the following: 49 | 50 | ``` 51 | Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 52 | [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin 53 | Type "help", "copyright", "credits" or "license" for more information. 54 | >>> 55 | ``` 56 | 57 | Try writing some Python in the interactive interpreter! When you're done, you can exit the interactive interpreter with CTRL+D or by entering `quit()` at the Python command prompt. 58 | 59 | ## Getting `pip` 60 | 61 | For CS41, we'll be using a package manager called `pip` to install and manage Python software packages. By default, Python 3.4.3 ships with a version of `pip` prebuilt (in our case, `pip3` for Python 3). `pip` interacts very well with PyPI (the Python Package Index), so we'll be using `pip` extensively this quarter. 62 | 63 | First, run the following code at a command prompt. You should see something like the sample output (perhaps different for a different OS) 64 | 65 | ``` 66 | $ python3 -m pip --version 67 | pip 7.1.2 from /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages (python 3.4) 68 | ``` 69 | 70 | If it worked, great! If not, check with a member of the course staff before progressing further. 71 | 72 | ## Configuring Virtual Environment 73 | 74 | The following instructions apply to Mac OS X and Linux. 75 | 76 | Next, we'll install `virtualenvwrapper`. This third-party software allows for the creation of isolated Python environments, so there is no conflict in the event that you maintain multiple Python installations on your device. You will need to grant root privileges to the installation script (thus the `sudo`), so you may need to enter your password. 77 | 78 | Note: `virtualenvwrapper` only works with `bash`, `ksh`, and `zsh`. 79 | 80 | ``` 81 | $ sudo python3 -m pip install virtualenvwrapper 82 | Collecting virtualenvwrapper 83 | Downloading virtualenvwrapper-4.7.1-py2.py3-none-any.whl 84 | Collecting stevedore (from virtualenvwrapper) 85 | Downloading stevedore-1.12.0-py2.py3-none-any.whl 86 | Collecting virtualenv (from virtualenvwrapper) 87 | Downloading virtualenv-15.0.1-py2.py3-none-any.whl (1.8MB) 88 | 100% |████████████████████████████████| 1.8MB 381kB/s 89 | Collecting virtualenv-clone (from virtualenvwrapper) 90 | Downloading virtualenv-clone-0.2.6.tar.gz 91 | Collecting pbr>=1.6 (from stevedore->virtualenvwrapper) 92 | Downloading pbr-1.8.1-py2.py3-none-any.whl (89kB) 93 | 100% |████████████████████████████████| 90kB 4.3MB/s 94 | Collecting six>=1.9.0 (from stevedore->virtualenvwrapper) 95 | Downloading six-1.10.0-py2.py3-none-any.whl 96 | Building wheels for collected packages: virtualenv-clone 97 | Running setup.py bdist_wheel for virtualenv-clone 98 | Stored in directory: /Users//Library/Caches/pip/wheels/ 99 | Successfully built virtualenv-clone 100 | Installing collected packages: pbr, six, stevedore, virtualenv, virtualenv-clone, virtualenvwrapper 101 | Successfully installed pbr-1.8.1 six-1.10.0 stevedore-1.12.0 virtualenv-15.0.1 virtualenv-clone-0.2.6 virtualenvwrapper-4.7.1 102 | ``` 103 | 104 | Next, we'll need to do some one-time setup to configure the virtual environment for this class. 105 | 106 | ``` 107 | $ export WORKON_HOME=$HOME/.virtualenvs 108 | $ export VIRTUALENVWRAPPER_PYTHON=`which python3` 109 | ``` 110 | 111 | This instructs the `virtualenvwrapper` utility to store all of your virtual environments in the folder `.virtualenvs/` in your home directory. 112 | 113 | Next, let's see where we installed the `virtualenvwrapper.sh` script. 114 | 115 | On a Mac, the easiest way to do this is with `mdfind`, which emulates the behavior of Spotlight. 116 | 117 | ``` 118 | $ mdfind virtualenvwrapper.sh 119 | /Library/Frameworks/Python.framework/Versions/3.4/bin/virtualenvwrapper.sh 120 | /usr/local/bin/virtualenvwrapper.sh 121 | $ 122 | ``` 123 | 124 | Copy the first result to your clipboard. If you see no results, or if you see an error like `mdfind: Command not found.`, try the (slower but also effective) command: 125 | 126 | ``` 127 | $ find / -name virtualenvwrapper.sh 128 | < ... lots of output ... > 129 | /Library/Frameworks/Python.framework/Versions/3.4/bin/virtualenvwrapper.sh 130 | /usr/local/bin/virtualenvwrapper.sh 131 | $ 132 | ``` 133 | 134 | Copy the first result to your clipboard if you didn't have any luck with `mdfind`. 135 | 136 | If there are no results from the `find` command, go back and make sure that you have successfully installed `virtualenvwrapper`. If further problems persist, contact a staff member. 137 | 138 | Next, we're going to set up our virtual environment manager: 139 | 140 | ``` 141 | $ source 142 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/premkproject 143 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/postmkproject 144 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/initialize 145 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/premkvirtualenv 146 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/postmkvirtualenv 147 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/prermvirtualenv 148 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/postrmvirtualenv 149 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/predeactivate 150 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/postdeactivate 151 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/preactivate 152 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/postactivate 153 | virtualenvwrapper.user_scripts creating /Users/sredmond/.virtualenvs/get_env_details 154 | ``` 155 | where `` is the path that you found and copied in the previous step. 156 | 157 | For example, you might run `source /Library/Frameworks/Python.framework/Versions/3.4/bin/virtualenvwrapper.sh` or `source /usr/local/bin/virtualenvwrapper.sh` 158 | 159 | In order to make sure everything went smoothly, run `workon` from the command prompt. This command prints a list of environments, currently empty. 160 | 161 | ``` 162 | $ workon 163 | $ 164 | ``` 165 | 166 | Now, we'll actually create the virtual environment for CS41. You can name your virtual environment anything you want, but we recommend a short, easy-to-remember name. When you run `mkvirtualenv`, a new environment is created, and we specify the particular version of Python to use via the `--python` option. 167 | 168 | ``` 169 | $ mkvirtualenv --python=`which python3` cs41 170 | Running virtualenv with interpreter /usr/local/bin/python3 171 | Using base prefix '/Library/Frameworks/Python.framework/Versions/3.4' 172 | New python executable in cs41/bin/python3 173 | Also creating executable in cs41/bin/python 174 | Installing setuptools, pip, wheel...done. 175 | virtualenvwrapper.user_scripts creating /Users//.virtualenvs/cs41/bin/predeactivate 176 | virtualenvwrapper.user_scripts creating /Users//.virtualenvs/cs41/bin/postdeactivate 177 | virtualenvwrapper.user_scripts creating /Users//.virtualenvs/cs41/bin/preactivate 178 | virtualenvwrapper.user_scripts creating /Users//.virtualenvs/cs41/bin/postactivate 179 | virtualenvwrapper.user_scripts creating /Users//.virtualenvs/cs41/bin/get_env_details 180 | ``` 181 | 182 | Now, if you run `workon`, you should see the list of all environments, which now includes `cs41`. 183 | 184 | ``` 185 | (cs41)$ workon 186 | cs41 187 | $ 188 | ``` 189 | 190 | ### Observations 191 | 192 | You may notice that your command prompt now has the name of the active environment, cs41, printed before it. For example, if your old command prompt was 193 | 194 | ``` 195 | sredmond:stanfordpython$ 196 | ``` 197 | 198 | your new command prompt would be 199 | 200 | ``` 201 | sredmond:stanfordpython$ workon cs41 202 | (cs41)sredmond:stanfordpython$ 203 | ``` 204 | 205 | If you see this parenthesized environment name, it means that your environment is active. To deactivate the environment, simply run 206 | 207 | ``` 208 | (cs41)$ deactivate 209 | $ 210 | ``` 211 | 212 | from a command prompt and you should see the parenthesized environment name disappear. 213 | 214 | Let's make sure everything is running smoothly. Run all of the following commands and ensure that the output is appropriate. 215 | 216 | ``` 217 | # Checking `python` 218 | (cs41)$ which python 219 | /Users//.virtualenvs/cs41/bin/python 220 | (cs41)$ python --version 221 | Python 3.4.3 222 | (cs41)$ python -c "print('Hello world.')" 223 | Hello world. 224 | 225 | # Testing `pip` 226 | (cs41)$ which pip 227 | /Users//.virtualenvs/cs41/bin/pip 228 | (cs41)$ pip --version 229 | pip 7.1.2 from /Users//.virtualenvs/cs41/lib/python3.4/site-packages (python 3.4) 230 | ``` 231 | 232 | Lastly, we'll install some useful packages that will make development a lot easier. 233 | 234 | 235 | ## Using `pip`: Installing Awesome Packages 236 | 237 | Run the following commands. You should see lots of output, but I've omitted it here. 238 | ``` 239 | (cs41)$ pip install --upgrade pip # Make sure `pip` is the newest version 240 | (cs41)$ pip install "ipython[all]" # For ipython interactive interpreter and more 241 | ``` 242 | 243 | Most relevantly, you should now have access to `ipython`, an interactive Python interpreter that is vastly superior to the default Python interpreter. You can read an overview [here](http://ipython.readthedocs.org/en/stable/overview.html) if you'd like. To make sure `ipython` is configured correctly, run it from a command prompt, and ensure that you get something similar to the below. 244 | 245 | ``` 246 | (cs41)$ ipython 247 | Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) 248 | Type "copyright", "credits" or "license" for more information. 249 | 250 | IPython 4.1.2 -- An enhanced Interactive Python. 251 | ? -> Introduction and overview of IPython's features. 252 | %quickref -> Quick reference. 253 | help -> Python's own help system. 254 | object? -> Details about 'object', use 'object??' for extra details. 255 | 256 | In [1]: 257 | ``` 258 | 259 | ## Important Note 260 | Every time you develop code for CS41, you will need to run `workon cs41` in order to activate your virtual environment. Again, to deactivate it, you can run `deactivate`. It might be convenient to add `workon cs41` to your shell startup script. 261 | 262 | On Mac OS X running bash, you can accomplish this with 263 | 264 | ``` 265 | $ echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.bash_profile 266 | $ echo "export VIRTUALENVWRAPPER_PYTHON=`which python3`" >> ~/.bash_profile 267 | $ echo "source " >> ~/.bash_profile 268 | ``` 269 | 270 | Additionally, if you want to automatically activate the CS41 virtual environment when you start a new shell session, you can also run: 271 | 272 | ``` 273 | $ echo "workon cs41" >> ~/.bash_profile 274 | ``` 275 | 276 | so that `workon cs41` is executed at shell startup time. 277 | 278 | To see that everything was appended correctly, run 279 | 280 | ``` 281 | $ tail ~/.bash_profile 282 | < ... possibly some other stuff ... > 283 | export WORKON_HOME=/Users/sredmond/.virtualenvs 284 | export VIRTUALENVWRAPPER_PYTHON=/Library/Frameworks/Python.framework/Versions/3.4/bin/python3 285 | source /Library/Frameworks/Python.framework/Versions/3.4/bin/virtualenvwrapper.sh 286 | workon cs41 # Optional 287 | ``` 288 | 289 | or something similar. 290 | 291 | If you have a different shell startup script (for example, `~/.profile`), you will need to append the same line to the end of that startup script. 292 | 293 | Try opening a new Terminal / iTerm window, and running `workon cs41`, `python`, `ipython`, and `deactivate`. 294 | 295 | ### Aside: Text Editors 296 | 297 | In CS41, we'll be using Sublime Text 3 for development, although Sublime Text 2 will also be fine. You are, of course, free to choose any text editor you please (vim/emacs/nano/xcode/idle/atom/textedit/notepad/etc). On most operating systems, you can provide a default application to open all files of a given type. In our case, you may find it helpful to make every `.py` file open in Sublime Text. 298 | 299 | > With <3 by @sredmond 300 | -------------------------------------------------------------------------------- /old/submitting-assignments.md: -------------------------------------------------------------------------------- 1 | # CS41 Submission Instructions 2 | 3 | At a high level, submitting code for CS41 consists of 2 major parts. 4 | 5 | 1. Upload your files to Stanford's AFS server 6 | 2. Submit your program using `/usr/class/cs41/tools/submit` 7 | 8 | Easy, right? Let's chat in more detail. 9 | 10 | If you've already taken CS107 and feel comfortable with Unix, skip to the section titled "Upload Files to Myth." 11 | 12 | *In all of the below examples, content inside angle braces (``) should be replaced with the correct information.* 13 | 14 | ## Background Information 15 | 16 | ### Overview 17 | 18 | Everything we'll do this quarter involves running commands on Unix. Developed in the 70s at Bell Labs, Unix is an operating system, like Windows, Android or MacOS. Over the years, Unix and its derivatives and cousins, including Linux, have become ubiquitous. In fact, MacOS X is built on Unix and lets you access its Unix insides through the Terminal (more on that later). Although technically Linux (that we'll use in this class) isn't Unix, but rather a copy-cat of Unix rebuilt from the ground up to address some of Unix's limitations. However, the interface that users (that's us!) see is so similar that for the purposes of this class "Linux" and "Unix" are synonymous. 19 | 20 | In CS41, we'll be submitting assignments on "myth," a cluster of computers in the basement of Gates running Ubuntu Linux. The myth computers themselves are physically located in Gates B08. You can also use them remotely to do assignments, because the room is not always available to everyone. 21 | 22 | ### Logging into `myth` with SSH 23 | 24 | The first step of this assignment is to set up your own computer to log in to myth. Logging in through a program called ssh will allow you to work on the myth computers in a way that is indistinguishable from being physically in the Gates B08 room. While some version of ssh is available on all kinds of computers, the exact details of this step will be different depending on what kind of computer you have: 25 | 26 | - [MacOS](https://web.stanford.edu/class/cs107/assign0/macos.html): Use this if you have your own Mac or you are on a Stanford lab machine in libraries, dorms, etc. 27 | - [Windows](https://web.stanford.edu/class/cs107/assign0/windows.html): Use this if you have a Windows computer. 28 | - [Linux](https://web.stanford.edu/class/cs107/assign0/linux.html): Use this if you have a Linux computer. 29 | 30 | Do not proceed until you have seen `myth`'s successful login welcome text, as shown at the links above. 31 | 32 | ### Upload/Downloading Files with FTP/SCP 33 | 34 | The above instructions allow you to access `myth` to do things on `myth` - edit your code, run your code, debug your code, submit your code, and so on. What it doesn't allow you to do is to bring any files that are on `myth` back with you to your own computer. To do that, you'll need an FTP/SCP file transfer program. There are several options for this, again varying based on your operating system. But one reliable approach is probably just to use [Stanford's AFS web interface](https://afs.stanford.edu). You'll be asked to log in to Stanford as you would for Axess and other secure Stanford websites (unless you are already logged in to one of those at the moment). It will then take you to a list of all the files on your myth account. Click the download icon next to any file to download it. You can also upload files using this web interface, and files you add will be visible when you ssh to myth. 35 | 36 | ## Upload Files to Myth 37 | 38 | **TL:DR** 39 | 40 | ``` 41 | $ ssh @myth.stanford.edu "mkdir -p ~/cs41/assign{0,1,2,3,4}" 42 | $ scp -r @myth.stanford.edu:~/cs41/ 43 | ``` 44 | 45 | *Note: you should replace every instance of `` with your own SUNetID.* 46 | 47 | ### Create Folder Structure on AFS 48 | 49 | First, you can optionally construct a folder for your submission to land in - we suggest `~/cs41/`. 50 | 51 | If you're on a Macintosh or Linux computer, you can run 52 | 53 | ``` 54 | $ ssh @myth.stanford.edu "mkdir -p ~/cs41/assign{0,1,2,3,4}" 55 | ``` 56 | 57 | It may ask for your password, in which case you should type in your Stanford (SUNet) password. Don't worry if it doesn't appear as you type it - it's not supposed to! 58 | 59 | If you're on a Windows computer, you can use a graphical interface ([SecureFX](https://uit.stanford.edu/software/securefx), [FileZilla](https://filezilla-project.org/), [Fugu](http://rsug.itd.umich.edu/software/fugu/)) or a specialized Unix-ish terminal ([cmder](http://cmder.net/), [powershell](https://msdn.microsoft.com/en-us/powershell/scripting/setup/installing-windows-powershell), [MobaXterm](http://mobaxterm.mobatek.net/)) to accomplish this task, but you can *also* do it with the [AFS web client](https://afs.stanford.edu)! Hooray! 60 | 61 | Go to [afs.stanford.edu](https://afs.stanford.edu) and click "Create a New Folder" on the left hand side. Name the new folder `cs41`! Inside this folder, create five new folders: 62 | 63 | ``` 64 | assign0/ 65 | assign1/ 66 | assign2/ 67 | assign3/ 68 | assign4/ 69 | ``` 70 | 71 | When done, you should see something like this: 72 | ![AFS Structure](https://raw.githubusercontent.com/stanfordpython/python-handouts/master/img/afs-structure.png) 73 | 74 | ### Upload files to AFS 75 | 76 | On Mac/Linux, you need to copy your files over to the FarmShare servers. You can do this via 77 | 78 | ``` 79 | $ scp -r @myth.stanford.edu:~/cs41/ 80 | ``` 81 | 82 | where `` is a filepath identifying the directory your solution code is in, and `` is your SUNetID. 83 | 84 | On Windows, if you have an `scp` tool, you can do the same thing. Otherwise, you can use one of the GUI programs or specialized terminals (described at the start of this file) or just upload your files manually via the [WebAFS client](https://afs.stanford.edu). 85 | 86 | ## Submitting Code! 87 | 88 | **TL:DR** 89 | 90 | ``` 91 | $ ssh @myth.stanford.edu 92 | myth$ cd ~/cs41// 93 | myth$ /usr/class/cs41/tools/sanitycheck ./ 94 | myth$ /usr/class/cs41/tools/submit ./ 95 | ``` 96 | 97 | We providing both a `sanitycheck` tool and a `submit` tool. 98 | 99 | If you're on Windows, you'll need to SSH into Stanford FarmShare (`myth`, `corn`, etc.). Hopefully, you already know how to do this, but if not, University IT has some [good solutions](https://uit.stanford.edu/service/sharedcomputing/loggingin), if the earlier SSH solutions didn't work. 100 | 101 | ### sanitycheck 102 | 103 | The `sanitycheck` script, in general, will exercise some basic functionality of your assignment. It isn't extensive, and we'll be testing your code on more advanced test cases, but it should provide you with some confidence that everything is at least set up correctly and working properly on basic inputs. 104 | 105 | When logged into myth (or another of the Stanford computer clusters), first navigate to your submission directory. From there, you test your code by running 106 | 107 | ``` 108 | myth$ /usr/class/cs41/tools/sanitycheck ./ 109 | ``` 110 | 111 | ### submit 112 | 113 | When you're ready to submit, make sure that you're currently in your submission directory (you can check by running `pwd` on myth), and run 114 | 115 | ``` 116 | myth$ /usr/class/cs41/tools/submit 117 | ``` 118 | 119 | You should get output that looks something like: 120 | 121 | ``` 122 | Hello, sredmond 123 | Which assignment are you submitting? 124 | * Please enter the assignment number 125 | 0: Welcome to Python 126 | 1: Cryptography 127 | 2: Quest for the Holy Grail 128 | 3: Stylize 129 | 4: Final Project 130 | > 0 131 | Submission for Assignment #0 132 | This isn't a question - but it's the last step... I'm about to upload all files in the current folder to AFS. Hit ENTER to confirm this is desired. 133 | ``` 134 | 135 | Note that you have the option to run sanity check before submitting. 136 | 137 | ## Notes 138 | 139 | There are a few important things to consider: 140 | 141 | 1. Every time that you want to submit a new version of your assignment, you must upload your changed files to AFS (myth), and run `/usr/class/cs41/tools/submit` 142 | 2. We'll grade the most recent assignment that you submit. 143 | 3. Make sure that you're running the `tools` scripts from inside your assignment directory! Otherwise there might be some weird errors. 144 | 145 | ## Credit 146 | 147 | Several sections of this handout were copied, verbatim, from Cynthia's incredible [CS107 introductory materials](https://web.stanford.edu/class/cs107/assign0/), and some instructive commands (especially for SCPing from Windows) came from [CS221's submission instructions](http://web.stanford.edu/class/cs221/). It wouldn't be possible without them! -------------------------------------------------------------------------------- /old/virtualenv.md: -------------------------------------------------------------------------------- 1 | # Virtual Environments 2 | 3 | ## What is a virtual environment? 4 | A virtual environment is simply an isolated folder that contains all the executables you need to build something awesome in Python, including code to run the interpreter, use the standard library (https://docs.python.org/3.4/library/), and install other 3rd-party libraries that we'll touch on towards the end of the quarter. 5 | 6 | ## Why bother using virtual environments? 7 | Of course, you can also develop Python projects without a virtual environment, but it's a good idea to become familiar with this tool because you can avoid dependency conflicts between your system-wide Python installations and your project-specific Python installations. For example, if you're using Python to build 3 separate Web apps because you're a beast, Project A might depend on Django version 1.2 while Project C depends on Django version 1.9 (yes, Django is the name of a real Web framework: https://docs.djangoproject.com/en/1.9/releases/). You can create a separate virtual environment for each project then install whichever version you need in each project. When you ship awesome projects later in your Python career, you'll know the exact libraries and versions that your project requires (: 8 | 9 | ## How to create virtual environment 10 | In class we audibled to using a piece of software called virtualenv to build virtual environments because some people had trouble with the virtualenvwrapper software. After you've installed Python3 and pip (see https://github.com/stanfordpython/python-handouts/blob/master/installing-python.md#linux if you need help with this step), you're almost done. Here's the rest of the commands to execute: 11 | 12 | ### Install the software (only do this once) 13 | `$ pip install virtualenv` 14 | 15 | this uses pip to install the software used to build your virtual environments, called virtualenv 16 | 17 | ### Creating a virtual environment 18 | cd to your Desktop then execute 19 | 20 | `$ virtualenv cs41` 21 | 22 | this uses virtualenv to create a new virtual environment in the working directory named cs41. you should be able to see this folder on your Desktop now. 23 | 24 | ### Activating and deactivating a virtual environment 25 | To activate, simply cd into the environment we created above then execute 26 | 27 | `$ source bin/activate` 28 | 29 | Now you can play with the interactive interpreter inside your isolated environment using 30 | 31 | `$ python3` 32 | 33 | You can also create new files, modules, whatever you need to make a beautiful Python project ready to ship! 34 | To deactivate, type 35 | 36 | `$ deactivate` 37 | 38 | All done! If you want to read more about the above steps, check out http://docs.python-guide.org/en/latest/dev/virtualenvs/ 39 | 40 | If you want to read about the interactive interpreter, check out http://www.python-course.eu/python3_interactive.php 41 | 42 | 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /submitting-assignments.md: -------------------------------------------------------------------------------- 1 | # CS41 Submission Instructions 2 | 3 | In CS41, we will submit assignments using [Paperless](https://paperless.stanford.edu/), an online tool that lets the course staff download, test, grade, and comment on your code without using paper copies. 4 | 5 | You may be familiar with the Paperless submission process from the CS106 series of courses. We will use Paperless in almost the exact same way. 6 | 7 | ## Detailed Instructions 8 | 9 | 1. Open [the Paperless website](https://paperless.stanford.edu) in Google Chrome or Firefox. 10 | 2. Click on CS41, where you should be listed as a student. 11 | 3. Click "Submit Assignment" in the top-right. 12 | 4. Select which assignment you would like to submit from the dropdown. Once you do this, an area should appear where you may upload your assignment files. 13 | 5. Drag and drop your assignment files into the area marked "Files."" This will add to the list of files to upload. 14 | 6. Click "Submit Assignment". Once your project is submitted, you will be taken back to the main page of the Paperless website. 15 | 7. Confirm that your files were properly submitted. You can view your submission on the Paperless website, which is what the grader will see when grading your submission, by clicking on the "Assignments" tab at the top. You are responsible for checking Paperless to make sure that your files were submitted properly. 16 | 17 | You may make as many new submissions as you would like by repeating the steps above. We will receive only the most recent submission. 18 | 19 | You must submit all of the files necessary to run your program. These files will typically by Python (`.py`) files containing programs. However, particularly if you are extending the program (say, because you've added some extra features in search of a + or ++), you may also have additional image files or audio files that form part of the submission and should also be submitted. 20 | 21 | ## Browser Compatibility 22 | 23 | Paperless works on Google Chrome and Firefox, so ideally use one of those browsers to submit your code. It also usually works on Safari but has some latent issues. Do not use Internet Explorer to upload submissions to Paperless. 24 | 25 | ## Submission Time 26 | 27 | Whether an assignment is submitted on time is determined by the time we receive your electronic submission, which is timestamped in the submission process. That time is based on the time on the server that receives the assignment, so it pays to submit 28 | things with a few minutes to spare, particularly if you discover that your computer’s clock is running 29 | slow. 30 | 31 | ## Back Up Your Work 32 | 33 | Although we work hard to keep track of all the assignments that come in, assignments have sometimes not been received as expected. If your assignment goes missing, you will need to resubmit. *To make resubmission possible, you are responsible for keeping a backup copy of your work.* 34 | 35 | ## Credit 36 | 37 | Based on similar handouts written by Eric Roberts, Mehran Sahami, Keith Schwarz, Marty Stepp, and Jeremy Keeshin. 38 | -------------------------------------------------------------------------------- /term_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/stanfordpython/python-handouts/89aedaa93af92c58ec2d0511836a5c04579eb23e/term_example.png -------------------------------------------------------------------------------- /virtual-environments.md: -------------------------------------------------------------------------------- 1 | # Virtual Environments Primer 2 | 3 | This document is meant as a supplement to our Installing Python series: 4 | 5 | - [Installing Python for macOS](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-macos.md) 6 | - [Installing Python for Linux](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-linux.md) 7 | - [Installing Python for Windows](https://github.com/stanfordpython/python-handouts/blob/master/installing-python-windows.md) 8 | 9 | ## Using virtual environments 10 | 11 | Once you have a virtual environment set up for a project or for a course, there's only one important thing to remember. **Activate your virtual environment every time you open a new shell.** We'll see what this means and how to do this later in this document. For now, if you only take away one thing, it should be that you should run `source ~/cs41-env/bin/activate` every time you open a new shell. If you want to get fancy, you can even add this line to your shell startup script (like `~/.bashrc` or `~/.bash_profile`) so it is executed automatically on shell startup. 12 | 13 | ## What is a virtual environment? 14 | A virtual environment is simply an isolated folder that contains all the executables you need to build something awesome in Python, including code to run the Python interpreter, use [the standard library] (https://docs.python.org/3/library/), and install other third-party libraries that we'll need later in the quarter. Importantly, a virtual environment will keep all of these things in one place (inside the virtual environment folder), so that your local development environment is isolated from the rest of your computer. 15 | 16 | ## Why bother using virtual environments? 17 | Of course, you could also develop Python projects without a virtual environment, but it's a good idea to become familiar with this tool. 18 | 19 | Suppose that you want to use version 2 of the `foo` library but another application requires version 1 of `foo` (this comes up a lot!). How can you have both these applications on your computer at the same time? If you install everything into `/usr/lib/python3.7/site-packages` (or whatever your platform's standard location is), you could easily end up in a sticky situation, in which you might unintentionally upgrade an application that shouldn't be upgraded. 20 | 21 | More generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application. 22 | 23 | Also, perhaps you can't install packages into the global directory, maybe because you're on a shared host like `rice`. 24 | 25 | In all of these cases, a virtual environment can isolate a project's development and execution environment and make programming in Python a breeze. 26 | 27 | 28 | ## Creating a virtual environment 29 | In Python 3.6+, the recommended way to create a virtual environment is to run: 30 | 31 | ``` 32 | $ python3 -m venv /path/to/new/virtual/environment 33 | ``` 34 | 35 | Make sure that `python3` resolves to whichever version of Python 3 you'd like to bind to your virtual environment. 36 | 37 | For example, to create a new virtual environment for CS41 named `cs41-env` in your home folder, you could run: 38 | 39 | ``` 40 | $ python3 -m venv ~/cs41-env 41 | ``` 42 | 43 | ## Activation and Deactivation 44 | To activate a virtual environment on macOS or Linux running `bash` or `zsh`, `source` the following path: 45 | 46 | ``` 47 | $ source ~/cs41-env/bin/activate 48 | ``` 49 | 50 | You can replace `~/cs41-env/bin/activate` with the corresponding path if you created your virtual environment in a different location. 51 | 52 | If you're using a different shell, you'll need to run a different command: 53 | 54 | - `fish`: `$ . ~/cs41-env/bin/activate.fish` 55 | - `csh/tcsh`: `$ source ~/cs41-env/bin/activate.csh` 56 | - `cmd.exe` (Windows): `> ~\cs41-env\Scripts\activate.bat` 57 | - `PowerShell` (Windows): `PS> ~\cs41-env\Scripts\Activate.ps1` 58 | 59 | When a virtual environment is activated, you will see a prefix on your prompt, so it will look like this: 60 | 61 | ``` 62 | (cs41-env)$ 63 | ``` 64 | 65 | Now that we have an active virtual environment, we can play around with it: 66 | 67 | ``` 68 | (cs41-env)$ python --version 69 | (cs41-env)$ pip --version 70 | (cs41-env)$ python 71 | >>> print("Hello world!") 72 | Hello world! 73 | >>> quit() 74 | (cs41-env)$ 75 | ``` 76 | 77 | You can create new files, modules, and whatever else you need to make a beautiful Python project! 78 | 79 | Most importantly, when a virtual environment is activated, you can install Python packages into this virtual environment using `pip`. For example, to install the numerical Python package `numpy`, run: 80 | 81 | ``` 82 | (cs41-env)$ pip install numpy 83 | ``` 84 | 85 | To deactivate, type 86 | 87 | ``` 88 | (cs41-env)$ deactivate 89 | $ 90 | ``` 91 | 92 | That's it! 93 | 94 | ## Last words and alternatives 95 | 96 | To reiterate, **activate your virtual environment every time you open a new shell.** 97 | 98 | Also, know that you should not move your virtual environment folder (in the above, that's `~/cs41-env`), as it is subject to break if it is relocated. 99 | 100 | There are also some alternatives to virtual environments that operate at a higher level, but are a little more complicated to set up. You can use `virtualenvwrapper` to manage virtual environments in a single place, or the even-higher-level tool `pipenv` to automatically handle everything. You can read more [here](https://docs.python-guide.org/dev/virtualenvs/). 101 | 102 | ## Credit 103 | 104 | Much credit goes to [Python's `venv` documentation](https://docs.python.org/3/library/venv.html) and numerous other online tutorials. 105 | 106 | 107 | --------------------------------------------------------------------------------