1.验证三次用户登录
#!/usr/bin/python env # coding:utf-8
# 验证三次用户登录
count = 0
while count < 3:
username = input("输入账号:")
pwd = input("输入密码:")
if username == "zq" and pwd == "zq":
print("登录成功")
break
else:
print("账号或者密码错误")
count += 1
print("退出系统!!!!")
2.随机生成四位数
# 随机生成4位数
import random
def ident_code(num=4):
res = ""
for i in range(num):
# 数字0-9
num1 = str(random.randint(0, 9))
# 大写字母A-Z
# a = chr(random.randint(65, 90))
# 小写字母a-z
b = chr(random.randint(97, 122))
res += random.choice([num1, b])
return res
print(ident_code())
3.99乘法表
# 99乘法表 for i in range(1, 10): string = "" for j in range(1, i + 1): string += str(j) + " * " + str(i) + " = " + str(i * j) + " " print(string)
4.文件操作
# 文件操作去取文件中空行 并将zhang改为zzzzzzzzzz with open('data_txt.py', encoding="utf-8") as f: with open('temp.py', 'w', encoding="utf-8") as f1: # 要改数据的行号 res_line = [] # 保存除去空行后的数据 del_n_data = [] data = f.readlines() for i in data: if len(i) > 1: del_n_data.append(i) for k,v in enumerate(del_n_data): if v.startswith("zhang") and len(v) == 6: res_line.append(k) for i in res_line: del_n_data[i] = "zzzzzzzzzzzzzzz " print(del_n_data) f1.writelines(del_n_data)
5.读取文件的最后一行
# 读取文件最后一行 循环文件的推荐方式 with open('20190225.log', 'rb') as f: for i in f: offs = -10 while True: f.seek(offs, 2) data = f.readlines() #最后一行数据+上面数据 用列表索引-1,可取到最后一行数据 if len(data) > 1: print(data[-1].decode("utf-8")) break #data长度小于1,表示未读到大于一行的数据 添加offs偏移量 offs *= 2
6.斐波那契数列
# 斐波那契数列 class Fib: def __init__(self, num): self._x = 1 self._y = 1 self.num = num def __iter__(self): return self def __next__(self): self._x, self._y = self._y, self._x + self._y if self._x > self.num: raise StopIteration("结束") return self._x def show_fib(self): l = [] for i in self: l.append(i) return l #求1000内的数 f1 = Fib(10000) print(f1.show_fib())
7.生成器 统计每个省份的年龄
# 生成器 统计每个省份的年龄 ''' b.txt {'name': '北京', 'age': 20} {'name': '上海', 'age': 33} {'name': '广州', 'age': 28} {'name': '深圳', 'age': 40} ''' def get_age(): with open('b.txt',encoding='utf-8') as f: for i in f: yield i g = get_age() all_age = sum(int(eval(i)['age']) for i in g) g = get_age() def show_age(): for i in g: print('省份:%s 人口平均年龄:%.2f%%' %(eval(i)['name'],100*eval(i)['age']/all_age)) show_age()
8.装饰器验证用户账号登录
# 简单账号密码验证 # 账号 密码 user_list = [ {'username': 'zxq', 'passwd': 'zxq'}, {'username': 'zq', 'passwd': 'zq'}, ] # 用户状态 current_status = {'username': None, 'login': False} def check_passwd(func): def wrapper(*args, **kwargs): if current_status['username'] and current_status['login']: res = func(*args, **kwargs) return current_status['username'] username = input('username:'.strip()) passwd = input('password:'.strip()) for user_dict in user_list: if username == user_dict['username'] and passwd == user_dict['passwd']: current_status['username'] = username current_status['login'] = True res = func(*args, **kwargs) return current_status['username'] else: print('用户名或者密码错误') return wrapper def index(): print('hi, guest ,welcome to my index') return "ok_index" @check_passwd def home(): print('hi, %s ,welcome home' % (current_status['username'])) return "ok_home" @check_passwd def shop(): print('hi, %s ,welcome shop' % (current_status['username'])) return 'ok_shop' index() home() shop()
9.函数闭包带参数装饰器 验证用户登录
# 基于文件账号密码验证 user_list = [ {'username': 'zxq', 'passwd': 'zxq'}, {'username': 'zq', 'passwd': 'zq'}, ] current_status = {'username': None, 'login': False} def auth(auth_type='filedb'): def check_passwd(func): def wrapper(*args, **kwargs): if auth_type == 'strdb': print('认证类型是:%s' % (auth_type)) if current_status['username'] and current_status['login']: res = func(*args, **kwargs) return 'ok' username = input('username:'.strip()) passwd = input('password:'.strip()) for user_dict in user_list: if username == user_dict['username'] and passwd == user_dict['passwd']: current_status['username'] = username current_status['login'] = True res = func(*args, **kwargs) return 'ok' else: print('用户名或者密码错误') elif auth_type == 'filedb': print('认证类型是:%s' % (auth_type)) else: print('认证类型是:%s' % ('未知')) return wrapper return check_passwd @auth(auth_type='strdb') def index(): print('hi, guest,welcome') @auth(auth_type='strdb') def home(): print('hi, %s,welcome home' % (current_status['username'])) return "ok" @auth(auth_type='strdb') def shop(): print('hi, %s,welcome shop' % (current_status['username'])) return 'ok' index() home() shop()
10.文件增删改查
#!/usr/bin/python env # coding:utf-8 import os def file_handler(backend_data,res=None,type='fetch'): if type == 'fetch': with open('haproxy.conf','r') as read_f: tag=False ret=[] for read_line in read_f: if read_line.strip() == backend_data: tag=True continue if tag and read_line.startswith('backend'): # tag=False break if tag: print('