函数调用函数
函数名可以当作参数传递
函数名() 执行函数
函数名 代指函数本身
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def f1():
return "F1"
# f1 = 函数
# f1 => 代指函数
# f1() => 执行函数
def f2(arg):
arg()
return "F2"
# x = 123
# f1 = f1函数
# f2 = f2函数
# f2(x)
#执行f2函数, f1函数当作参数
f2(f1)
filter()的函数实现:
def MyFile(func, seq):
result = []
for item in seq:
req = func(item)
if req == True:
result.append(item)
return result
def f1(x):
if x > 22:
return True
else:
return False
r = MyFile(f1, [11, 22, 33, 44, 55])
print(r)
实现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(r)
r = map(x,li)
函数读取文件来判读用户登录
def login(username,password):
f = open('db1','r',encoding='utf-8')
for line in f:
list = line.strip()
list_line = list.split(";")
if username == list_line[0] and password == list_line[1]:
return True
return False
while True:
user = input("USERNAME: ")
pwd = input("PASSWORD: ")
is_login = login(user,pwd)
if is_login:
print("Login successfully!")
else:
print("LOgin Failed!")
db1:
admin ; 111
root ; 222
添加,删除账号;更改密码;已存在账号判断,完整代码:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
def login(username,password):
f = open('db1','r',encoding='utf-8')
for line in f:
list = line.strip()
list_line = list.split(";")
if username == list_line[0] and password == list_line[1]:
return True
return False
def register(username,password):
'''
:param username: 用户名
:param password: 密码
:return: True 注册成功
'''
with open("db1",'a',encoding="utf-8") as f:
temp = "\n" + username +";" + password
f.write(temp)
return True
def user_exist(username):
with open("db1",'r',encoding='utf-8') as f1:
for line in f1:
list = line.strip()
list_line = list.split(";")
if username ==list_line[0]:
return True
return False
def user_del(username, password):
with open("db1", 'r+', encoding="utf-8") as f:
passwd_list = []
for line in f:
list = line.strip()
list_user = list.split(";")
if list_user[0] == username:
pass
else:
passwd_list.append(list)
with open("db1", "w", encoding="utf-8") as f:
for item in passwd_list:
f.write(item+"\n")
return True
return False
def main():
print("Welcome to GrapeCity!")
inp = input("1. login; 2. Rigister; 3.Del user ; 4. change password.")
if inp =="1":
user = input("USERNAME: ")
pwd = input("PASSWORD: ")
is_login = login(user,pwd)
if is_login:
print("Login successfully!")
else:
print("Login Failed!")
elif inp == "2":
user = input("Please enter a username: ")
pwd = input("Please enter the password: ")
is_exist = user_exist(user)
if is_exist:
print("The user has exist,can not register.")
else:
register_user = register(user,pwd)
if register_user:
print("Register Successfully!")
else:
print("Register Failed!")
elif inp == "3":
user = input("please enter a username: ")
pwd = input("Please enter a password: ")
if user_exist(user):
is_user_del = user_del(user,pwd)
if is_user_del:
print("Succed to delete user %s" %user)
else:
print("Delete user failed!")
else:
print("User don't exist!")
main()