Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 15

Before We Install Python:

1. Prepare to Use Command Line


To install Python and follow this lesson, you will need to use the command line.
We will walk you through all the details, so don't worry if you have never used it
before! If you would like to learn or refresh on command lines, we strongly
recommend going through this free Shell Workshop lesson, where you can set up
and learn how to use Unix Shell commands.

** Note to Windows Users: Install Git Bash


As noted in the free Shell Workshop linked above, we recommend you install Git
Bash here and use this as your terminal for this lesson. Please note that during
installation you should select the checkboxUse Git and Optional Unix tools from
the Windows Command Prompt. This will allow you to use Unix commands while
in Windows. If you'd rather use PowerShell, those commands are also provided in
this lesson. For more information on the different command shells, check out the
Shell Workshop lesson linked above.

2. Is Python Already Installed On Your Computer?


In this course, we're using the most recent major version of Python - Python 3.
Although Python 2 is still being used in many places, it is no longer being
updated. In order to keep up compatibility with future improvements to Python,
we recommend using Python 3.

Mac OS X and Linux usually come with Python 2 already installed. We DO NOT
recommend that you make any changes to this Python, since parts of the
operating system are using Python. However, it shouldn't do any harm to your
system to install Python 3 separately, too.

Windows doesn't usually come with Python included, but you can still check
whether you have it installed before going ahead. So, first, check that you’ve not
already got Python 3 installed.

Open up your Terminal or Command Line (this would be Git Bash on Windows).

In a new terminal or command prompt, type


$ python --version
and press Enter.
You might get a response that the Python version installed is something
like Python 2.7.9. In that case, it would tell you that you have Python 2 installed,
and you'll want to follow the steps in the next couple of sections to update it to
Python 3.
If instead the version number starts with a 3, then you already have Python 3
installed! Don't install Python again!

Alternatively, you might see an error message - don't worry about that for now,
just try the steps in the next couple of sections.

For Windows users using Git Bash:


If you are on Windows and choose to use Git Bash, you'll need to run a few
commands to configure it to run Python and Anaconda. We'll do this by creating
a .bashrc file.
Open the Git Bash terminal and follow the steps below.

Step 1: Enter cd to get to your home directory.


This step is important. Git Bash does not open in this directory by default, and you'll
need to be here to create your .bashrc file.

Troubleshooting error messages


In case you get an error message here, such as bash: cd: command not found, you
may need to uninstall Git and reinstall Git. However, this time during installation
select the checkbox Use Git and Optional Unix tools from the Windows Command
Prompt.
Here are some additional resources and pages:
https://hackernoon.com/install-git-on-windows-9acf2a1944f0
Then retry Step 1 above.
Step 2: Enter pwd to get the path to your home directory.
pwd gives you the path to your current directory, which should be your home
directory if you did Step 1. You'll need this for the next step.
The path to my home directory is /c/Users/Juno .
Step 3: Get the file path to your Anaconda installation.
To get the file path to your Anaconda installation, you need to take the path you got
from the previous step and append to it with the name of your Anaconda folder.

Find the name of your Anaconda folder by entering ls . (These are lower case letters
"l" and "s", because you want to "list" your files.) This should print all the file names
in your home directory. If you used the default settings during your Anaconda
installation, this folder name is likely Anaconda3 or anaconda .
In my directory, I had a folder named Anaconda3 . So the full file path to my Anaconda
installation is /c/Users/Juno/Anaconda3 .
Step 4: Add Python and Anaconda to PATH in .bashrc file.
Next, enter the following command in your terminal, replacing [YOUR_PATH] with the
path to your Anaconda installation. For example, I would replace [YOUR PATH] in the
string below with /c/Users/Juno/Anaconda3 .
echo 'export PATH="$PATH:[YOUR_PATH]:[YOUR_PATH]/Scripts"' >> .bashrc
WARNING: Before pressing enter, make sure you are following the syntax exactly
(especially the placement of each ' , " , and $ symbol), and double check that you
are replacing [YOUR PATH] correctly. You can compare your complete command with
mine in the screenshot below.
This step adds two paths to a .bashrc file, which tells Git Bash where to find the
scripts it needs to execute Python and Anaconda. Again, it's important that you are
in your home directory when you complete this step.

Step 5: Add alias for Python in .bashrc file.


Next, enter this command to tell Git Bash where to find the Python executable file.

echo 'alias python="winpty python.exe"' >> .bashrc


This is an extra step that's needed for users running Python in Git Bash. This adds a
command to your .bashrc file that says to run winpty python.exe whenever you
enter python into the terminal.

Step 6: Execute commands from .bashrc


Now that you added the necessary commands to your .bashrc file, run the following
line to execute the file.
source .bashrc
Alternatively, you can just close and open a new Git Bash window, which would
accomplish the same thing. .bashrc is executed every time Git Bash launches.

Step 7: Test Run


Run the following commands to make sure you can access conda, Python, and the
Python interpreter. If you followed these steps correctly, you should now be able to
run Python in Git Bash!
Enter exit() to leave the Python interpreter after the last step above.

Scripting With Raw Input


We can get raw input from the user with the built-in function input , which takes
in an optional string argument that you can use to specify a message to show to
the user when asking for input.
name = input("Enter your name: ")
print("Hello there, {}!".format(name.title()))
This prompts the user to enter a name and then uses the input in a greeting.
The input function takes in whatever the user types and stores it as a string. If
you want to interpret their input as something other than a string, like an integer,
as in the example below, you need to wrap the result with the new type to
convert it from a string.
num = int(input("Enter an integer"))
print("hello" * num)
We can also interpret user input as a Python expression using the built-in
function eval . This function evaluates a string as a line of Python.
result = eval(input("Enter an expression: "))
print(result)
If the user inputs 2 * 3 , this outputs 6 .

Errors And Exceptions


 Syntax errors occur when Python can’t interpret our code, since we didn’t follow
the correct syntax for Python. These are errors you’re likely to get when you
make a typo, or you’re first starting to learn Python.
 Exceptions occur when unexpected things happen during execution of a
program, even if the code is syntactically correct. There are different types of
built-in exceptions in Python, and you can see which exception is thrown in the
error message.

Specifying Exceptions
We can actually specify which error we want to handle in an except block like
this:
try:
# some code
except ValueError:
# some code
Now, it catches the ValueError exception, but not other exceptions. If we want
this handler to address more than one type of exception, we can include a
parenthesized tuple after the except with the exceptions.
try:
# some code
except (ValueError, KeyboardInterrupt):
# some code
Or, if we want to execute different blocks of code depending on the exception,
you can have multiple except blocks.
try:
# some code
except ValueError:
# some code
except KeyboardInterrupt:
# some code
Accessing Error Messages
When you handle an exception, you can still access its error message
like this:
try:
# some code
except ZeroDivisionError as e:
# some code
print("ZeroDivisionError occurred: {}".format(e))
This would print something like this:
ZeroDivisionError occurred: integer division or modulo by zero
So you can still access error messages, even if you handle them to keep
your program from crashing!

If you don't have a specific error you're handling, you can still access
the message like this:
try:
# some code
except Exception as e:
# some code
print("Exception occurred: {}".format(e))
is just the base class for all built-in exceptions. You can learn
Exception
more about Python's exceptions here.

Reading and Writing Files


To follow along with the example above, create a new file in Atom, copy
the following text into it, and save it as some_file.txt!
Hello!!

You've read the contents of this file!


Here's how we read and write files in Python.

Reading a File
f = open('my_path/my_file.txt', 'r')
file_data = f.read()
f.close()
1. First open the file using the built-in function, open. This requires a string that shows the path to the
file. The open function returns a file object, which is a Python object through which Python interacts
with the file itself. Here, we assign this object to the variable f.
2. There are optional parameters you can specify in the open function. One is the mode in which we
open the file. Here, we use r or read only. This is actually the default value for the mode argument.
3. Use the read method to access the contents from the file object. This read method takes the text
contained in a file and puts it into a string. Here, we assign the string returned from this method
into the variable file_data.
4. When finished with the file, use the close method to free up any system resources taken up by the
file.

Writing to a File
f = open('my_path/my_file.txt', 'w')
f.write("Hello there!")
f.close()
1. Open the file in writing ('w') mode. If the file does not exist, Python will create it for you. If you
open an existing file in writing mode, any content that it had contained previously will be deleted.
If you're interested in adding to an existing file, without deleting its content, you should use the
append ('a') mode instead of write.
2. Use the write method to add text to the file.
3. Close the file when finished.

Too Many Open Files


Run the following script in Python to see what happens when you open
too many files without closing them!
files = []
for i in range(10000):
files.append(open('some_file.txt', 'r'))
print(i)

With
Python provides a special syntax that auto-closes a file for you once
you're finished using it.
with open('my_path/my_file.txt', 'r') as f:
file_data = f.read()
This with keyword allows you to open a file, do operations on it, and
automatically close it after the indented code is executed, in this case,
reading from the file. Now, we don’t have to call f.close()! You can only
access the file object, f, within this indented block.

Calling the read Method with an Integer


In the code you saw earlier, the call to f.read() had no arguments passed to
it. This defaults to reading all the remainder of the file from its current
position - the whole file. If you pass the read method an integer argument, it
will read up to that number of characters, output all of them, and keep the
'window' at that position ready to read on.
Let's see this in an example that uses the following file, camelot.txt :
We're the knights of the round table
We dance whenever we're able
Here's a script that reads in the file a little at a time by passing an integer
argument to .read() .
with open("camelot.txt") as song:
print(song.read(2))
print(song.read(8))
print(song.read())
Outputs:

We
're the
knights of the round table
We dance whenever we're able
You can try out this example by creating your
own camelot.txt and example.py files with the text above.
Each time we called read on the file with an integer argument, it read up to
that number of characters, outputted them, and kept the 'window' at that
position for the next call to read . This makes moving around in the open file a
little tricky, as there aren't many landmarks to navigate by.

Reading Line by Line


\n s in blocks of text are newline characters. The newline character marks the
end of a line, and tells a program (such as a text editor) to go down to the next
line. However, looking at the stream of characters in the file, \n is just
another character.
Fortunately, Python knows that these are special characters and you can ask
it to read one line at a time. Let's try it!
Read the next line
Use the relevant part of the Python documentation to find a method that
reads the next line of a file. Put the name of the method in the box.

readline
RESET
Conveniently, Python will loop over the lines of a file using the syntax for line
in file . I can use this to create a list of lines in the file. Because each line still
has its newline character attached, I remove this using .strip() .
camelot_lines = []
with open("camelot.txt") as f:
for line in f:
camelot_lines.append(line.strip())

print(camelot_lines)
Outputs:

["We're the knights of the round table", "We dance whenever we're able"]

Importing Local Scripts


We can actually import Python code from other scripts, which is helpful
if you are working on a bigger project where you want to organize your
code into multiple files and reuse code in those files. If the Python script
you want to import is in the same directory as your current script, you
just type importfollowed by the name of the file, without the .py
extension.
import useful_functions
It's the standard convention for import statements to be written at the
top of a Python script, each one on a separate line. This import statement
creates a module object called useful_functions. Modules are just Python
files that contain definitions and statements. To access objects from an
imported module, you need to use dot notation.
import useful_functions
useful_functions.add_five([1, 2, 3, 4])
We can add an alias to an imported module to reference it with a
different name.
import useful_functions as uf
uf.add_five([1, 2, 3, 4])

Using a main block


To avoid running executable statements in a script when it's imported
as a module in another script, include these lines in an if __name__ ==
"__main__" block. Or alternatively, include them in a function called main()
and call this in the if main block.
Whenever we run a script like this, Python actually sets a special built-in
variable called __name__ for any module. When we run a script, Python
recognizes this module as the main program, and sets
the __name__ variable for this module to the string "__main__". For any
modules that are imported in this script, this built-in __name__ variable is
just set to the name of that module. Therefore, the condition if __name__ ==
"__main__"is just checking whether this module is the main program.

Techniques for Importing Modules


There are other variants of import statements that are useful in different situations.
1. To import an individual function or class from a module:
2. from module_name import object_name
3. To import multiple individual objects from a module:
4. from module_name import first_object, second_object
5. To rename a module:
6. import module_name as new_name
7. To import an object from a module and rename it:
8. from module_name import object_name as new_name
9. To import every object individually from a module (DO NOT DO THIS):
10. from module_name import *
11. If you really want to use all of the objects from a module, use the standard import module_name statement
instead and access each of the objects with the dot notation.
12. import module_name

Modules, Packages, and Names


In order to manage the code better, modules in the Python Standard Library are split down into sub-
modules that are contained within a package. A package is simply a module that contains sub-modules. A
sub-module is specified with the usual dot notation.
Modules that are submodules are specified by the package name and then the submodule name separated
by a dot. You can import the submodule like this.

import package_name.submodule_name

Third-Party Libraries
There are tens of thousands of third-party libraries written by independent
developers! You can install them using pip, a package manager that is
included with Python 3. pip is the standard package manager for Python, but it
isn't the only one. One popular alternative is Anaconda which is designed
specifically for data science.

To install a package using pip, just enter "pip install" followed by the name of
the package in your command line like this: pip install package_name . This
downloads and installs the package so that it's available to import in your
programs. Once installed, you can import third-party packages using the same
syntax used to import from the standard library.
Using a requirements.txt File
Larger Python programs might depend on dozens of third party packages. To
make it easier to share these programs, programmers often list a project's
dependencies in a file called requirements.txt. This is an example of a
requirements.txt file.

beautifulsoup4==4.5.1
bs4==0.0.1
pytz==2016.7
requests==2.11.1
Each line of the file includes the name of a package and its version number.
The version number is optional, but it usually should be included. Libraries can
change subtly, or dramatically, between versions, so it's important to use the
same library versions that the program's author used when they wrote the
program.

You can use pip to install all of a project's dependencies at once by typing pip
install -r requirements.txt in your command line.

Useful Third-Party Packages


Being able to install and import third party libraries is useful, but to be an
effective programmer you also need to know what libraries are available for
you to use. People typically learn about useful new libraries from online
recommendations or from colleagues. If you're a new Python programmer you
may not have many colleagues, so to get you started here's a list of packages
that are popular with engineers at Udacity.

 IPython - A better interactive Python interpreter


 requests - Provides easy to use methods to make web requests. Useful for
accessing web APIs.
 Flask - a lightweight framework for making web applications and APIs.
 Django - A more featureful framework for making web applications. Django is
particularly good for designing complex, content heavy, web applications.
 Beautiful Soup - Used to parse HTML and extract information from it. Great
for web scraping.
 pytest - extends Python's builtin assertions and unittest module.
 PyYAML - For reading and writing YAML files.
 NumPy - The fundamental package for scientific computing with Python. It
contains among other things a powerful N-dimensional array object and useful
linear algebra capabilities.
 pandas - A library containing high-performance, data structures and data
analysis tools. In particular, pandas provides dataframes!
 matplotlib - a 2D plotting library which produces publication quality figures in
a variety of hardcopy formats and interactive environments.
 ggplot - Another 2D plotting library, based on R's ggplot2 library.
 Pillow - The Python Imaging Library adds image processing capabilities to
your Python interpreter.
 pyglet - A cross-platform application framework intended for game
development.
 Pygame - A set of Python modules designed for writing games.
 pytz - World Timezone Definitions for Python

Experimenting With An Interpreter


Start your Python interactive interpreter by entering the
command python in your terminal. You can type here to interact with
Python directly. This is an awesome place to experiment and try bits of
Python code at a time. Just enter Python code, and the output will
appear on the next line.
>>> type(5.23)
<class 'float'>
In the interpreter, the value of the last line in a prompt will be outputted
automatically. If you had multiple lines where you’d want to output
values, you’d still have to use print.

If you start to define a function you will see a change in the prompt, to
signify that this is a continuation line. You'll have to include your own
indentation as you define the function.
>>> def cylinder_volume(height, radius):
... pi = 3.14159
... return height * pi * radius ** 2
A drawback of the interpreter is that it’s tricky to edit code. If you made
a mistake when typing this function, or forgot to indent the body of the
function, you can't use the mouse to click your cursor where you want it.
You have to navigate with arrow keys to move the cursor forwards and
backwards through the line itself for editing. It would be helpful for you
to learn useful shortcuts for actions like moving to the beginning or end
of the line.

Notice I can reference any objects I defined earlier in the interpreter!


>>> cylinder_volume(10, 3)
282.7431
One useful trick is using the up and down arrow to cycle through your
recent commands at the interactive prompt. This can be useful to re-run
or adapt code you've already tried.

To quit the Python interactive interpreter, use the command exit() or


hit ctrl-D on mac or linux, and ctrl-Z then Enter for windows.

IPython
There is actually an awesome alternative to the default Python
interactive interpreter, IPython, which comes with many additional
features.

 tab completion
 ? for details about an object
 ! to execute system shell commands
 syntax highlighting!
and a lot more you can find here!

Hierarchy of Online Resources


While there are many online resources about programming, not all of the
them are created equal. This list of resources is in approximate order of
reliability.

1. The Python Tutorial - This section of the official documentation surveys


Python's syntax and standard library. It uses examples, and is written
using less technical language than the main documentation. Make sure
you're reading the Python 3 version of the docs!
2. The Python Language and Library References - The Language Reference
and Library Reference are more technical than the tutorial, but they are
the definitive sources of truth. As you become increasingly acquainted
with Python you should use these resources more and more.
3. Third-Party Library Documentation - Third-party libraries publish their
documentation on their own websites, and often times
at https://readthedocs.org/. You can judge the quality of a third-party
library by the quality of its documentation. If the developers haven't
found time to write good docs, they probably haven't found the time to
polish their library either.
4. The websites and blogs of prominent experts - The previous resources are
primary sources, meaning that they are documentation from the same
people who wrote the code being documented. Primary sources are the
most reliable. Secondary sources are also extremely valuable. The
difficulty with secondary sources is determining the credibility of the
source. The websites of authors like Doug Hellmann and developers
like Eli Bendersky are excellent. The blog of an unknown author might
be excellent, or it might be rubbish.
5. StackOverflow - This question and answer site has a good amount of
traffic, so it's likely that someone has asked (and someone has
answered) a related question before! However, answers are provided by
volunteers and vary in quality. Always understand solutions before
putting them into your program. One line answers without any
explanation are dubious. This is a good place to find out more about your
question or discover alternative search terms.
6. Bug Trackers - Sometimes you'll encounter a problem so rare, or so new,
that no one has addressed it on StackOverflow. You might find a
reference to your error in a bug report on GitHub for instance. These bug
reports can be helpful, but you'll probably have to do some original
engineering work to solve the problem.
7. Random Web Forums - Sometimes your search yields references to forums
that haven't been active since 2004, or some similarly ancient time. If
these are the only resources that address your problem, you should
rethink how you're approaching your solution.

You might also like