Lesson6 Python
Lesson6 Python
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).
Alternatively, you might see an error message - don't worry about that for now,
just try the steps in the next couple of sections.
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.
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 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.
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.
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.
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"]
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.
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.
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!