On Github catalyst-training / python-intro
Presented by Tom Eastman
The Python language
The Python environment
The Python ecosystem
How to write some Python
The core datatypes and how to use them
A crash course in language features (spotters guide)
This setup script will:
Use apt to install Python 2 and 3
Use pip to install IPython Notebook
Clone my python-for-perl-developers repository.
$ wget http://tap.wgtn.cat-it.co.nz/python-for-perl-developers/setup.sh $ bash ./setup.sh
Running...
ipython notebook
...will get you a workspace to start writing Python.
You can create workbooks for both Python 2 and Python 3
- Make sure everyone can get the IPython Notebook fired up.If you're writing a library, you can make it 2.7 and >3.3 compatible in the same codebase.
At the module level, you can make Python 2 act a lot more like Python 3:
from __future__ import ( division, ## Make 3 / 2 == 1.5 absolute_import, ## New path syntax for importing modules print_function, ## Replace keyword with the print() function unicode_literals ## All "strings" are not implicitly u"strings" )
If you're using Python 2.7, you should do this in all your modules.
Python 2
$ python >>> print "Hello World!" Hello World! >>>
Python 3
$ python3 >>> print("Hello World!") Hello World! >>>
Python is self documenting:
>>> help() Welcome to Python 3.4! This is the interactive help utility. [...] To get a list of available modules, keywords, symbols, or topics, type "modules", "keywords", "symbols", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose name or summary contain a given string such as "spam", type "modules spam". help>
You can get help on any function, class, or module:
>>> help(str) Help on class str in module builtins: class str(object) | str(object='') -> str | str(bytes_or_buffer[, encoding[, errors]]) -> str | | Create a new string object from the given object. If encoding or | errors is specified, then the object must expose a data buffer [... cont'd ...]
Sometimes you don't need the full help(), just a hint:
>>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
[Use help() to look up the documentation for dir() and see what it's doing]
Let's talk about the literal types (the ones that are built into the syntax of the language)
## These mean the same thing >>> 1 1 >>> int(1) 1 >>> int("1") 1- There used to be a difference between classes and types. It's not relevant anymore.
>>> True True >>> False False >>> True or False True >>> True and "Bob" True >>> bool("") False >>> bool("0") False
Integers are integers. You do integery things with them.
>>> 1 1 >>> 1000000000000000000000000 1000000000000000000000000 >>> 1000000000000000000000000 - 5 999999999999999999999995 >>> int("-17") -17- Integers won't overflow in Python
Floats are double-precision floating point numbers.
>>> 3.0 / 2.0 1.5
Careful: Division works differently in Python 2 and 3
In Python 3:
>>> 5 / 4 1.25
In Python 2:
>>> 5 / 4 1 >>> 5 / 4.0 1.25
'hi!'
"hi!"
'''hi!'''
"""hi!"""
'hi!'
... are all the same string
Lists are your general purpose ordered container type in Python.
>>> my_list = ["one", "two", "three"] >>> my_list.append(4.0) >>> print(my_list) ['one', 'two', 'three', 4.0]
Dictionaries are your key value store/hash table.
>>> tel = {'jack': 4098, 'sape': 4139} >>> tel['guido'] = 4127 >>> tel {'sape': 4139, 'guido': 4127, 'jack': 4098'
Imagine a dictionary that is 'keys only'.
In Python, blocks of code are delimited by indentation of whitespace.
>>> if 1 >= 0: ... print("Well, obviously") ... else: ... print("Wait, what?") ... Well, obviously
Long lines can be broken up with a \
>>> 1 + 2 + 3 + 4 + 5 + \ ... 6 + 7 + 8 + 9 + 0 45
Long lines are almost always broken up using parentheses, brackets, or braces.
>>> (1 + 2 + 3 + 4 + 5 + ... 6 + 7 + 8 + 9 + 0) 45
The indentation of a continued line is ignored, except stylistically:
foo = long_function_name(var_one, var_two, var_three, var_four)
#!/usr/bin/env python3 def main(): print("Hello World!") if __name__ == "__main__": main()
System libraries are in...
/usr/lib/pythonX.Y/
3rd party libraries in
/usr/lib/pythonX.Y/site-packages/
Or maybe in
/usr/local/lib/pythonX.Y/site-packages/
If everything you need is in the standard library, or in Ubuntu/Debian package distributions, yay for you!
If not, your options are to install libraries system-wide in /usr/local or site-packages, or...
... use a virtualenv.
Setting up a virtualenv
$ virtualenv my_venv New python executable in my_venv/bin/python Installing setuptools, pip...done.
$ tree -d my_venv/ my_venv/ ├── bin ├── include │ └── python2.7 -> /usr/include/python2.7 ├── lib │ └── python2.7 │ ├── distutils │ └── site-packages │ ├── pip │ ├── pip-1.5.4.dist-info │ ├── setuptools │ └── setuptools-2.2.dist-info └── local ├── bin -> /home/tom/my_venv/bin ├── include -> /home/tom/my_venv/include └── lib -> /home/tom/my_venv/lib
Activate that virtualenv
$ source my_venv/bin/activate (my_venv) $
(Note the altered command prompt)
(my_venv) $ which python /home/tom/my_venv/bin/python (my_venv) $ which pip /home/tom/my_venv/bin/pip
Installing packages into your activated virtualenv
(my_venv) $ pip install --use-wheel django Downloading/unpacking django Downloading Django-1.7.7-py2.py3-none-any.whl (7.4MB): 7.4MB downloaded Installing collected packages: django Successfully installed django Cleaning up...
Now you have your own python environment in which you can use Django.
If you don't want to (or can't) source the environment file you can run the python binary directly:
$ /home/tom/my_venv/bin/python <FILE>
As of Python 3.3, virtualenvs (renamed 'venv') are a feature of the standard library.
$ python3.4 -m venv my_venv --without-pip
On Ubuntu Trusty, you have to include --without-pip and install pip yourself with get-pip.py
Other useful facts about virtualenvs:
So what are you supposed to use?
This page has all you need:
Presented by Name
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at scelerisque eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam placerat posuere nibh vel dapibus.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris at scelerisque eros. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam placerat posuere nibh vel dapibus.
Some text
function linkify( selector ) { if( supports3DTransforms ) { var nodes = document.querySelectorAll( selector ); for( var i = 0, len = nodes.length; i < len; i++ ) { var node = nodes[i]; if( !node.className ) { node.className += ' roll'; } } } }
open source technologists