Text
stringlengths
1
9.41k
Say you’re collaborating with Jane on a new game written in Python. You both want to be able to run and test your code in the same environment.
With venv, again, you can create a virtual environment just for that project, and share instructions as to how to set up the environment.
That way, you can ensure if your project uses package XYZ, that you and Jane both have the exact same version of package XYZ in your respective virtual environments.
If you work with multiple collaborators on multiple projects, this kind of isolation and control is essential. So that’s why we want to use venv.
Virtual environments allow us to create isolated installations of Python, along with installed modules.
We often create virtual environments for specific projects—so that installing or uninstalling modules for one project does not break the other project or your OS-installed Python. A virtual environment isn’t anything magical.
It’s just a directory (folder) which contains (among other things) its own version of Python, installed modules, and some utility scripts. The venv module supports creating lightweight “virtual environments”, each with their own independent set of Python packages installed in their site directories.
A virtual environment is created on top of an existing Python installation, known as the virtual environment’s “base” Python, and may ----- optionally be isolated from the packages in the base environment, so only those explicitly installed in the virtual environment are available. When used from within a virtual en...
At a command prompt, ``` $ python -m venv [name of or path to environment] ``` where $ represents the command prompt, and we substitute in the name of the environment we wish to create.
So if we want to create a virtual environment called “cs1210” we’d use this command: ``` $ python -m venv cs1210 ``` This creates a virtual environment named cs1210 in the current directory (you may wish to create your virtual environment elsewhere, but that’s up to you). � If you get an error complaining that there ...
If you find yourself in that situation, just substitute python3 or, on some OSs, ``` py, for python wherever it appears in the instructions. ``` In order to use a virtual environment it must be activated.
Once activated, any installations of modules will install the modules into the virtual environment.
Python, when running in this virtual environment will have access to all installed modules. On macOS ``` $ .
./cs1210/bin/activate (cs1210) $ ``` On Windows (with PowerShell) ``` PS C:\your\path\here > .\cs1210\Scripts\activate (cs1210) PS C:\your\path\here > ``` Notice that in each case after activation, the command prompt changed.
The prefix, in this case (cs1210) indicates the virtual environment that is currently active. When you’re done using a virtual environment you can deactivate it. To deactivate, use the deactivate command. ----- If you work in multiple virtual environments on different projects you can just deactivate one virtual env...
I have my virtual environment activated. Now what? Installation, upgrading, and uninstallation of third-party Python modules is done with pip.
pip is an acronym for package installer for Python. pip is the preferred installer program.
Starting with Python 3.4, it is included by default with the Python binary installers. – Python documentation When you ask pip to install a module, it will fetch the necessary files from PyPI—the public repository of Python packages—then build and install to whatever environment is active.
For example, we can use pip to install the colorama package (colorama is a module that facilitates displaying colored text). First, before using pip make sure you have a virtual environment active.
Notice that in the examples that follow, this virtual environment is called my_venv (what you call yours is up to you).
Example: ``` (my_venv) $ pip install colorama Collecting colorama Using cached colorama-0.4.6-py2.py3-none-any.whl (25 kB) Installing collected packages: colorama Successfully installed colorama-0.4.6 (my_venv) $ ``` At this point, the colorama package is installed and ready for use.
Pretty easy, huh? To see what packages you have in your virtual environment you can use pip freeze. This will report all installed packages, along with dependencies and version information.
You can save this information to a file and share this with others.
Then all they need to do is install using this list with pip install -r <filename here> (requirements.txt is commonly used). [For more information and documentation, see: https://docs.python.](https://docs.python.org/3/installing/index.html) [org/3/installing/index.html](https://docs.python.org/3/installing/index.html)...
Oftentimes, we want to read data from a file or write data to a file.
Accordingly, we must have some basic understanding of files and file systems. While file systems will vary somewhat based on your operating system—macOS, Linux, or Windows—file systems share common features.
First, they include files and directories (also called “folders”), second, they are organized hierarchically, and third, there is some physical _device on which they are stored._ The physical device on which files and directories are stored is usually a hard disk drive (HDD) or solid state drive (SSD).
Your laptop or desktop computer will have at least one of these. Files and directories stored on such a device are arranged hierarchically in a tree-like structure.
This means that directories can contain files or other directories. Each physical device will have a “root” directory, and may have multiple directories as branches.
You may think of files as leaves on a branch.
The location of each element in the file system is represented as a path going from the root to the element in question. For example, the file on my laptop that contains the text you are reading right now has the path ``` /Users/clayton/Workspace/UVM/Instructor/cs1210/book/... ...appendix_d_file_systems/_file_systems...
Subsequent slashes separate _segments in the path.
All the intermediate elements are directory names._ The last element is the actual file: _file_systems.qmd. This is to say that on my laptop’s SSD, there’s the root directory.
The root directory contains a directory called Users.
Within the Users directory, there’s another directory called clayton, within that, a directory called Workspace, and so on. All modern operating systems provide a graphical user interface for browsing and interacting with the file system (for example, searching for files; creating, moving, deleting, or renaming files o...
This is typical for all operating systems.
Every element in your file system has a unique path, indicating how to get from the root to that element, be it a directory or file. **Filename extensions** Filenames usually include an extension which is used to indicate the type of file it is.
For example, Python files have a .py extension, as in ``` hello_world.py.
Other file types make use of different extensions: .txt ``` for plain-text files, .md for Markdown files, .csv for comma-separated value files, and so on. It’s important to note that changing a filename extension doesn’t change the content of a file—you can’t convert Python source code to a PDF by changing the extensi...
For example, if you have a data file in CSV format with a .csv extension, double-clicking it will most likely launch Excel if you’re using Microsoft Windows, or Numbers if you’re using macOS.
Sometimes this behavior is desirable, sometimes it ----- is not.
All operating systems allow you to change such associations if you wish. **The good, the bad, the ugly** One nice thing about modern operating systems is that they provide great search tools to find files in your file system.
Just enter a keyword, or portion of a file name, and the file browser will show you your file. This is quite handy, and in many cases it eliminates the need to browse the file system to a particular location in search of a file. One not-so-nice thing about modern operating systems is that they provide great search tool...
This means that casual users often have no idea where a file is actually located—what directory it’s contained in, or its full path.
The convenience of search functionality can obscure (or make entirely invisible) the hierarchical structure of your file system. **Differences between operating systems** While all modern file systems share the general features outlined above, there are some minor differences.
For example, macOS and Linux use “/” to separate path segments (in a command line interface), while Windows uses “\”.
Windows assigns drive letters to disk drives, the default for the boot disk on a Windows machine being C.
So on a Windows machine, the path to this file (given above), might be something like this instead: ``` C:\Users\clayton\Workspace\UVM\Instructor\cs1210\book\... ...appendix_d_file_systems\_file_systems.qmd ``` Different operating systems provide different GUIs, but they behave similarly.
macOS has the Finder, Windows has its File Explorer, and most Linux distributions offer a choice of file browser: Nautilus, Dolphin, Thunar, Nemo, and Konqueror to name a few.
Again, while these are somewhat different, they all provide similar interfaces to similar file systems. You should familiarize yourself with the file browser for your OS.
Make sure you can: - browse to any given location in your file system, - find a file without using the built-in search functionality, - rename a file, - delete a file, - create a new, empty folder. **Modern IDEs and browsing files** Many integrated development environments (IDEs) provide a built-in fil...
All have built-in file browsers. ----- **Figure D.1: File browser in Thonny** Some of these file browsers support drag-and-drop operations (for example, to move a file from one directory to another, to move a file from outside a project into a project, etc.).
Others do not. You should familiarize yourself with the file browser within the IDE of your choice.
Make sure you can: - browse to a given file, - create a new Python file (with .py extension), - open a plain-text file (for example, either .txt or .csv file extension), and - rename, move, and delete files. ----- #### Appendix E ### Flow charts Flow charts are a convenient and often used tool for repr...
They can help us reason about the behavior of a program before we start writing it. If we have a good flow chart, this can be a useful “blueprint” for a program. We’ll begin with the basics.
The most commonly used elements of a flow chart are: - ellipses, which indicate the start or end of a program’s execution, - rectangles, which indicate performing some calculation or task, - diamonds, which indicate a decision, and - directed edges (a.k.a.
arrows), which indicate process flow. **Figure E.1: Basic flow chart elements** Diamonds (decisions) have one input and two outputs. It is at these points that we test some condition.
We refer to this as branching—our 369 ----- path through or flow chart can follow one of two branches. If the condition is true, we take one branch.
If the condition is false, we take the other branch. **Figure E.2: Branches** ###### A minimal example Here’s a minimal example—a program which prompts a user for an integer, n, and then, if n is even, the program prints “n is even”, otherwise the program prints “n is odd!” In order to determine whether n is even or...
(This assumes, of course, that the user has entered a valid integer.) Here’s what the flow chart for this program looks like: 1Remember, if we have some integer 𝑛, then it must be the case that either 𝑛≡0 mod 2 or 𝑛≡1 mod 2.
Those are the only possibilities. ----- **Figure E.3: Even or odd** - We start at the top (the ellipse labeled “start”). - From there, we proceed to the next step: prompting the user for an integer, n. - Then we test to see if the remainder when we divide n by two equals zero. **– If it does, we follow the...
How do we do this with comparisons that only yield True or False? The answer is: with more _than one comparison!_ First we’ll check to see if the number is greater than zero.
If it is, it’s positive. But what if it is not greater than zero? Well, in that case, the number could be negative or it could be zero. There are no other possibilities. Why?
Because we’ve already ruled out the possibility of the number being positive (by the previous comparison). Here’s a flow chart: **Figure E.4: Positive, negative, or zero** As before, we start at the ellipse labeled “start.” Then we prompt the user for a float, x.
Then we reach the first decision point: Is x greater ----- than zero?
If it is, we know x is positive, we follow the left branch, we print “x is positive”, and we’re done. If x is not positive, we follow the right branch.
This portion of the flow chart is only executed if the first test yields False (that is, x is not greater than zero). Here, we’re faced with another choice: Is x less than zero?
If it is, we know x is negative, we follow the left branch (from our second decision point), we print “x is negative”, and we’re done. There’s one last branch: the one we’d follow if x is neither positive nor negative—so it must be zero.
If we follow this branch, we print “x is zero”, and we’re done. Here it is in Python, ``` """ CS 1210 Positive, negative, or zero? Using nested if. """ x = float(input('Please enter an real number: ')) if x > 0: print('x is positive!') else: if x < 0: print('x is negative!') else: ...
We can implement the flow chart for our three-way decision using elif, thus: ``` """ CS 1210 Positive, negative, or zero? Using elif. """ x = float(input('Please enter an real number: ')) if x > 0: print('x is positive!') elif x < 0: print('x is negative!') else: print('x is zero!') ``` B...
In some cases, the choice is largely a matter of taste. In other cases, we may have reason to prefer one or the other.
All things being equal (in terms of ----- behavior), I think the elif solution presented here is the more elegant of the two. In any event, I hope you see that flow charts are a useful tool for diagramming the desired behavior of a program.
With a good flow chart, implementation can be made easier. You should feel free to draw flow charts of programs before you write your code.
You may find that this helps clarify your thinking and provides a plan of attack. ----- #### Appendix F ### Code for cover artwork Here is the code used to generate the tessellated pattern used on the cover of this book.
It’s written in Python, and makes use of the DrawSVG package.
It’s included here because it’s a concise example of a complete Python program which includes docstrings (module and function), imported Python modules, an imported third-party module, constants, functions and functional decomposition, and driver code.
This is all written in conformance to PEP 8 (or as close as I could manage with the constraint of formatting for book page). ``` """ Cover background for ITPACS. Clayton Cafiero <cbcafier@uvm.edu> Requires DrawSVG package. To install DrawSVG: `$ pip install "drawsvg[raster]~=2.2"` See: https://pypi.org/proj...
Going for that green and gold! COLORS = ['goldenrod', 'lightseagreen', 'lightgreen', 'gold', 'cyan', 'olivedrab', 'cadetblue', 'darkgreen', 'lawngreen', 'green', 'teal', 'darkseagreen', 'palegreen', 'orange', ``` 375 ----- ``` 'khaki', 'turquoise', 'mediumspringgreen', 'lawngre...
""" transform = f'rotate({rotate}, 0, 0)' # angle, cx, cy return draw.Lines(0, 0, TRAPEZOID_BASE, 0, TRAPEZOID_BASE_SEGMENT + TRAPEZOID_LEG, TRAPEZOID_HEIGHT, TRAPEZOID_BASE_SEGMENT, TRAPEZOID_HEIGHT, 0, TILE_HEIGHT, -TRAPEZO...
""" transform = f'translate({trans_x}, {trans_y})' c = draw.Group(fill='none', stroke='black', transform=transform) c.append(draw_tile(0, colors_[0])) c.append(draw_tile(120, colors_[1])) c.append(draw_tile(240, colors_[2])) return c if __name__ == '__main__': d = draw.Drawing(COVER_...
----- #### Learning Python Part I, Getting Started We begin with a general overview of Python that answers commonly asked initial questions—why people use the language, what it’s useful for, and so on.
The first chapter introduces the major ideas underlying the technology to give you some background context.
Then the technical material of the book begins, as we explore the ways that both we and Python run programs.
The goal of this part of the book is to give you just enough information to be able to follow along with later examples and exercises. Part II, Types and Operations Next, we begin our tour of the Python language, studying Python’s major built-in object types in depth: numbers, lists, dictionaries, and so on.
You can get a lot done in Python with these tools alone. This is the most substantial part of the book because we lay groundwork here for later chapters.
We’ll also look at dynamic typing and its references—keys to using Python well—in this part. **f** **|** ----- Part III, Statements and Syntax The next part moves on to introduce Python’s statements—the code you type to create and process objects in Python.
It also presents Python’s general syntax model.
Although this part focuses on syntax, it also introduces some related tools, such as the PyDoc system, and explores coding alternatives. Part IV, Functions This part begins our look at Python’s higher-level program structure tools.
Func_tions turn out to be a simple way to package code for reuse and avoid code redun-_ dancy.
In this part, we will explore Python’s scoping rules, argument-passing techniques, and more. Part V, Modules Python modules let you organize statements and functions into larger components, and this part illustrates how to create, use, and reload modules.
We’ll also look at some more advanced topics here, such as module packages, module reloading, and the __name__ variable. Part VI, Classes and OOP Here, we explore Python’s object-oriented programming tool, the class—an optional but powerful way to structure code for customization and reuse.
As you’ll see, classes mostly reuse ideas we will have covered by this point in the book, and OOP in Python is mostly about looking up names in linked objects.
As you’ll also see, OOP is optional in Python, but it can shave development time substantially, especially for long-term strategic project development. Part VII, Exceptions and Tools We conclude the language fundamentals coverage in this text with a look at Python’s exception handling model and statements, plus a bri...
Although exceptions are a fairly lightweight tool, this part appears after the discussion of classes because exceptions should now all be classes. Part VIII, Advanced Topics (new in the fourth edition) In the final part, we explore some advanced topics.
Here, we study Unicode and byte strings, managed attribute tools like properties and descriptors, function and class decorators, and metaclasses.
These chapters are all optional reading, because not all programmers need to understand the subjects they address.
On the other hand, readers who must process internationalized text or binary data, or are responsible for developing APIs for other programmers to use, should find something of interest in this part. Part IX, Appendixes The book wraps up with a pair of appendixes that give platform-specific tips for using Python on v...
Solutions to end-of-chapter quizzes appear in the chapters themselves. **|** **f** ----- Note that the index and table of contents can be used to hunt for details, but there are no reference appendixes in this book (this book is a tutorial, not a reference).
As mentioned earlier, you can consult Python Pocket Reference, as well as other books, and the free Python reference manuals maintained at _http://www.python.org for syntax and_ built-in tool details. ###### Book Updates Improvements happen (and so do mis^H^H^H typos).
Updates, supplements, and corrections for this book will be maintained (or referenced) on the Web at one of the following sites: _http://www.oreilly.com/catalog/9780596158064 (O’Reilly’s web page for the book)_ _http://www.rmi.net/~lutz (the author’s site)_ _http://www.rmi.net/~lutz/about-lp.html (the author’s web pag...