In [ ]:
{1,2,3,"bingo"}
In [ ]:
type({1,2,3,"bingo"})
In [ ]:
type({})
In [ ]:
type(set())
In [ ]:
set("spamIam")
Sets have unique elements. They can be compared, differenced, unionized, etc.
In [ ]:
a = set("sp"); b = set("am"); print(a) ; print(b)
In [ ]:
c = set(["a","m"])
In [ ]:
c == b
In [ ]:
"p" in a
In [ ]:
"ps" in a
In [ ]:
q = set("spamIam")
a.issubset(q)
In [ ]:
a | b
In [ ]:
q - (a | b)
In [ ]:
q & (a | b)
Like lists, we can use as (unordered) buckets
.pop() gives us a random element
In [ ]:
# this is pretty volitile...wont be the same
# order on all machines
for i in q & (a | b):
print(i)
In [ ]:
q.remove("a")
In [ ]:
q.pop()
In [ ]:
print(q.pop())
print(q.pop())
In [ ]:
print(q.pop())
In [ ]:
# q.pop()
In [ ]:
d = {"favorite cat": None, "favorite spam": "all"}
these are key: value, key: value, ...
In [ ]:
print(d["favorite cat"])
d[0] ## this is not a list and you dont have a keyword = 0
In [ ]:
e = {"favorite cat": None, "favorite spam": "all", \
1: 'loneliest number'}
e[1] == 'loneliest number'
dictionaries are UNORDERED*.
You cannot assume that one key comes before or after another
* you can use a special type of ordered dict if you really need it:
http://docs.python.org/whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections
In [ ]:
# number 1...you've seen this
d = {"favorite cat": None, "favorite spam": "all"}
In [ ]:
# number 2
d = dict(one = 1, two=2,cat = 'dog') ; print(d)
In [ ]:
# number 3 ... just start filling in items/keys
d = {} # empty dictionary
d['cat'] = 'dog'
d['one'] = 1
d['two'] = 2
d
In [ ]:
# number 4... start with a list of tuples
mylist = [("cat","dog"), ("one",1),("two",2)]
print(dict(mylist))
In [ ]:
dict(mylist) == d
In [ ]:
d = {"favorite cat": None, "favorite spam": "all"}
In [ ]:
d = {'favorites': {'cat': None, 'spam': 'all'}, \
'least favorite': {'cat': 'all', 'spam': None}}
print(d['least favorite']['cat'])
remember: the backslash () allows you to across break lines. Not technically needed when defining a dictionary or list
In [ ]:
phone_numbers = {'family': [('mom','642-2322'),('dad','534-2311')],\
'friends': [('Sylvia','652-2212')]}
In [ ]:
for group_type in ['friends','family']:
print("Group " + group_type + ":")
for info in phone_numbers[group_type]:
print(" ",info[0], info[1])
In [ ]:
# this will return a list, but you dont know in what order!
phone_numbers.keys()
In [ ]:
phone_numbers.values()
.keys() and .values(): are called methods on dictionaries
In [ ]:
for group_type in phone_numbers.keys():
print("Group " + group_type + ":")
for info in phone_numbers[group_type]:
print(" ",info[0], info[1])
we cannot ensure ordering here of the groups
In [ ]:
groups = phone_numbers.keys()
groups.sort()
for group_type in groups:
print("Group " + group_type + ":")
for info in phone_numbers[group_type]:
print(" ",info[0], info[1])
.iteritems() is a handy method,
returning key,value pairs with each iteration
In [ ]:
for group_type, vals in phone_numbers.iteritems():
print("Group " + group_type + ":")
for info in vals:
print(" ",info[0], info[1])
Some examples of getting values:
In [ ]:
phone_numbers['co-workers']
In [ ]:
phone_numbers.has_key('co-workers')
In [ ]:
print phone_numbers.get('co-workers')
In [ ]:
phone_numbers.get('friends') == phone_numbers['friends']
In [ ]:
print phone_numbers.get('co-workers',"all alone")
In [ ]:
# add to the friends list
phone_numbers['friends'].append(("Jeremy","232-1121"))
print(phone_numbers)
In [ ]:
## Sylvia's number changed
phone_numbers['friends'][0][1] = "532-1521"
In [ ]:
phone_numbers['friends'][0] = ("Sylvia","232-1521");
print(phone_numbers['friends'])
In [ ]:
## I lost all my friends preparing for this Python class
phone_numbers['friends'] = [] # sets this to an empty list
In [ ]:
## remove the friends key altogether
print(phone_numbers.pop('friends'))
In [ ]:
print(phone_numbers)
In [ ]:
del phone_numbers['family']
In [ ]:
print(phone_numbers)
.update() method is very handy, like .append() for lists
In [ ]:
phone_numbers.update({"friends": [("Sylvia's friend, Dave", "532-1521")]})
print(phone_numbers)
In [ ]:
x = 1
print(x)
IPython Notebook automatically converts tabs into spaces, but some programs do not. Be careful not to mix these up! Be consistent in your programming.
If you're working within the Python interpreter (not the IPython Notebook), you'll see this:
>>> x = 1
>>> if x > 0:
... print "yo"
... else:
... print "dude"
... print "ok"
...
yo
ok
In [ ]:
# You can mix indentations between different blocks ...
# but this is ugly and people will judge you
x = 1
if x > 0:
print("yo")
else:
print("dude")
In [ ]:
# You can put everything on one line/statement
print("yo" if x > 0 else "dude")
In [ ]:
# Multiple cases
x = 1
if x < -10:
print("yo")
elif x > 10: # 'elif' is short for 'else if'
print("dude")
else:
print("sup")
In [ ]:
for x in range(5):
print(x**2)
In [ ]:
for x in ("all","we","wanna","do","is","eat","your","brains"):
print(x)
In [ ]:
x = 0
while x < 5:
print(pow(2,x))
x += 1 # don't forget to increment x!
In [ ]:
# Multiple levels
for x in range(1,5):
if x % 2 == 0:
print(str(x) + " is even.")
else:
print(str(x) + " is odd.")
In [ ]:
# Blocks cannot be empty
x = "fried goldfish"
if x == "spam for dinner":
print("I will destroy the universe")
else:
AA=1
# Nothing here.
In [ ]:
# Use a 'pass' statement, which indicates 'do nothing'
x = "fried goldfish"
if x == "spam for dinner":
print("I will destroy the universe")
else:
pass
In [ ]:
# Use a 'break' statement to escape a loop
x = 0
while True:
print(x**2)
if x**2 > 10:
break
x +=1
In [ ]:
In [ ]:
def addnums(x,y):
return x + y
In [ ]:
addnums(2,3)
In [ ]:
print(addnums(0x1f,3.3))
In [ ]:
print addnums("a","b")
In [ ]:
print addnums("cat",23232)
In [ ]:
def numop(x,y):
x *= 3.14
return x + y
x = 2
print(numop(x, 8))
print(x)
In [ ]:
def numop(x,y):
x *= 3.14
global a
a += 1
return x + y, a
a = 2
numop(1,1)
numop(1,1)
In [ ]:
def changeme_1( mylist ):
mylist = [1,2,3,4]; # This would assig new reference in mylist
print( "Values inside the function changeme_1: ", mylist)
return
def changeme_2( mylist ):
mylist.append([1,2,3,4]);
print( "Values inside the function changeme_2: ", mylist)
return
mylist1 = [10,20,30];
changeme_1( mylist1 );
print( "Values outside the function: ", mylist1)
print
mylist2 = [10,20,30];
changeme_2( mylist2 );
print( "Values outside the function: ", mylist2)
You can call a function by using the following types of formal arguments:
In [ ]:
def numop1(x,y,multiplier=1.0,greetings="Thank you for your inquiry."):
""" numop1 -- this does a simple operation on two numbers.
We expect x,y are numbers and return x + y times the multiplier
multiplier is also a number (a float is preferred) and is optional.
It defaults to 1.0.
You can also specify a small greeting as a string. """
if greetings is not None:
print(greetings)
return (x + y)*multiplier
In [ ]:
help(numop1)
In [ ]:
numop1(1,1)
In [ ]:
numop1(1,1,multiplier=-0.5,greetings=None)
In [ ]:
def cheeseshop(kind, *arguments, **keywords):
print( "-- Do you have any", kind, "?")
print( "-- I'm sorry, we're all out of", kind )
for arg in arguments:
print( arg)
print ("-" * 40)
keys = keywords.keys()
keys.sort()
for kw in keys:
print (kw, ":", keywords[kw])
In [ ]:
cheeseshop("Limburger",
"It's very runny, sir.",
"It's really very, VERY runny, sir.",
shopkeeper='Michael Palin',
client="John Cleese",
sketch="Cheese Shop Sketch")
In [ ]:
import math
In [ ]:
math.cos(0)
In [ ]:
math.cos(math.pi)
In [ ]:
math.sqrt(4)
In [ ]:
from datetime import datetime
In [ ]:
now = datetime.now()
In [ ]:
print(now.year, now.month, now.day)
In [ ]:
from math import acos as arccos
In [ ]:
arccos(1)
In [ ]: