python练习
1.检验注册用户是否合法;需要输入用户名,校验用户名是否被注册,如已注册,提示已经注册过,没注册就可以注册;用户名不能为空;用户名长度必须在6-13位之间;最多只能输入三次。
1 users = ['aatest1','aatest2','aatest3']
2 for i in range(3):
3 username = input('请输入用户名:').strip()
4 if len(username)>5 and len(username)<13:
5 if username in users: #if users.count(username)>0
6 print('这个名字太好了,已经被注册!')
7 else:
8 print('这个名字不错,赶紧注册吧!')
9 break
10 else:
11 print('用户名应该是6-12位!')
12 else:
13 print('失败次数太多!')
2.输出已完成工作的员工和未完成工作的员工,并分别统计人数
stus=[
['小明','未完成'],
['小白','已完成'],
['小紫','已完成'],
['小红','未完成'],
['小绿','未完成'],
['小黄','未完成'],
['小黑','已完成']
]
1 stus=[
2 ['小明','未交'],
3 ['小白','已交'],
4 ['小紫','已交'],
5 ['小红','未交'],
6 ['小绿','未交'],
7 ['小黄','未交'],
8 ['小黑','已交']
9 ]
10 pass_list = []
11 fail_list = []
12 for stu in stus:
13 stuname=stu[0]
14 status=stu[1]
15 if status=='未交':
16 fail_list.append(stuname)
17 else:
18 pass_list.append(stuname)
19 print('未交作业的同学是:%s,总共有%s人'%(fail_list,len(fail_list)))
20 print('已交作业的同学是:%s,总共有%s人'%(pass_list,len(pass_list)))
3.检验注册用户是否合法;需要输入用户名,校验用户名是否被注册,如已注册,提示已经注册过,没注册就可以注册;用户名不能为空;用户名长度必须在6-13位之间;校验密码和确认密码是否一致;最多只能输入三次;输出所有注册成功的账号。
1 users={'cctest1':'123456','cctest2':'333444'}
2 for i in range(3):
3 uname=input('uname:').strip()
4 pwd=input('pwd:').strip()
5 cpwd=input('cpwd:').strip()
6 if uname=='' or pwd=='' or cpwd=='':
7 print('用户名/密码不能为空')
8 elif pwd!=cpwd:
9 print('密码和确认密码不一致')
10 elif uname in users:
11 print('用户名已注册')
12 else:
13 print('恭喜,注册成功')
14 users.setdefault(uname,pwd)
15 break
16 else:
17 print('失败次数太多')
18 print(users)
4.校验密码是否合法的程序。
输入一个密码
1、长度5-10位
2、密码里面必须包含,大写字母、小写字母和数字
3、最多输入5次
1 for i in range(5):
2 list=[]
3 passwd=input("请输入密码:").strip()
4 if len(passwd)>4 and len(passwd)<11:
5 for i in passwd:
6 if i.isdigit()==True:
7 list.append(1)
8 elif i.isupper()==True:
9 list.append(2)
10 elif i.islower()==True:
11 list.append(3)
12 else:
13 print('输入不合法')
14 break
15 if 1 in list and 2 in list and 3 in list:
16 print("密码合法,请注册!")
17 else:
18 print("密码必须由大写字母、小写字母和数字组成!")
19 else:
20 print('用户名长度不合法!长度5-10之间!')
21 else:
22 print('失败次数过多!')
5.写一个录入学生作业情况的一个程序
1、查看学生作业情况
2、录入学生作业情况
3、可以让输入3次,需要为空的情况
homeworks = {
'张流量':
{'2018.3.22':"未交",'2018.3.23':'wei交'},
'田雨':
{'2018.3.22':"未交",'2018.3.23':'wei交'},
}
1 homeworks ={
2 '张流量': {
3 '2018-03-31':"未交"
4 },
5 '李wifi':{
6 '2018-03-31':"未交"
7 }
8 }
9 choice = input('请输入你的选择,1查看作业,2录入:')
10 if choice=='1':
11 for k,v in homeworks.items():
12 print('【%s】的作业情况是 %s'%(k,v))
13 elif choice=='2':
14 for i in range(3):
15 name = input('输入名字:').strip()
16 time = input('输入日期:').strip()
17 status = input('输入状态:').strip()
18 if name =='' or time =='' or status=='':
19 print('输入不能为空')
20 else:
21 if name in homeworks:
22 tmp = {time:status}
23 homeworks[name].update(tmp)
24 print('更新学生作业信息成功')
25 break
26 else:
27 homeworks[name]={time:status}
28 print('成功')
29 break
30 print(homeworks)
6.你是一个高级测试工程师,现在要做性能测试,需要你写一个函数,批量生成一些注册使用的账号。
产生的账号是以@163.com结尾,长度由用户输入,产生多少条也由用户输入,用户名不能重复,用户名必须由大写字母、小写字母、数字组成,结果如下图:

import random,string acc_set = set() length = input('请输入需生成的账号长度:') count = input('请输入要生成的账号个数:') if count.isdigit(): count = int(count) while len(acc_set) != count: upper = random.choice(string.ascii_uppercase) lower = random.choice(string.ascii_lowercase) number = str(random.randint(0,9)) other_length = int(length) - 3 other_string = random.sample(string.digits+string.ascii_letters,other_length) account_list = [upper , lower , number] + other_string random.shuffle(account_list) print(account_list) account = ''.join(account_list)+'@163.com' acc_set.add(account+'\n') else: open('account.txt','w').writelines(acc_set) else: print('输入的账号个数必须是整数!')
7.随机生成指定数量的电话号码,号码以1861235开头。
1 import random
2 start = '1861235'
3 f = open('phone.txt','w+',encoding='utf-8')
4 num = input('请输入你想生成的电话号码个数:')
5 for i in range(int(num)):
6 random_num = str(random.randint(1,9999))
7 new_num = random_num.zfill(4)
8 phone = start+new_num
9 f.write(phone+'\n')
10 f.close()
8.公司服务器,经常被别人攻击,要写个监控nginx日志的脚本,每分钟运行一次,如果这一分钟内同一个ip请求次数超过200次,加入黑名单,nginx日志每一行的格式如下:
1 46.161.9.44 - - [23/Jun/2017:03:17:37 +0800] "GET /bbs/forum.php?mod=forumdisplay&fid=2 HTTP/1.0" 200 48260 "http://aaaa.bbbbb.com/bbs/forum.php?mod=forumdisplay&fid=2" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "-"
2 46.161.9.44 - - [23/Jun/2017:03:17:39 +0800] "GET /bbs/forum.php?mod=forumdisplay&fid=2 HTTP/1.0" 200 46200 "http://aaaa.bbbbb.com/bbs/forum.php?mod=forumdisplay&fid=2" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36" "-"
3
1 import time
2
3 point = 0 # 每次记录文件指针的位置
4 while True:
5 all_ips = [] #存放所有的ip地址
6 f = open('access.log',encoding='utf-8')
7 f.seek(point)#移动文件指针
8 for line in f:
9 ip = line.split()[0]#先按照空格分割元素,然后取第一个元素,就是IP地址
10 all_ips.append(ip)
11 point = f.tell() #记录了指针的位置
12 all_ip_set = set(all_ips) #
13 for ip in all_ip_set:
14 if all_ips.count(ip)>200:
15 print('应该加入黑名单的ip是%s'%ip)
16 f.close()
17 time.sleep(60) #暂停60秒
9.写一个自动生成密码文件的程序
1、你输入几,文件里面就给你产生多少条密码
2、密码必须包括,大写字母、小写字母、数字、特殊字符
3、密码不能重复
4、密码都是随机产生的
5、密码长度6-11
http://www.nnzhp.cn/archives/150
随机数怎么用 参考 random模块怎么用
1 import string,random
2 pwd_len = input('请输入你要产生多少条密码:').strip()
3 pwds = set() #存放所有的密码
4 if pwd_len.isdigit():
5 pwd_len = int(pwd_len)
6 while len(pwds)!=pwd_len:
7 num=random.choice(string.digits)
8 letter = random.choice(string.ascii_lowercase)
9 upper = random.choice(string.ascii_uppercase)
10 pun = random.choice(string.punctuation)
11 pasd_len = random.randint(6,11) #代表生成密码的长度
12 other_len = pasd_len - 4 #剩余的长度
13 all_strs = string.digits+string.ascii_letters+string.punctuation
14 other_passwd = random.sample(all_strs,other_len)#随机取到剩下的密码
15 pwd_list = [num,letter,upper,pun]+other_passwd #产生密码之后的list
16 random.shuffle(pwd_list)#顺序打乱
17 pwd_str = ''.join(pwd_list) #最终的密码
18 pwds.add(pwd_str+'\n')
19 else:
20 open('passwds.txt','w').writelines(pwds)
21
22 else:
23 print('条数必须是整数!')
10.写一个注册的程序,账号和密码都存在文件里面。
choice = input('请输入你的选择:1,注册2、删除用户3、登录')
#注册
输入
账号
密码
密码确认
#需要校验用户是否存在,两次输入的密码,是否一致,为空的情况
#账号和密码都存在文件里面
#删除
输入一个用户名
#需要校验用户是否存在
#登录
输入账号密码登录
1 user_info = {} #存放所有的用户
2 with open('users.txt') as f:
3 for line in f:
4 # niuhanyang,123456\n
5 line = line.strip()
6 temp = line.split(',')
7 username = temp[0]
8 pwd = temp[1]
9 user_info[username]=pwd
10 for i in range(3):
11 choice = input('请输入你的选择'
12 '1、登录 2、注册 3、删除').strip()
13 if choice=='1':
14 username = input('username:').strip()
15 pwd = input('pwd:').strip()
16 if username and pwd:
17 if username in user_info:
18 if user_info.get(username)==pwd:
19 print('登录成功')
20 else:
21 print('账号密码错误!')
22 else:
23 print("user not found!")
24 else:
25 print('账号密码不能为空!')
26 elif choice=='2':
27 username = input('username:').strip()
28 pwd = input('pwd:').strip()
29 cpwd = input('cpwd:').strip()
30 if username and pwd and cpwd:
31 if username in user_info:
32 print('该用户已经被注册!')
33 else:
34 if pwd==cpwd:
35 user_info[username]=pwd
36 print('恭喜,注册成功!')
37 else:
38 print('两次输入的密码不一致!')
39 else:
40 print('不能为空!')
41 elif choice=='3':
42 username = input('username:').strip()
43 if username:
44 if username in user_info:
45 user_info.pop(username)
46 print('删除成功!')
47 else:
48 print('不能为空!')
49 else:
50 print("输入有误,请重新输入")
51 else:
52 with open('users.txt','w') as fw:
53 for uname,pwd in user_info.items():
54 fw.write(uname+','+pwd+'\n')
11、写一个生成双色球号码的一个程序,生成的号码写到文件里面
# 中奖号码由6个红色球号码和1个蓝色球号码组成
# 篮球范围:01-16
# 红球范围:01-33
def swq(num):
random.ranint(1,16)
#tikti.txt
篮球:xx 红球号码是xx 01 08 09 12 13 19
篮球:xx 红球号码是xx 01 08 09 12 13 19
1 import random 2 3 def seq(): 4 red_num = [] #红球 5 while len(red_num)!=6: 6 # 1 - 33 7 num = random.randint(1,33) 8 num = str(num).zfill(2) 9 if num not in red_num: 10 red_num.append(num) 11 blue_num = str(random.randint(1,16)).zfill(2) 12 red_num_str = ' '.join(red_num) 13 res = '篮球是 %s 红球是 %s\n'%(blue_num,red_num_str) 14 return res 15 16 def write_file(l): 17 with open('seq.txt','w',encoding='utf-8') as fw: 18 fw.writelines(l) 19 20 def main(): 21 all_res = [] #存所有结果的 22 num = input('请输入你要产生多少条:').strip() 23 if num.isdigit(): 24 num = int(num) 25 while num != len(all_res): 26 res = seq() 27 if res not in all_res: 28 all_res.append(res) 29 else: 30 print('条数只能是整数!') 31 write_file(all_res) 32 main()
12、商品管理的程序,商品信息都存在一个json串里面
校验商品是否存在
1、查询商品信息
2、新增商品 ##校验价格是否合法 #校验商品是否存在
3、修改商品信息 ##校验商品是否存在
if chice =="1":
query_goods()
elif choice = ="2":
add_goods()
import json FILE_NAME = 'goods.json' def op_file(name,content=None): if content: with open(name,'w',encoding='utf-8') as fw: json.dump(content,fw,indent=4,ensure_ascii=False) else: with open(name,encoding='utf-8') as fr: res = json.load(fr) return res all_goods = op_file(FILE_NAME) def check_price(price): price = str(price) if price.isdigit(): price = int(price) if price>0: return True else: if price.count('.')==1: tmp = price.split('.') #0.0 left = tmp[0] right = tmp[1] # 1.00 if left.isdigit() and right.isdigit() and int(right)>0: #1.0 return True elif left.isdigit() and right.isdigit() and int(left)>0: # 0.1 return True return False def get_good_info(): while True: good_name = input('商品名称:').strip() price = input('price:').strip() count = input('count:').strip() color = input('color:').strip() if good_name and price and count and color: if not check_price(price): print('价格输入不合法,必须大于0') elif not count.isdigit() and int(count)<1: print('数量不合法') else: return good_name,price,count,color else: print('输入不能为空!') def add_good(): good_name,price,count,color = get_good_info() if good_name not in all_goods: all_goods[good_name]= { 'price':price, 'count':count, 'color':color } op_file(FILE_NAME,all_goods) print('添加完成!') else: print('商品已经存在!') def update_good(): good_name,price,count,color = get_good_info() if good_name in all_goods: all_goods[good_name]= { 'price':price, 'count':count, 'color':color } op_file(FILE_NAME,all_goods) print('修改完成!') else: print('商品不存在!') def query_good(): good_name = input('商品名称:').strip() if good_name in all_goods: print(all_goods.get(good_name)) else: print('商品不存在') def delete_good(): good_name = input('商品名称:').strip() if good_name in all_goods: all_goods.pop(good_name) op_file(FILE_NAME,all_goods) else: print('商品不存在') def main(): for i in range(3): choice = input('请输入你的选择' '1、添加' '2、修改' '3、删除' '4、查看' '5、退出') if choice=="1": add_good() elif choice=="2": update_good() elif choice=="3": delete_good() elif choice=="4": query_good() elif choice=="5": quit('程序退出') else: print('输入错误,请重新输入!') return main() main()
13、logs目录下,有一部分文件是空的
1、删除log目录下,所有的空文件
2、删除5天前的文件
import os,datetime,time for abs_path,dir,file in os.walk(r'D:\syz_python\code\day6\logs'): for f in file: file_name = os.path.join(abs_path, f) #拼接文件和绝对路径 size = os.path.getsize(file_name) #获取文件大小 file_date = f.split('.')[0].split('_')[-1] #获取文件日期 five_days = str(datetime.date.today() + datetime.timedelta(days=-5)) #将五天前日期转化为str if file_date<five_days or size ==0: os.remove(file_name)
14、写代码实现,把我的数据库里面的stu表中的数据,导出到excel中
#编号 名字 性别
import pymysql,xlwt coon = pymysql.connect( host='118.24.3.40',user='jxz',passwd='123456', port=3306,db='jxz',charset='utf8' #port必须写int类型, #charset这里必须写utf8 ) cur = coon.cursor() #建立游标 cur.execute('select * from stu;')#执行sql语句 res = cur.fetchall() #获取所有返回的结果 print(res) title = ['编号','姓名','性别'] book = xlwt.Workbook() #新建一个excel sheet = book.add_sheet('stu_info') for i in range(len(title)): sheet.write(0,i,title[i]) row = 1 for i in res: col = 0 for j in i: sheet.write(row,col,j) col+=1 row+=1 book.save('stu_info.xls') cur.close()#关闭游标 coon.close()#关闭连接
15、注册 登录。数据都存在数据库里面
id username passwd
注册的时候,密码存的是加密之后的密码
username pwd cpwd,都是必填的
用户不能重复
登录
账号
密码
登录成功之后打印当前的日期
def my_db(host,user,passwd,db,sql,rec,port=3306,charset='utf8'): import pymysql coon = pymysql.connect(user=user, host=host, port=port, passwd=passwd, db=db, charset=charset ) cur = coon.cursor() #建立游标 cur.execute(sql,rec)#执行sql if sql.strip()[:6].upper()=='SELECT': res = cur.fetchall() else: coon.commit() res = 'ok' cur.close() coon.close() return res def my_md5(pwd): import hashlib new_pwd = pwd.encode() m = hashlib.md5() m.update(new_pwd) return m.hexdigest() import datetime for i in range(3): choice = input('请输入你的选择: 1.登录 2.注册') if choice=='1': name = input('username:').strip() pwd = input('pwd:').strip() if name and pwd : s_pwd = my_md5(pwd) res = [name, s_pwd] result = my_db(host='192.168.21.129',user='root',passwd='123456',port=3306,db='test',charset='utf8',sql = 'select * from user where username=%s and passwd=%s',rec = [name,s_pwd]) if result!=(): print('登录成功!',datetime.datetime.today()) else: print('用户名或密码错误!') else: print('用户名密码不能为空!') elif choice == '2': name = input('username:').strip() pwd = input('pwd:').strip() cpwd = input('cpwd:').strip() if name and pwd and cpwd: sql = 'select username from user where username = %s' sql_name = my_db(host='192.168.21.129',user='root',passwd='123456',port=3306,db='test',charset='utf8',sql = 'select username from user where username = %s',rec = [name]) if sql_name != (): print('该用户已注册!') else: if pwd != cpwd: print('两次输入的密码不一致!') else: s_pwd = my_md5(pwd) my_db(host='192.168.21.129', user='root', passwd='123456', port=3306, db='test', charset='utf8', sql="insert into user(username,passwd) values(%s,%s)", rec = [name, s_pwd]) print('恭喜你,注册成功!') else: print('输入不能为空!')
16、修改excel,把app_student.xls里面的数据,
1、如果这一行数据里面有乱码,那么就给他删掉
2、再加上一列,是否毕业
3、如果班级是天蝎座的话,毕业这一列写成毕业
4、其他班级的写成未毕业
import xlrd from xlutils import copy book = xlrd.open_workbook('app_student.xls') sheet = book.sheets()[0] new_book = copy.copy(book)# 通过xlutils这个模块里面copy方法,复制一份excel sheet1 = new_book.get_sheet(0) # 获取sheet页 table = sheet.row_values(0) table.append('是否毕业') for col,field in enumerate(table): sheet1.write(0, col, field) print(sheet.row_values(0)) tmp = 1 for row in range(1,sheet.nrows): list = sheet.row_values(row) if '?' in str(list): continue else: if list[table.index('grade')] == '天蝎座': list.append('已毕业') else: list.append('未毕业') for col,data in enumerate(list): sheet1.write(tmp,col,data) tmp+=1 new_book.save('app_student.xls')
17、


浙公网安备 33010602011771号