Learn_Day7 登录实例、冒泡排序、递归函数、初识装饰器

上节补充:
# 函数名可以当作参数进行传递
def f1():
    return "F1"

def f2(arg):
    # print(arg)
    return "F2"

x = 123
print("f1:", f1())
# f1: F1
print("f2(x):", f2(x))
# f2(x): F2
print("f2(f1):", f2(f1))
# f2(f1): F2
# 实现筛选功能等同于fillter
def MyFillter(func, seq):
    result = []
    for i in seq:
        ret = func(i)
        if ret:
            result.append(i)
    return result

def f1(x):
    if x > 22:
        return True
    else:
        return False

r = MyFillter(f1, [11, 22, 33, 44])
print("MyFillter:", r)
# MyFillter: [33, 44]
# 实现筛选功能等同于map
li = [11, 22, 33, 44]
def x(arg):
    return arg + 100

def MyMap(func, arg):
    result = []
    for i in arg:
        ret = func(i)
        result.append(ret)
    return result

r = MyMap(x, li)
print("MyMap:", r)
# MyMap: [111, 122, 133, 144]

实例 ==>> 用户登录:
# strip()   使用strip时无参数默认去掉两端的空格和换行符\n,有参数则去掉两端的指定值(即参数值)
# split()   用参数分割字符串("alex|123" ==>> split("|") ==>> "alex","123")

# 方法1
user = input("USERNAME:")
pwd = input("PASSWORD:")
f = open("db.txt", 'r', encoding="utf-8")
for line in f:
    line = line.strip()
    line_list = line.split("|")
    print(line_list)
    if user == line_list[0] and pwd == line_list[1]:
      print("登录成功!")
      break
# 方法2
def login(username, password):
    """
    用于用户名密码验证
    :param username:用户名
    :param password:密码
    :return:True:验证成功;False:验证失败
    """
    f = open("db.txt", 'r', encoding="utf-8")
    for line in f:
        line = line.strip()
        line_list = line.split("|")
        if user == line_list[0] and pwd == line_list[1]:
            return True
        return False
user = input("USERNAME:")
pwd = input("PASSWORD:")
# is_login = login(user, pwd)
# if is_login:
if login(user, pwd):
    print("登录成功")
else:
    print("失败")

冒泡排序:
# a1 = 123, a2 = 456, 将a1与a2的值互换
a1 = 123
a2 = 456

temp = a1
a1 = a2
a2 = temp

print("a1:", a1, "a2:", a2)
# a1: 456 a2: 123
# 对列表li进行排序
li = [2, 3, 45552, 212, 2343565, 13, ]
for i in range(len(li) - 1):
    if li[i] > li[i + 1]:
        temp = li[i]
        li[i] = li[i + 1]
        li[i + 1] = temp
print("li:", li)
# li: [2, 3, 212, 45552, 13, 2343565]

递归函数:
def f1():
    return "f1"
def f2():
    r = f1()
    return r
def f3():
    r = f2()
    return r
def f4():
    r = f3()
    return r
print(f4())  # f1

#斐波那契函数:
def func(a1, a2, n):
    a3 = a1 + a2
    if n == 10:
        return a2
    return func(a2, a3, n + 1)


print(func(0, 1, 1))
参考实例:http://m.blog.csdn.net/article/details?id=49422093

初识装饰器:
装饰器用于装饰某个函数(类或方法),让函数(类或方法)在执行前或执行后做一些操作
  1. 执行outer函数并且将下面的函数名当作参数
  2. 将outer 参数的返回值重新赋值给f1(f1=outer的返回值)
# 装饰器
def outer(func):
    def inner():
        print("hello")
        r = func()
        print("end")
        return r

    return inner


@outer
def f1():
    print("F1")


f1()
# hello
# F1
# end

 

posted @ 2017-02-23 14:02  Grisom  阅读(116)  评论(0编辑  收藏  举报