Second half of the course!

Python

Syntax

# Thanks, Todd Waits
# oh look, comments start with pound sign, not //
import random

# no need to declare variables.
r = random.randint(0, 100)

while r < 85: # no parentheses.
    if r > 70:
        print(r, ":  so close!", sep="")    # what's that sep=""?
    elif r > 45:                            # elif??
        print(r, end="")
        print(":  Getting there...")
    else:
        print("{}:  Still so far away!".format(r))

    r = random.randint(0, 100)

print("WE GOT OUT!")

# a function with no code.
def emptyFunction():
	pass # 'pass' is like empty braces {}

""" Multi-line comments are delimited by triple-quotes.
This is kind of weird, because we'll see that we can also use
triple-quotes for strings... """

Control structures

Variables and types

See the official docs here

Lists

Sets

Dicts

Tuples

# from X import Y means "import the X module, and grab the Y name out of it"
# so I don't have to write collections.namedtuple, I can just write namedtuple
from collections import namedtuple

# like making a "Point" class with 2 fields, but way less typing, and it acts like a tuple
Point = namedtuple('Point', ['x', 'y'])

p = Point(10, 20) # uses class-like construction syntax
x, y = p          # can unpack it like a real tuple
print(p[0], p.x)  # can access fields by name or by index - same thing here

Functions

counter = 0

def printCounter():
	# can *read* counter just fine
	print("counter is", counter)

def incCounter():
	# ??!??!??!
	# this doesn't make a global variable. this says
	# "within this function, treat counter as a global."
	global counter
	# now when we access it, it won't make a local.
	counter += 1

Next time…