python11day

菲波那契数列

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”)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值