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.
Three things people (I) hate(d) about Python syntax:
Feel free to hate these too, but be warned it's well-trod ground.
continue_meditating = True
while continue_meditating:
if True:
continue
elif False:
raise SystemExit("Gah! Paradox!")
else:
continue_meditating = False
share_enlightenment()
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
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.
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.
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.
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)
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
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?