代码如下:
x = 1
y = math.sqrt
callable(x) #False
callable(y) #True
代码如下:
def hello(name):
return 'Hello, ' + name + '!'
代码如下:
fibs = [0, 1]
for i in range(8):
fibs.append(fibs[-2] + fibs[-1])
result:[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
代码如下:
def fibs(num):
result = [0, 1]
for i in range(num-2):
result.append(result[-2] + result[-1])
return result
代码如下:
def test():
print 'This is printed'
return
print 'This is not'
代码如下:
def try_to_change(n):
n = 'Mr. Gumby'
name = 'Mrs. Entity'
try_to_change(name)
name # 'Mrs. Entity'
代码如下:
def change(n):
n[0] = 'Mr. Gumby'
names = ['Mrs. Entity', 'Mrs. Thing']
change(names)
names #['Mr. Gumby', 'Mrs. Thing']
代码如下:
def hello_1(greeting, name):
print '%s, %s!' % (greeting, name)
hello_1(greeting='Hello', name='world') #Hello, world!
代码如下:
def init(data): #1
data['first'] = {}
data['middle'] = {}
data['last'] = {}
def lookup(data, label, name):
return data[label].get(name)#2
def store(data, full_name):
names = full_name.split()#3
if len(names) == 2: names.insert(1, '')#4
labels = 'first', 'middle', 'last'
for label, name in zip(labels, names):#5
people = lookup(data, label, name)
if people:
people.append(full_name)#6
else:
data[label][name] = [full_name]
代码如下:
MyNames = {}
init(MyNames)
store(MyNames, 'Magnus Lie Hetland')
lookup(MyNames, 'middle', 'Lie') #['Magnus Lie Hetland']
代码如下:
test = 'a,2,d'
test.split(',') #['a', '2', 'd']
name = 'my xy dd'
names = name.split()
names #['my', 'xy', 'dd']
代码如下:
names.insert(1, '')
names #['my', '', 'xy', 'dd']
代码如下:
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)#(1, 4), (2, 5), (3, 6)
代码如下:
def print_params_2(title, *params):
print title
print params
print_params_2('Params:', 1, 2, 3)
代码如下:
def print_params(**params):
print params
print_params(x=1, y=2, z=3)
代码如下:
def store(data, *full_names):
for full_name in full_names:
names = full_name.split()
if len(names) == 2: names.insert(1, '')
labels = 'first', 'middle', 'last'
for label, name in zip(labels, names):
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]
代码如下:
d = {}
init(d)
store(d, 'Han Solo')
store(d, 'Luke Skywalker', 'Anakin Skywalker')
lookup(d, 'last', 'Skywalker')#['Luke Skywalker', 'Anakin Skywalker']