Windows machines usually do not ship with Python installed. Installing on Windows is pretty simple.
Download the latest Python 3 Installer from python.org (Links to an external site.) (make sure you pay attention to 32-bit vs. 64-bit and select the right one for your machine).
Run the installer and make sure you check the box that says "Add Python 3.x to PATH" to ensure that you place the interpreter in your execution path.
Most likely, your Linux distribution already has Python installed. However, it is likely to be Python 2 and not Python 3.
You can determine what version you have by opening a terminal and typing python --version
. If the version shown is Python 2.x.x
, then you want to install the latest version of Python 3.
The procedure for installing the latest version of Python depends on which distribution of Linux you are running.
Use this article (Links to an external site.) to find instructions specific to your Linux distribution.
Current versions of macOS include a version of Python 2, but you want to be using Python 3.
The best way to install Python 3 on macOS is to use the Homebrew package manager.
Install Homebrew
Go to http://brew.sh/ (Links to an external site.) and select the Homebrew bootstrap code under "Install Homebrew" and copy the complete command to your clipboard.
Open a terminal window, paste the Homebrew bootstrap code, and hit "Enter."
It may take some time to install Homebrew, so you need to wait for that process to complete before moving on.
After Homebrew has finished its installation process, you then need to install Python.
Install Python
Open a terminal and run the following command brew install python3
. This command will download and install the latest version of Python.
Ensure that everything was installed correctly by opening a terminal window and running the command pip3
.
If you see help text from Python's "pip" package manager, you have a working Python installation.
Here are a few websites that give you online access to the Python interpreter:
Before you do anything else, search for a solution to your problem on your own. One thing you should start doing is keeping track of all your research when solving a problem. One easy way to do this is to have a browser window represent a specific search for a solution, and each open tab represents an attempt at solving it. Keeping track of your research is vital because it's helpful to provide examples of similar questions or similar problems and explain why those didn't answer your specific problem or question. It also helps the person answering your question avoid pointing you toward resources you've already explored, and lets them know that you've already put in the work.
The first thing you do when you ask a question is to introduce the problem. The first paragraph of your written question should serve as an executive summary of the problem. All the following paragraphs should fill in the details of the problem.
An important thing to include in your problem introduction is a precise explanation of how you encountered the problem. Write about the difficulties that kept you from solving it. Describe what you already tried and include the results of the research you've done.
You should also provide as much detail about the context as possible. For instance, include the language version, the platform version, the operating system, the database type, specific IDE, and any web server information. You should also include your particular constraints. For example, you may not be allowed to use feature A or B that would provide an obvious solution. If you have an odd constraint, it may also help explain why you have that constraint.
One thing to remember is that not all questions benefit from including code. However, if you include code, definitely do not just copy in your entire program! By having irrelevant details, you make your question much harder to answer and decrease the chances of someone helping you.
Here are some guidelines for when to include code in your question.
Include just enough code to allow others to reproduce your specific problem. One way to do this is to restart from scratch. Do not include snippets of your entire program. Instead, create a new program, but only add what's necessary to recreate the problem.
If you aren't exactly sure where the problem code is, one way to find it is by removing code chunks one at a time until the problem disappears — then add back the last part. This way, you can deduce that the last piece of code you added back is likely the source of your problem.
Be careful not to remove too much code, either. Keep your question brief, but maintain enough context for clarity.
Make sure you include all the portions of the code needed to reproduce the problem. It would be best if you assumed that the person who is answering your question would not write any code to reproduce your issue. Again, remember, do not use images of code—those trying to help you need direct access to the code you include in your question.
When you include your code, it's also important to tell the reader exactly what you expect the behavior to be. Be sure to show the reader the exact wording of the error message you encountered (if there was one). It's also crucial to double-check that your included example reproduces the problem.
One other thing you can do is create a live example on a site like sqlfiddle.com or jsbin.com. If you do, make sure you also include a copy of your code in your question. Not everyone will utilize the link to the live example.
And to reiterate, do not post images of any code, data, or error messages—reserve images for things like rendering bugs—things that are impossible to describe accurately with just text.
Don't send a question you haven't proofread. When you post your question, you should have already read and reread it, taking care to follow all the best practices and making sure your question makes sense. It would be best if you imagined that you're coming to your question fresh, with no other context but the question itself. You want to make your question as easy for someone to answer as possible. Remember, the reader is likely choosing between several questions they could answer. You want your question to stand out as something concise and approachable. Don't forget to double-check your spelling, grammar, and formatting. Keep it as straightforward as you can; you're not writing a novel.
As feedback and responses to your question begin coming in, respond as quickly as possible. You'll likely receive clarifying questions, and your readers need that clarification to help you.
Now let's look at an example of a question posted to Stack Overflow and analyze it to see if it follows the best practices outlined above.
The question (Links to an external site.):
The first thing to notice is that the post has a short but descriptive title that adequately summarizes the question.
Accessing the index in 'for' loops?
Next, did the questioner provide any additional context or proof of the research they've done so far? It doesn't look like it. They could improve the question by including what they tried and the resources they explored.
The questioner did an excellent job of introducing the question and including code that shows what they are trying to do. In this case, they did not need to include experience vs. expected behavior; they just needed to have the expected behavior. By clearly stating what the desired result was, it helped the person answering to respond appropriately.
The code they included is a minimal and complete example, allowing someone to reproduce the problem quickly. The questioner left out irrelevant details and code that would've distracted from the primary question. They also included an example of what the desired output would be, which is helpful.
It appears the questioner proofread their question beforehand as it does not contain any glaring spelling, grammar, or formatting problems. However, we could critique this example for including a redundant sentence at the end. Instead of including that sentence, they might have rephrased the first sentence of the question to be more precise.
Choose a real-world example from a recent problem/challenge. Use the guidelines and process outlined above to ask for help in your cohort-specific help channel.
Identify an unanswered question in your cohort-specific help channel. Do your best to provide a helpful response to that question.
Find an example of a bad question on Stack Overflow. Analyze the question using the guidelines above and write a short response explaining why you believe it is a bad question.
Find an example of a good question on Stack Overflow. Analyze the question using the guidelines above and write a short response explaining why you believe it is a good question.
Learning to use the print
function in Python is the perfect way to start writing Python code. When learning to write in any new programming language, one of the first things you want to do is get some output from your program. The print
function is how you output the value of an object to the screen. You will learn how to use the print
function in Python.
print
with different objectsLet's start by executing the print function to print different types of objects in Python. There are numerous types of objects that you can print using the print
function.
Using print
with no arguments:
Notice the empty line after calling the print
function. The default end
value when calling print is the newline character \n
.
Using print
with a string literal:
Notice how calling print
with the string literal printed the exact string we passed in onto the screen.
Using print
with a variable:
Notice how calling print
with the slogan
variable prints the value assigned to the slogan
variable.
Using print
with an expression:
Notice how the argument for the print
function can be an expression. Once the expression is resolved to a string object, the print
function can output it to the screen.
Using print
with other object types:
Any object passed as an argument into print
will get converted into a string type before outputted to the screen.
You can see how the print
function is easy to use and how it can handle any object type that you pass into it.
print
Now, let's look at how we can pass multiple arguments into the print
function. Using print
with multiple arguments gives you a flexible and easy way to output items to the screen.
We can pass multiple objects, all of the same or different types, into print
.
Notice how each object we passed in was converted to a string and then output to the screen. Notice also that print
used " "
as the default separator value.
We can change the separator value by assigning a value to the keyword argument sep
.
end
value with print
You can also specify the end
value by assigning a value to the end
keyword argument when you call the print
function. Being able to print a value to the screen but allow the user to stay on the same line is useful and necessary in some cases.
Here is how you can change the default end
value (which is \n
) when calling the print
function.
Customizing the end
value when calling the print
function can be useful and necessary in some circumstances.
You have now learned the basics of using the print
function in Python. You learned how to call the print
function to print objects of different types. You now know how to use print
with multiple positional arguments. In certain necessary situations, you also know how to change the default end
value when calling the print
function.
Now, get some practice using the print
function by completing the challenge below.
Python is unique because indentation instead of some other character marks blocks of code. A block of code is a collection of statements that are grouped. The syntax for denoting blocks varies from language to language. For example, in C, blocks are delimited by curly braces ({
and }
). Understanding how Python uses whitespace and indentation to denote logical lines and code blocks is essential.
Whitespace is any character represented by something that appears empty (usually \t
or " "
). The characters that Python considers to be whitespace can be seen by printing out the value of string.whitespace
from the string
library.
Notice the characters are " "
(space), \t
(tab), \n
(newline), \r
(return), \x0b
(unicode line tabulation), and \x0c
(unicode form feed).
You've seen the different types of whitespace characters that can appear, but you mainly need to concern yourself with " "
, \t
, and \n
.
Whitespace is used to denote the end of a logical line of code. In Python, a logical line of code's end (a statement or a definition) is marked by a \n
.
Notice how the REPL evaluates the expression first + second
when I return on line 3. Below that, I can write one logical line of code over multiple lines by ending each line with a \
character. That \
character lets the Python interpreter that even though there is a newline, you don't want it to treat it as the end of a logical line.
It's important to understand that Python assumes meaning in newline characters when trying to interpret your code.
Whitespace (indentation) can denote code blocks. Python gives meaning to the amount of whitespace (indentation level) that comes before a logical line of code.
This code raises an Indentation Error
because the Python interpreter expects to find additional whitespace inside the if
block.
The Python interpreter can successfully run this code because consistent whitespace (level of indentation) is used.
Although you can't tell in the code snippet above, for the second if
statement, I used a \t
to indent. But, for the indentation on print("it worked!"
, I used eight " "
(spaces). The mismatch of tab usage and spaces raises an error when Python tries to interpret the code.
Consistent whitespace usage (indentation) is crucial to making sure that Python can interpret your code correctly.
In Python, whitespace has meaning; it denotes the end of logical lines and also code blocks. Whitespace is any character represented by something that appears empty, although the most common characters are " "
, \t
, and \n
. The Python interpreter knows where the end of a logical line of code is because of the \n
. The amount of whitespace (level of indentation) is used in Python to denote blocks of code. Understanding how the Python interpreter looks at whitespace is vital to writing valid Python code.
Python is not a "statically typed" language, and every variable in Python is an object. You don't have to declare a variable's type.
In Python, you can have integers and floating-point numbers.
You can define an integer like so:
You can also cast a floating-point number to be an integer like so:
To define a floating-point number, you can declare it literally or typecast it with the float constructor function:
You can define strings with either single or double quotes:
It's common to use double quotes for strings so that you can include apostrophes without accidentally terminating the string.
Let's practice declaring variables to store an int, a float, and a string:
There are a few basic operators that you should be familiar with as you start writing Python code.
You can use the addition (+
), subtraction (-
), multiplication (*
), and division (/
) operators with numbers in Python.
There is also an operator called the modulo operator (%
). This operator returns the remainder of integer division.
You can use two multiplication operators to make the exponentiation operator (**
).
You can use the addition operator to concatenate strings and lists:
You can also use the multiplication operator to create a new list or string that repeats the original sequence:
Now, let's see if we can combine all of this information in a quick demo.
First, let's create two variables, a
and b
, where each variable stores an instance of the object
class.
Next, let's see if we can make two lists, one containing five instances of a
, and the second with five instances of b
.
Then, let's combine a_list
and b_list
into a combined
list.
If our code works as expected, combined
should have a length of 10.
To format a string in Python, you use the %
operator to format a set of stored variables in a tuple. You also include argument specifiers in your string with special symbols like %s
and %d
.
For example, let's say you want to insert a name
variable inside a string. You would do the following:
If you have more than one argument specifier, you need to enclose your arguments in a tuple:
Any object that is not a string can also be formatted using the %s
operator. The string which returns from the object's repr
method will be used in the formatted string.
A few of the common argument specifiers are:
%s
- String (or any object with a string representation)
%d
- Integers
%f
- Floating point numbers
%.<number of digits>f
- Floating point numbers with a fixed amount of digits to the dot's right.
%x/%X
- Integers in hexadecimal (lowercase/uppercase)
Let's see if we can use all of this information to practice formatting a few strings.
Let's imagine that we have some data that we want to inject into a string.
We need to print a formatted string using argument specifiers and a tuple that contains our data:
8
You can think of a string as anything between quotes. Strings store a sequence of characters or bits of text.
There are lots of ways you can interact with strings in Python.
The len()
method prints out the number of characters in the string.
The index()
method prints out the index of the substring argument's first occurrence.
The count()
method returns the number of occurrences of the substring argument.
To slice a string, you can use this syntax: [start:stop:step]
. To reverse the string's order, you can set the step value to be -1
.
You can convert a string to uppercase or lowercase with the upper()
and lower()
methods.
You can determine if a string starts with or ends with a specific sequence with the startswith()
and endswith()
methods.
The split()
method allows you to split up a string into a list. The default separator is any whitespace. You can also specify the separator value with an argument if you want.
You can think of a string as anything between quotes. Strings store a sequence of characters or bits of text.
There are lots of ways you can interact with strings in Python.
The len()
method prints out the number of characters in the string.
The index()
method prints out the index of the substring argument's first occurrence.
The count()
method returns the number of occurrences of the substring argument.
To slice a string, you can use this syntax: [start:stop:step]
. To reverse the string's order, you can set the step value to be -1
.
You can convert a string to uppercase or lowercase with the upper()
and lower()
methods.
You can determine if a string starts with or ends with a specific sequence with the startswith()
and endswith()
methods.
The split()
method allows you to split up a string into a list. The default separator is any whitespace. You can also specify the separator value with an argument if you want.
Python uses boolean values to evaluate conditions. An expression in any Boolean context will evaluate to a Boolean value and then control your program's flow. Python's boolean values are written as True
and False
(make sure you capitalize the first character).
To compare the value of two expressions for equality, you use the ==
operator. You can also use <
(less than), >
(greater than), <=
(less than or equal), >=
(greater than or equal), and !=
(not equal).
You build up more complex boolean expressions by using the and
and or
operators.
Any time you have an iterable object (like a list), you can check if a specific item exists inside that iterable by using the in
operator.
We can use the if
, elif
, and the else
keywords to define a series of code blocks that will execute conditionally.
Any object that is considered "empty" evaluates to False
. For example, ""
, []
, and 0
all evaluate to False
.
If we want to determine if two objects are actually the same instance in memory, we use the is
operator instead of the value comparison operator ==
.
There is also the not
operator, which inverts the boolean that follows it:
You can use two types of loops in Python, a for
loop and a while
loop. A for
loop iterates over a given sequence (iterator expression). A while
loop repeats as long as a boolean context evaluates to True
.
The break
statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break
statement is inside a nested loop (loop inside another loop), the break
statement will only terminate the innermost loop.
You can use the continue
statement to skip the rest of the code inside a loop for the current iteration only. The loop does not terminate entirely but continues with the next iteration.
Here is an example of a few different ways you can use a range
as the iterable for a for
loop.
This example shows the simple usage of a while
loop to print the same values as the for
loops above.
You can use a break
statement to exit a for
loop or a while
loop.
You can also use a continue
statement to skip the current block but not exit the loop entirely.
To make our code more readable and DRY (Don't Repeat Yourself), we often want to encapsulate code inside a callable function.
To define a function in Python, we follow this syntax:
Let's define a greeting function that allows us to specify a name and a specific greeting.
Now, we can call our greet
function and pass in the data that we want.
If we want to define a function that returns a value to the caller, we use the return
keyword.
Python uses boolean values to evaluate conditions. An expression in any Boolean context will evaluate to a Boolean value and then control your program's flow. Python's boolean values are written as True
and False
(make sure you capitalize the first character).
To compare the value of two expressions for equality, you use the ==
operator. You can also use <
(less than), >
(greater than), <=
(less than or equal), >=
(greater than or equal), and !=
(not equal).
You build up more complex boolean expressions by using the and
and or
operators.
Any time you have an iterable object (like a list), you can check if a specific item exists inside that iterable by using the in
operator.
We can use the if
, elif
, and the else
keywords to define a series of code blocks that will execute conditionally.
Any object that is considered "empty" evaluates to False
. For example, ""
, []
, and 0
all evaluate to False
.
If we want to determine if two objects are actually the same instance in memory, we use the is
operator instead of the value comparison operator ==
.
There is also the not
operator, which inverts the boolean that follows it:
Note: the following instructions assume that you are connected to the Internet and that you have both the main
and universe
package repositories enabled. All unix shell commands are assumed to be running from your home directory ($HOME). Finally, any command that begins with sudo
assums that you have administrative rights on your machine. If you do not — please ask your system administrator about installing the software you need.
What follows are instructions for setting up an Ubuntu 16.04 (Xenial) home environment for use with this book. I use Ubuntu GNU/Linux for both development and testing of the book, so it is the only system about which I can personally answer setup and configuration questions.
In the spirit of software freedom and open collaboration, please contact me if you would like to maintain a similar appendix for your own favorite system. I’d be more than happy to link to it or put it on the Open Book Project site, provided you agree to answer user feedback concerning it.
Thanks!Jeffrey ElknerArlington, Virginia
Ubuntu 16.04 comes with both Python 2 and Python 3 installed. Typing python
at the shell prompt still launches Python 2. Use the command python3
for Python 3.
In addition to the debian packages in the Ubuntu Package archive, we will be using Python software from the Python Package Index or PyPI. The tool for installing packages from PyPI is called pip. Since we want Python 3 packages installed which will work with the Python 3 already on our Ubuntu system, we will use the Ubuntu python3-pip debian package.
To add this package run following from the unix command prompt:
Now would also be a good time to install a few other packages you will want to have on your system:
This will install the Tkinter GUI toolkit, the pep8 Python style checker, and the bzr revision control system which we will use to grab some program examples.
Bottle is a micro web application framework written in Python. It is used in this book to introduce web application development.
To install bottle
run:
Then try:
at the python prompt to varify that it is working.
Vim can be used very effectively for Python development, but Ubuntu only comes with the vim-tiny
package installed by default, so it doesn’t support color syntax highlighting or auto-indenting.
To use Vim, do the following:
From the unix command prompt, run:
Create a file in your home directory named .vimrc
that contains the following:
When you edit a file with a .py
extension, you should now have color systax highlighting and auto indenting. Pressing the <f3>
key should run your program, and bring you back to the editor when the program completes. <f4>
runs the program with the verbose (-v
) switch set, which will be helpful when running doctests. <f8>
will run the pep8 style checker against your program source, which is useful in helping you learn to write Python programs with good styling.
To learn to use vim, run the following command at a unix command prompt:
The following creates a useful environment in your home directory for using pip3
to install packages into your home directory and for adding your own Python libraries and executable scripts:
From the command prompt in your home directory, create bin
and lib
subdirectories of your .local
directory by running the following command:
Now add a my_python
subdirectory to .local/lib
:
Add the following lines to the bottom of your .bashrc
in your home directory:
This will set your prefered editor to Vim, add your own .local/bin
directory as a place to put executable scripts, and add .local/lib/my_python
to your Python search path so modules you put there will be found by Python.
Then run:
to set these environment varialbles and prepend the .local/bin
directory to your search path (note: logging out and back in will accomplish the same result).
Lumpy is python module that generates UML diagrams. It was written by Allen B. Downey as part of his Swampy suite of Python programs written for use with his textbooks.
The version here is modified to work with Python 3 on Ubuntu 16.04. Click on lumpy.py
to download the module. Put this file in your .local/lib/my_python
directory after your $HOME environment is configured.
Lumpy is used in several of the exercises in this book to help illustrate python data structures.
On unix systems, Python scripts can be made executable using the following process:
Add this line as the first line in the script:
At the unix command prompt, type the following to make myscript.py
executable:
Move myscript.py
into your .local/bin
directory, and it will be runnable from anywhere.
Brian "Beej Jorgensen" Hall edited this page on May 29, 2020 · 1 revision
NOTE: pipenv is optional! We don't use it in CS. But it's a neat package manager if you get into more complex Python projects. It can be a headache of an install for some people. You can safely ignore anything about pipenv below if you don't want to mess with it.
We'll want to install Python 3 (version 3.x), which is the runtime for the language itself. The runtime is what allows you to execute Python code and files by typing python [file_or_code_to_execute]
in your terminal. You can also open up a Python REPL (Read-Eval-Print Loop) to quickly and easily mess around with Python code once you've gotten the runtime installed. If you recall how Node let's you execute and run JavaScript code locally on your machine instead of having to rely on the browser, the Python runtime pretty much let's you do the same thing but with Python code.
Additionally, we'll be talking about how to install the (optional) pipenv virtual environment manager. Think of it as the npm
of Python (though pipenv is also capable of performing a bunch of other tasks as well, most notably running your Python projects in an isolated virtual environment).
Unfortunately, we haven't found a way to get Anaconda to play nicely with pipenv. If you get them working together, please let your instructor know how you did it.
If you can run python
or python3
and see a 3.7 or later version, you're good to go:
or on some systems, Python 3 is just python
:
And optionally try pipenv
:
Otherwise, keep reading. :)
While macOS comes with Python 2, we need to get Python 3 in there as well.
If you don't have Brew installed, follow the instructions on the brew website.
Use Brew to install Python and pipenv at the Terminal prompt:
Note: Git Bash doesn't seem to cooperate if you're trying to install Python on Windows. Try another terminal like Powershell.
Recommend updating Windows to the latest version.
Python 3 is in the Windows Store and can be installed from there.
When installing the official package, be sure to check the
checkbox!!
This is what worked for Beej. YMMV.
Install Python, as per above.
Bring up a shell (cmd.exe or Powershell)
Run py -m pip
Run py -m pip install --user pipenv
At this point, you should be able to always run pipenv with py -m pipenv
, but that's a little inconvenient. Read on for making it easier.
You'll see a message like this in the pipenv install output, but with a slightly different path:
Select that path (not including any quotes around it), and copy it
Go to the Start menu, type "environment" and run the program Edit Environment Variables
In the System Properties popup, hit the Advanced
tab, then Environment Variables
On the list of environment variables, doubleclick Path
Click New
Paste that path from step 5 into the new entry slot. Make sure there aren't any quotes around it.
Click OK
, OK
, OK
.
Relaunch any shells you have open.
Now you should be able to just run pip
and pipenv
in Powershell without putting py -m
in front of it.
Pipenv official instructions
Install pipenv per these instructions
Install Python 3 with Chocolatey
Install pipenv per these instructions
If you're running Windows 10+, you might want to install the Windows Subsystem for Linux. This gives you a mini, integrated Linux system inside Windows. You then install and use Python from there.
Update Windows to latest if you haven't already.
Go to the Microsoft store and install Ubuntu.
Run Ubuntu to get a bash shell.
Make a new username and password. This is completely separate from your Windows username and password, but I made mine the same so that I wouldn't forget.
Upgrade the Ubuntu system. Run:
Give your newly-entered password if prompted.
Running python3 --version
should give you 3.6 or higher.
Run pip install pipenv
.
If you've installed VS Code, add the "Remote WSL" extension. This way you can run code
from within Ubuntu.
In the Ubuntu shell, you can run explorer.exe .
in any directory to open a Windows Explorer window in that directory.
Also in Windows Explorer, you can put \\wsl$
in the URL bar to see your Ubuntu drive. (If it doesn't show up, relaunch your Ubuntu shell.)
If you run into trouble with the above, try the following:
Open cmd.exe as an administrator and start bash with bash
Type Python -V' and 'Python3 -V
If one of these responds with Python 3.6.8
use that command from now on
If neither response is Python 3.6.8
but one is a higher version of Python, this means one of two things
If you have manually installed a higher version of Python, we recommend uninstalling it
If you have not, it is possible that Microsoft has updated WSL and you will need to adjust these instructions to accommodate
Otherwise, update Ubuntu:
sudo apt-get update
sudo apt-get upgrade
Repeat 2.1 above to determine if you should use Python
or Python3
when using Python. Note: inside the shell, you will always use Python as the command.
Make sure pip is installed for Python 3
pip --version
and pip3 --version
. One of these needs to respond with a version that has a version of Python 3 at the end of the line.
If you only have it for 2.7, you will need to install for 3 with:
sudo apt update && sudo apt upgrade
sudo apt install python3-pip
Check versions and commands again. You will likely need to use pip3
for the next step, but it's possible it may be just pip
. Use the one with the version associated with Python 3.6.8
Make sure pipenv is installed for Python 3 python3 -m pipenv --version
If not, install pipenv:
sudo apt update && sudo apt upgrade
(if you didn't just do this above)
pip3 install --user pipenv
Check the version again
Try pipenv shell
. If this fails, make sure that every reference in the error refers to Python 3.6. If not, review the above steps
If the error does refer to 3.6:
Confirm that python --version
refers to 2.7.something
Confirm that /usr/bin/python3 --version
refers to 3.6.8
pipenv --three --python=
which python3`` NOTE that there are backticks (`) around which python3
This should create the shell forcing it to use 3.6.8