Syntax

Python code has a simple syntax and is generally easy to read and reason about, this session is intended to make sure you know how to read any code you come across.

But first, the bad news

Three things people (I) hate(d) about Python syntax:

  1. No pre-declaration (can make scope-related bugs hard to find).
  2. Many things are statements (don't return a value) in Python that aren't in other languages. (E.g. print, +=)
  3. Significant whitespace. Statements in the same block must be indented equally.

Feel free to hate these too, but be warned it's well-trod ground.

Example 1

continue_meditating = True
while continue_meditating:
    if True:
        continue
    elif False:
        raise SystemExit("Gah! Paradox!")
    else:
        continue_meditating = False

share_enlightenment()

You just saw:

Data Literals

number_list = [1, 2, 5] # "Three sir!"
number_list.append(3)

# Dictionaries map from keys to values
music = {"Aidan": "Beats", "Justin": "Grunge"}
music['Stephen'] = 'Sarcasm'

birth_year = ('Stephen', 1984) # Tuples are immutable
birth_year[1] = 1341 # Raises an exception

http://docs.python.org/library/stdtypes.html

Functions

def shout(message="Hi"):
    print "%s!" % message

shout() # Prints "Hi!"
shout("I love python")
shout(message="And keyword arguments")

Functions are defined with the def keyword, and arguments can specify default values. Additionally, arguments that specify defaults can be named at the call site. This is referred to as a keyword argument.

Classes

class LoudTalker(object):
    def say(self, message):
        shout(message)

shaun = LoudTalker()
shaun.say("Herpa derpa")

Classes are declared using the class keyword, and methods are declared as functions inside the class body (indicated by indentation). Instances are created by calling the class object, there is no new keyword.

Iteration

beverage = None
for fridge in office:
    if 'Coke' in fridge:
        beverage = fridge.remove('Coke')
        break
if not beverage:
    shout("Where's the @#$%ing Coke?")

All containers can be iterated over with for ... in .... The in keyword can also be used for existence checks with if.

Iteration - Dictionaries

If all containers can be iterated over, what happens when you iterate over a dictionary?

for key in mapping:
  print "%s=%s" % (key, mapping[key])

for value in mapping.values():
  print "???=%s" % value

for (k, v) in mapping.items():
  print "%s=%s" % (k, v)

Splats

Functions can declare that they accept a variable number of arguments or arbitrary keyword arguments or both. This is done by prefixing the final argument name with * or ** or having two argument names (with * and ** , respectively):

def takes_all(required, *args, **kwargs):
    # tuple of all positional (non-keyword) arguments
    print args

    # dictionary of all keyword arguments
    print kwargs

The End

There are some very important keywords that got left out here, but at this point you know enough to write some code and start filling in the gaps.

Questions?