Python Features and Surprises
Today we walked through some examples of "Python surprises" -- things that work differently than one might expect. Here are some fun examples:
#!/usr/bin/python numbers = [1, 2, 3, 4, 5] print numbers try: for index in range(0, 10): print numbers[index] except IndexError: print "We counted forward up to index " + str(index) + ", at which time " \ + "we got an IndexError." print "" print "" print numbers try: for index in range(-1, -10, -1): print numbers[index] except IndexError: print "We counted backward up to index " + str(index) + ", at which time " \ + "we got an IndexError."
But, let's not read too much into the anonymous part. Although they technically don't have names -- we can assign them to variables, which serve as names. Check out the example below:
square = lambda x: x**2 print square (4)
def power(n): return lambda x: x**n power3 = power(3) print power3(2)
def printRecord(name, role="Student", status="Active"): print name + ": " + role + "(" + status + ")" printRecord("Jane Blogs") printRecord("John Blogs", status="Graduated") printRecord("Asa Frank", role="TA") printRecord("Gregory Kesden", role="Instructor")
numbers = [ number for number in range(10) ] print numbers evens = [ number for number in range(10) if ((number%2) == 0)] print evens adjectives = ["Fast", "Slow", "Big", "Small" ] nouns = [ "Car", "Boat", "Truck", "Plane" ] combinations = [ (adjective, noun) for adjective in adjectives \ for noun in nouns ] print combinations boatCombinations = [ (adjective, noun) for adjective in adjectives \ for noun in nouns \ if (noun == "Boat") ] print boatCombinations