Slide 1

Slide 1 text

print('Introduction to Python') David Beitey PyNQ 2014 http://speakerdeck.com/davidjb

Slide 2

Slide 2 text

About me: vars(self) class David: name = 'David Beitey' home = 'Townsville, North Queensland' position = 'Online Services Manager' organisation = 'eResearch Centre, James Cook University' handle = '@davidjb' web = 'http://davidjb.com' me = David() print(me.name + ' lives in ' + me.home) print('The name is %i characters long.' % len(me.name))

Slide 3

Slide 3 text

What is Python? ● Powerful, object-oriented programming language ● Simple, readable syntax that's easy to learn ● Portable - different environments and platforms ○ Preinstalled on Mac/Linux ● Dynamic typing (duck typed), strongly typed language ● Flexible across use-cases (scripts, applications, big data) ● Extensive standard library ● Community developed and community focus ● Free and open source software

Slide 4

Slide 4 text

What can it do? ● Scripting (applications, one-off, embedded) ● Data processing and manipulation (science, maths, physics, web requests, any raw data) ● Web applications, sites, CMS portals, software ● Games, 3D rendering and pipelining ● Physical interactivity (sensors, hardware, data) ● … and heaps more …

Slide 5

Slide 5 text

A brief history of Python ● Conceived 1980s; started in 1989 by Guido van Rossum ● Guido continues in his role as ‘Benevolent Dictator for Life’ as Python’s principal author ● Python 2.0 released in 2000, ○ Python 2.7 is the current release, last 2.x ● Python 3.0 released in 2008 ○ Python 3.4 is the current release ○ Backwards incompatible with 2.x series ○ Many/most features have been backported ● Python 2 and 3 are very close, but not fully compatible.

Slide 6

Slide 6 text

Quick comparison (Warning: here be opinions!) ● C - Faster than Python as lower-level, but Python is easier to utilise because of simpler syntax, common structures, and libraries. ● C++ - Less clear in terms of language constructs, data types, and lower- level issues such as memory allocation. ● Java - Likely more verbose and “enterprise”-like (abstraction of functionality), leading to more “rigid” code. ● JavaScript - Python has more formal data structures (classes), a larger set of functionality, though CoffeeScript/Node.js blur this distinction. ● Ruby - Very similar to Python, referred to as bickering “twins”. Ruby feels less clear in terms of syntax and language constructs, but functionally very similar. Metaprogramming may be easier in Ruby. ● VisualBasic - Similar in nature, though Python is faster, portable, community-driven and open-source, has a larger standard library. ● … ad nauseum … ● Python: clear syntax, encourages explicit coding, enforces formatted code, encourages ‘Pythonic’ simplicity

Slide 7

Slide 7 text

Getting started - which install? ● Python 2 vs Python 3. Choose Python 3 unless explicitly required by tools or libraries that you need. ● Installing Python (actually CPython): ○ Installed by default with most/all Linux distributions (2.6/2.7) ○ Installed by default with Mac OS X (2.7) ○ Executable downloadable for Windows ○ Embedded in various applications ● Various implementations exist: ○ IronPython (.net), Jython (Java), PyPy (Python in Python), embedded devices etc. ● See http://python.org, http://www.pythonanywhere.com/

Slide 8

Slide 8 text

Getting started - tools ● Depends on your usage, requirements and skill level ● Command line: ○ Python interpreter ○ ipython (interactive notebook, console) ○ Your favourite text editor (Vim, Emacs) ● GUI: ○ IDLE (basic GUI) ○ PyCharm (from JetBrains, IntelliJ creators) ○ Wingware Python IDE

Slide 9

Slide 9 text

Basics of Python >>> import antigravity [Loads XKCD comic] >>> print(antigravity) Source code is easy to access, if you're ever curious about how Python works under the hood. Just open the .py file (not the . pyc file) and see!

Slide 10

Slide 10 text

Basics of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

Slide 11

Slide 11 text

Basic concepts - Structure ● Code will run top-to-bottom, like other languages ● Blocks are whitespace delimited, rather than braces or ending keywords. ● Types of blocks include: ○ if (conditional) ○ for, while (iteration) ○ try, except (exception handling) ○ class (class definitions) ○ def (functions or method definitions) ○ with (context code blocks) # This is a comment def purchase(item, count=1): print('You just bought %i of the item %s' % (count, item)) for_sale = 'albatross' if for_sale != 'choc-ices': purchase(for_sale, 2)

Slide 12

Slide 12 text

Basic concepts - Built-in types ● None (Null) None ● bool (Boolean) True, False ● int/float/complex (Numeric) 1, 1.5, (1+1j) ● str/unicode (Text) 'Hello' ● list/tuple/range (Sequences) [1,2,3], (1,2) ● bytes (Binary Sequences) ● set/frozenset (Sets) set([1,2,3]) ● dict (Mapping) {'key': 'value'} ● Any object can be tested for 'truth' ○ None, 0, empty sequences, maps result are False ● Some changes between Python 2.x and 3.x: ○ str implementation now unicode ○ int implementation now long ○ range implementation replaced by xrange

Slide 13

Slide 13 text

Basic concepts - Methods/Operators ● and, or, not (Boolean) ● <, <=, >, >=, ==, !=, is, is not (Comparisons) ● +, -, *, /, //, %, -x, +x, ** (Numerical) ● abs, int, float, complex, divmod, pow (Numerical) ● in, not in, +, *, s[i], s[i:j], s[i:j:k] (Sequences) ● len, min, max s.index, s.count (Sequences) ● |, ^, &, <<, >>, ~ (Bitwise) ● Large number of string methods: s.upper(), s.lower(), s.endswith (...), s.startswith(...), s.strip(), s.replace(...) ● Print to standard output: print('Hello world') ● Read input: input("What's your name?") ● Comprehensions: [key for key in data]

Slide 14

Slide 14 text

Basic concepts - Modules/importing ● Modules are complementary groups of code ● May consist of functions, classes, variables, any Python ● Utilise other modules or libraries to your current file with: ○ import os (imports the whole module/package) or ○ from os import listdir (imports specific parts) ● Once done, you can now access and run code using its name: import os from os import mkdir print(os.listdir('/etc')[:10]) # First 10 entries mkdir('/tmp/example') # Creates a directory ● Python has namespaces for nested grouping (such as davidjb. work.myproject) ● Go exploring the standard library for functionality! https://docs.python.org/3.4/library/index.html#library-index

Slide 15

Slide 15 text

Basic concepts - Classes, Methods, Functions ● Classes define blueprints for objects; can have methods ● Classes can have attributes and be dynamically added ● Functions are callable blocks of code and take arguments ○ Can be defined on classes, in modules, inside other functions ● Duck typing: if it walks like a duck and quacks like a duck, it is a duck. ● lambda: simple, inline functions class Spotter: def __init__(self, type_, initial_count=0): self.type = type_ self.count = initial_count def spot(self): self.count += 1 def how_many_have_you_spotted(self): print('Nearly %i, call it none.' % self.count) camel_spotter = Spotter(type='camel') camel_spotter.spot() camel_spotter.how_many_have_you_spotted() # Nearly 1, call it none. camel_spotter.spot() camel_spotter.how_many_have_you_spotted() # Nearly 2, call it none. camel_spotter.count # Value of 2 camel_spotter.type # Value of 'camel'

Slide 16

Slide 16 text

Basic concepts - Overview ● An example stand-alone Python script: send_credit.py ○ Processes command line arguments ○ Communicates with serial modem libraries ○ Writes output to log files ● Nature of Python encourages decent programming practices (“Pythonic”) ○ ...although this can be very, very wrong. ○ Python programs can be written like C spaghetti code. ○ A goto module exists for Python. Do not use it. ● Nature of Python's dynamic types is that it is possible to override or replace built-in elements ○ Powerful, but a potential tripping hazard ● For more info, see http://docs.python.org/.

Slide 17

Slide 17 text

What next? ● Dive in. Learn by doing. Think about topics you want to work with and start there. ● https://www.python.org/about/gettingstarted/ Beginner’s Guide (Installing, Learning) ○ Resources: https://wiki.python.org/moin/BeginnersGuide ○ Tutorial: https://docs.python.org/3.4/tutorial/ (version 2 as well) ● http://docs.python.org/ - Official Python documentation (language, standard library) ● http://docs.python-guide.org/ - Hitchhiker’s Guide to Python (covers general high-level tasks and approaches for Python) ● http://en.wikibooks.org/wiki/Python_Programming ● http://learnpythonthehardway.org/book/ - Useful methodology but Python 2.x only ● StackOverflow, web searches, IRC chat ● Ask here or email the PyNQ mailing list

Slide 18

Slide 18 text

Useful things to learn or research ● Version control: Git, Mercurial, SVN ● Source code platforms: GitHub BitBucket, SourceForge ● Standard Library - Become familiar with what's out there. ● PyPI - Python Package Index for public listing of installable modules. ○ Try anything with easy with easy_install

Slide 19

Slide 19 text

Real-world projects ● JCU Research Portfolio: http://jcu.me (Pyramid Web Framework) ● eSpaces for Research: https://espaces.edu.au (Plone) ● TileStache mapping service: https://tropicaldatahub.org/, (TileStache) ● 3G Modem Communication: python-gsmmodem, https: //github.com/davidjb/telstra.mobile ● Mist: HTML keyword cloud generator (SMS, Tweet ingestion) https://github.com/davidjb/mist ● Static blogs: http://pynq.org, http://davidjb.com ● Others can be found at http://python.org/about/apps/

Slide 20

Slide 20 text

PyNQ - what next? ● Expansion of interest: advertising, channels, communication. PyNQ website. ● Talks: different speakers, different audiences ● Workshops: bring in laptops and do coding on tasks, coding in a social environment. ○ Suggestions for useful topics? ○ Gauge interest from what people use or need to use. ● Development activities: ○ Code wars - coding challenges in teams on the big screen ○ Sprinting - open-source code development on a project, library, or task ● Location: JCU is available. May revisit this at some point.