python2
python2
Overview
Dictionaries
Functions
Logical expressions
Flow of control
Comprehensions
For loops
More on functions
Assignment and containers
Strings
Dictionaries: A Mapping type
Dictionaries store a mapping between a set of
keys and a set of values
• Keys can be any immutable type.
• Values can be any type
• A single dictionary can store values of
different types
You can define, modify, view, lookup or delete
the key-value pairs in the dictionary
Python’s dictionaries are also known as hash
tables and associative arrays
Creating & accessing dictionaries
def get_final_answer(filename):
“““Documentation String”””
line1
line2 Colon.
return total_counter
>>>
break and continue
You can use the keyword break inside a
loop to leave the while loop entirely.
assert(number_of_players < 5)
List
Comprehensions
Python’s higher-order functions
Python supports higher-order functions that
operate on lists similar to Scheme’s
>>> def square(x):
return x*x
>>> def even(x):
return 0 == x % 2
>>> map(square, range(10,20))
[100, 121, 144, 169, 196, 225, 256, 289, 324, 361]
>>> filter(even, range(10,20))
[10, 12, 14, 16, 18]
>>> map(square, filter(even, range(10,20)))
[100, 144, 196, 256, 324]
But many Python programmers prefer to use list
comprehensions, instead
List Comprehensions
A list comprehension is a programming
language construct for creating a list based on
existing lists
• Haskell, Erlang, Scala and Python have them
Why “comprehension”? The term is borrowed
from math’s set comprehension notation for
defining sets in terms of other sets
A powerful and popular feature in Python
• Generate a new list by applying a function to every
member of an original list
Python’s notation:
[ expression for name in list ]
List Comprehensions
The syntax of a list comprehension is
somewhat tricky
>>> li = [3, 6, 2, 7, 1, 9]
>>> [elem*2 for elem in li if elem > 4]
[12, 14, 18]
>>> x, y = 2, 3
>>> “hello”.upper()
‘HELLO’