菲波那契数列
fibs = [0, 1]
num = int(input("how many fibonacci numbers do you want? "))
for i in range(num - 2):
fibs.append(fibs[-2] + fibs[-1])
print(fibs)
def init(data):
data[‘first’] = {}
data[‘middle’] = {}
data[‘last’] = {}
def lookup(data, label, name):
return data[label].get(name)
def store(data, *full_names):
for full_name in full_names:
names = full_name.split()
if len(names) == 2: names.insert(1, ’ ')
lables = ‘first’, ‘middle’, ‘last’
for label, name in zip(lables, names):
people = lookup(data, label, name)
if people:
people.append(full_name)
else:
data[label][name] = [full_name]
do = {}
init(do)
print(store(do, ‘han slao’))
print(do)
def foo():
x = 42 # 局部变量
return x
x = 1 # 全局变量
y = foo()
print(y)
print(x)
引用全局变量,global()[’’]获取全局变量值,vars返回全局变量的字典值,locals返回局部变量的字典值
def test(a):
print(a + b)
b = ‘9’
c = test(“3”)
递归
阶乘
def facorial(n):
if n == 1:
return 1
else:
return n * facorial(n - 1)
print(facorial(6))
foo = [2, 18, 9, 7, 8]
def f(x):
return x ** 4
print(x)
print(list(map(f, foo))) # map将其他类型转换为列表,将某个功能作用于每个元素,python中map返回的是迭代器
print(list(map(lambda y: y ** 2, foo))) # lambda函数冒号前是参数,可以有多个,用逗号隔开
def f_1(y):
return y % 2 == 1
foo_1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(list(filter(f_1, foo_1))) # filter返回其函数为真的元素列表
from functools import reduce
def f_3(x, y):
return x * y
print(reduce(f_3, range(1, 9))) # reduce必须有两个元素,将计算结果与下个元素继续累加计算
def function(a, b):
print(a, b)
print(list((function, (‘good’, ‘ggg’))))
多态,使用对象而不知道其类型,不同的子类对象调用相同的方法,产生不同的执行结果
def getPrice(object):
if isinstance(object, tuple):
return object[1]
elif isinstance(object, dict):
return int(object[‘price’])
else:
return mag_network_method(object)
封装根据职责将属性和方法封装到一个抽象的类中
继承:实现代码的重用,相同的代码不需要重复的编写
hasattr(x,‘call’)查看类中的方法是否可用
异常
import encodings
print(dir(encodings)) # dir列出模块内容
try:
x = input("first number: ")
y = input("second number: ")
print(int(x) / int(y))
except Exception as e: # (ZeroDivisionError,TypeError,NameError) as e:#用 as e 显示错误
print(“your input numbers were bugs”)
print(e)
try:
x = 1 / 0
except (ZeroDivisionError) as e:
print(e)
else:
print(“that went well”)
finally:
print(“cleaning up”)