Learn Python in Ten Minutes - Dark
Learn Python in Ten Minutes - Dark
Stavros Korokithakis
This book is for sale at http://leanpub.com/learn-python
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
1.2 Properties
Python is strongly typed (i.e. types are enforced), dynamically, implicitly typed (i.e. you don’t have
to declare variables), case sensitive (i.e. var and VAR are two different variables) and object-oriented
(i.e. everything is an object).
1.4 Syntax
Python has no mandatory statement termination characters and blocks are specified by indentation.
Indent to begin a block, dedent to end one. Statements that expect an indentation level end in a colon
(:). Comments start with the pound (#) sign and are single-line, multi-line strings are used for multi-
line comments. Values are assigned (in fact, objects are bound to names) with the _equals_ sign
(“=”), and equality testing is done using two _equals_ signs (“==”). You can increment/decrement
values using the += and -= operators respectively by the right-hand amount. This works on many
datatypes, strings included. You can also use multiple variables on one line. For example:
myvar = 3
>>> myvar += 2
>>> myvar
5
>>> myvar -= 1
>>> myvar
4
"""This is a multiline comment.
The following lines concatenate the two strings."""
>>> mystring = "Hello"
>>> mystring += " world."
>>> print mystring
Hello world.
# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar
You can access array ranges using a colon (:). Leaving the start index empty assumes the first item,
leaving the end index assumes the last item. Negative indexes count from the last item backwards
(thus -1 is the last item) like so:
1.6 Strings
Its strings can use either single or double quotation marks, and you can have quotation marks of
one kind inside a string that uses the other kind (i.e. “He said ‘hello’.” is valid). Multiline strings are
enclosed in _triple double (or single) quotes_ (“””). Python supports Unicode out of the box, using
the syntax u”This is a unicode string”. To fill a string with values, you use the % (modulo) operator
and a tuple. Each %s gets replaced with an item from the tuple, left to right, and you can also use
dictionary substitutions, like so:
Learn Python in Ten Minutes 4
strString = """This is
a multiline
string."""
rangelist = range(10)
>>> print rangelist
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in rangelist:
# Check if number is one of
# the numbers in the tuple.
if number in (3, 4, 7, 9):
# "Break" terminates a for without
# executing the "else" clause.
break
else:
# "Continue" starts the next iteration
# of the loop. It's rather useless here,
# as it's the last statement of the loop.
continue
else:
# The "else" clause is optional and is
# executed only if the loop didn't "break".
pass # Do nothing
Learn Python in Ten Minutes 5
if rangelist[1] == 2:
print "The second item (lists are 0-based) is 2"
elif rangelist[1] == 3:
print "The second item (lists are 0-based) is 3"
else:
print "Dunno"
while rangelist[1] == 1:
pass
1.8 Functions
Functions are declared with the “def” keyword. Optional arguments are set in the function
declaration after the mandatory arguments by being assigned a default value. For named arguments,
the name of the argument is assigned a value. Functions can return a tuple (and using tuple
unpacking you can effectively return multiple values). Lambda functions are ad hoc functions that
are comprised of a single statement. Parameters are passed by reference, but immutable types (tuples,
ints, strings, etc) *cannot be changed*. This is because only the memory location of the item is passed,
and binding another object to a variable discards the old one, so immutable types are replaced. For
example:
1.9 Classes
Python supports a limited form of multiple inheritance in classes. Private variables and methods
can be declared (by convention, this is not enforced by the language) by adding at least two leading
underscores and at most one trailing one (e.g. “__spam”). We can also bind arbitrary names to class
instances. An example follows:
class MyClass(object):
common = 10
def __init__(self):
self.myvariable = 3
def myfunction(self, arg1, arg2):
return self.myvariable
>>> classinstance.common
10
>>> classinstance2.common
50
1.10 Exceptions
Exceptions in Python are handled with try-except [exceptionname] blocks:
Learn Python in Ten Minutes 8
def some_function():
try:
# Division by zero raises an exception
10 / 0
except ZeroDivisionError:
print "Oops, invalid."
else:
# Exception didn't occur, we're good.
pass
finally:
# This is executed after the code block is run
# and all exceptions have been handled, even
# if a new exception is raised while handling.
print "We're done with that."
>>> some_function()
Oops, invalid.
We're done with that.
1.11 Importing
External libraries are used with the import [libname] keyword. You can also use from [libname]
import [funcname] for individual functions. Here is an example:
import random
from time import clock
import pickle
mylist = ["This", "is", 4, 13327]
# Open the file C:\\binary.dat for writing. The letter r before the
# filename string is used to prevent backslash escaping.
myfile = open(r"C:\\binary.dat", "w")
pickle.dump(mylist, myfile)
myfile.close()
myfile = open(r"C:\\text.txt")
>>> print myfile.read()
'This is a sample string'
myfile.close()
1.13 Miscellaneous
• Conditions can be chained. 1 < a < 3 checks that a is both less than 3 and greater than 1.
• You can use del to delete variables or items in arrays.
• List comprehensions provide a powerful way to create and manipulate lists. They consist of
an expression followed by a for clause followed by zero or more if or for clauses.
An example:
Learn Python in Ten Minutes 10
lst1 = [1, 2, 3]
>>> lst2 = [3, 4, 5]
>>> print [x * y for x in lst1 for y in lst2]
[3, 4, 5, 6, 8, 10, 9, 12, 15]
>>> print [x for x in lst1 if 4 > x > 1]
[2, 3]
# Check if an item has a specific property.
# "any" returns true if any item in the list is true.
>>> any([i % 3 for i in [3, 3, 4, 4, 3]])
True
# This is because 4 % 3 = 1, and 1 is true, so any()
# returns True.
Global variables are declared outside of functions and can be read without any special declarations,
but if you want to write to them you must declare them at the beginning of the function with the
“global” keyword, otherwise Python will bind that object to a new local variable (be careful of that,
it’s a small catch that can get you if you don’t know it). For example:
number = 5
def myfunc():
# This will print 5.
print number
def anotherfunc():
# This raises an exception because the variable has not
# been bound before printing. Python knows that it an
# object will be bound to it later and creates a new, local
# object instead of accessing the global one.
print number
number = 3
def yetanotherfunc():
global number
Learn Python in Ten Minutes 11
1.14 Epilogue
This tutorial is not meant to be an exhaustive list of all (or even a subset) of Python. Python has a
vast array of libraries and much much more functionality which you will have to discover through
other means, such as the excellent book Dive into Python. I hope I have made your transition in
Python easier. Please let me know if you believe there is something that could be improved or added
or if there is anything else you would like to see (classes, error handling, anything).
2 Learn Python in More Minutes
2.1 Extra fluff
After the amazing success of the tutorial, with more than one and a half million readers since it was
first written (give or take a million, anyway), I decided to publish it as a book. Since the book was
well-received, I decided to add some extra content to help the lucky few, who have more than ten
minutes, learn more Python.
I’m not very good with rambling, or even with being verbose, so the extended section will still be
as short as necessary to explain new concepts adequately.
The following sections will probably also be made available as posts on my blog¹, for your reading
pleasure.
an “$” is what you will need to type in ($ is my prompt), so ignore the $ and type in the rest of the
command.
To install virtualenv (and pip, while we’re at it), you can use setuptools:
After that, both packages will be installed globally in your system, so you might want to use sudo
if you are on Linux or OS X. We can now continue to creating an environment. I prefer to put the
environment in the directory that contains the project I’m working on, so switch to the directory
that contains your scripts and run (you shouldn’t need to use sudo):
$ virtualenv env
That will create a directory called env in your current directory and put the environment there. If
you look inside, you should see some subdirectories, containing various files. The bin directory, in
particular, should contain executables called python, pip, easy_install, etc. These executables differ
from their globally-installed namesakes in that the former will be run in the virtual environment
you’ve just created, while the latter will run system-wide.
To illustrate this point, we need to install some packages. To do this, we will use pip, because it’s
great. We already installed it earlier, so we can use it simply by doing:
Learn Python in More Minutes 14
ipython is a very nice Python shell, which you might already be familiar with, and shortuuid is a
small library for creating short unique IDs, which we’ll use to demonstrate how virtualenv works.
You might have noticed that we didn’t just run pip, we ran env/bin/pip, which means that the two
packages are now installed inside the virtualenv. Sure enough, if you run:
$ env/bin/ipython
you will see that the ipython shell opens up. If you try to import shortuuid, you will see the
following:
In [2]: shortuuid.uuid()
Out[2]: 'ogxPuKH7qvtoXSzNmVECW'
Learn Python in More Minutes 15
You will get a different ID, but the gist is the same. shortuuid has been installed and is working
properly. If you now type exit to exit ipython, run the system-wide python installation (by typing
python), and try to import shortuuid, what do you think will happen? Let’s try it out:
This is because, as I mentioned before, these packages have only been installed in the virtualenv
directory, and we didn’t run the Python interpreter that’s inside the virtualenv, we ran the system-
wide one. These packages don’t exist globally in the system, so we can be sure that whatever package
we install will be in its own, tidy little directory.
What happens if there’s already a package installed system-wide and we try to install it in the
virtualenv, or even if we don’t install it in the virtualenv? Can we still access it? The answer is
“no, we cannot”, because virtualenv, by default, restricts all access to system packages. This can be
Learn Python in More Minutes 16
changed when creating the virtualenv, but it’s beyond our scope now. As far as the virtualenv is
concerned, the system has no packages other than the ones actually installed by us in the virtualenv.
If a library is at version X globally, but we install version Y in the virtualenv, programs in that
virtualenv will only be able to see version Y.
So, we have installed our packages and are able to write our program knowing that we won’t be
messing our computer up with the various packages, but using env/bin/python all the time is a bit
of a hassle. To activate one virtualenv to work with for one terminal session, we can run:
$ source env/bin/activate
This should put the environment’s name somewhere on our prompt, and, from now on, any program
we run that’s installed in the virtualenv, will be run from it. For example, if we run python, or pip,
or ipython, we will actually be running the versions inside the environment, so they will be able to
see (and install or remove, in the case of pip) only the packages inside the environment.
You might be thinking “This is all very nice so far, but you said I could easily distribute my program,
and I see none of that!”, and you would be right. Let’s see how we can obtain a list of all the packages
that are installed in the current virtualenv. Fortunately, pip makes this trivial:
$ pip freeze
ipython==0.12.1
shortuuid==0.2
You can see that pip gave us a list of all the packages we have installed, isn’t that fantastic? Yes, of
course it is. We can get that list and stick it in a text file (I like to call it requirements.txt). We can
then send that file to a friend, along with the source code, and all they have to do to ensure that our
program will run is create a virtualenv and install the packages we’ve provided, with three simple
commands:
$ virtualenv env
$ source env/bin/activate
$ pip install -r requirements.txt
This will create the virtualenv and install all the packages we have specified in the requirements file,
at the specific versions we need, no less. You’re happy, your friend is happy, I’m happy, everyone’s
happy.
That’s not all pip can do, though. It can remove packages, install them directly from source
directories, from remote repositories, just download (but not install) them, and much more, all for
one low, low price. To get a better view of what pip (or virtualenv) can do, just look at their
respective help sections:
Learn Python in More Minutes 17
$ pip --help
$ virtualenv --help
They contain much more useful functionality, so feel free to explore around. You can get rid of
virtualenvs just by deleting the directory, absolutely nothing else in your system is touched in any
way.