python练习题

计算圆的面积

#encoding=utf-8
#计算圆的面积,并且把面积打印出来,保留小数点后10位。
import math
r=int(input('请输入圆的半径:'))
x=(math.pi)*r*r
print('%0.10f'%x)

求N个数字的平均值

N=10
sum=0
count=0
print('input 10 numbers: ')
while count < N:
number = float(input())
sum = sum + number
count = count + 1
average = sum / N
print('N=%s,Sum=%s'%(N,sum))
print('average=%0.2f'%average)

 

九九乘法表

for i in range(1,10):
for j in range(1,i+1):
print('%s*%s=%s' %(i,j,i*j),end=' ')
print()

随机生成邮箱

#encoding=utf-8
import string
import random
def email(eamil_counts):#定义一个函数,用来传生成多少邮箱
emails=set()#定义一个空集合
list=['163.com','qq.com','sina.com','126.com']#定义邮箱段列表
f=0#计数器
while f < eamil_counts:#集合长度小于实参,则执行下面的代码,生成邮箱
end_email = random.choice(list) # 随机选择一个邮箱段
# 生成6-12位的随机数,返回一个list
start_email=random.sample(string.digits+string.ascii_letters+string.punctuation,random.randint(6,12))
#print(start_email)
#print(new_startemail)
start = ''.join(start_email) # 把生成的随机数连接起来变成字符串
#print(start)
new_startemail = set(start_email) # 把生成的随机数转成集合
#判断生成的有限前面的6-12位数是否同时包含大小写字母、数字、特殊符号,如果包含,则添加到集合里面。
if (new_startemail & (set(string.digits))) \
and (new_startemail & set(string.ascii_uppercase)) \
and (new_startemail & set(string.ascii_lowercase)) \
and (new_startemail & set(string.punctuation)) :#非空即真
full = start + '@' + end_email + '\n' # 拼接成邮箱
emails.add(full)#数据放到集合里
f=len(emails)#定义f为集合的长度,f每次都自动加1
with open('email.txt', 'w') as fw: # w方式打开文件,如果文件不存在则创建文件
fw.writelines(emails) # 把集合里面的数据逐行加入到文件里面
email(100)

随机生成11位不重复的手机号码,并存在文件里面。

#encoding=utf-8
import string#导入string模块
import random#导入随机数
def phone(nums):#定义一个函数,用来传入想要生成的号码数量
nums_count=set()#定义一个空集合,用来放电话号码,集合可以自动去重
list=['132','133','150','155','138','139','180','182','188','189','135']#定义号码段列表
f=0#计数器
while f < nums:#为集合的长度,如果f小于实参,则一直循环生成电话号
start=random.choice(list)#随机选择一个号码段
ends=random.sample(string.digits,8)#随机生成8为数字,返回的是列表
end=''.join(ends)#列表转成字符串
full=start+end +'\n'#拼接电话号码
nums_count.add(full)#电话号码放在集合里面,可以自动去重
f=len(nums_count)#重新定义f为集合的长度,如果f小于实参,则一直循环生成电话号
with open('phone.txt','w',encoding='utf-8') as fw:#以写入的方式打开文件,文件不存在,则会创建文件
fw.writelines(nums_count)#把集合里面的数据逐行写入到文件里面
phone(100)#调用函数,传入一个实参

判断一个小数是否是合法的小数

def is_float(s):
s=str(s)
if s.count('.')==1:
left,right=s.split('.')
if left.isdigit() and right.isdigit():
print('正小数')
return True
elif left.startswith('-') and left.count('-') == 1 and left[1:].isdigit() and right.isdigit():
print('负小数')
return True
print('不合法')
return False

双色球
# 1、写一个函数,输入N产生N条双色球号码,
# 红球 6个 01-33
# 蓝球 1个 1-16,
# 产生的双色球号码不能重复,写到一个文件里面,每一行是一条
# 红球:01 03 04 05 06 19 蓝球:16
# 红球需要升序排序
import random
import string
def nums(count):
listnum = set()
while len(listnum)<count:
redball=random.sample(range(1,34),6)#list
redball.sort()
#print(redball)
redballs=' '.join('%02d' %i for i in redball)#字符串、列表生成式
blueball = random.sample(range(1,17), 1)
blueball = ' '.join('%02d' %i for i in blueball) # 字符串
full=(redballs + ' '+ blueball+'\n')
listnum.add(full)
print(listnum)
with open('double_ball.txt', 'w', encoding='utf-8') as fw: # 以写入的方式打开文件,文件不存在,则会创建文件
fw.writelines(listnum) # 把集合里面的数据逐行写入到文件里面
nums(100)


商品管理
# 2、写一个商品管理的程序
# 1 添加商品 商品名称:商品已经存在的话,要提示
# 商品价格: 校验,是大于0的数字
# 商品数量:校验,只能是大于0的整数
# 2 删除商品 商品名称:商品不存在的话,要提示
# 3 查看商品 for循环 显示所有的商品信息
# 4 退出
import json
products='test.json'
#读文件
def read_product(filename):
f=open(filename,encoding='utf-8')
content=json.load(f)#json转成字典
#print(content)
return content

#写入文件
def write_file(dic):
fw = open('test.json', 'w', encoding='utf-8')
json.dump(dic, fw, indent=4, ensure_ascii=False)
fw.close()

#校验价格
def is_price(s):
s = str(s)
if s.count('.') == 1:
left, right = s.split('.')
if left.isdigit() and right.isdigit():
#print('正小数')
return True
elif left.startswith('-') and left.count('-') == 1 and left[1:].isdigit() and right.isdigit():
print('价格不能为负小数')
return False
elif s.isdigit():
s = int(s)
if s == 0:
print('价格不能为0')
return False
else:
#print('正数')
return True
else:
print('价格不能为负数或者字母或者符号')
return False
print('价格不能为负数或者字母或者符号')
return False

#校验数量
def is_counts(c):
c = str(c)
if c.isdigit():
c = int(c)
if c == 0:
print('数量不能为0')
return False
else:
#print('正数')
return True
else:
print('数量只能是大于0的正整数')
return False

#添加商品
def add_product():
product_dict=read_product(products)#读文件 字典格式
print(product_dict)
name=input('请输入商品名称: ').strip()
price=input('请输入商品价格:').strip()
count=input('请输入商品数量: ').strip()
if name!='' and price!='' and count!='':
if name in product_dict:
print('商品已经存在')
elif not is_price(price):
print('商品价格有误')
elif not is_counts(count):
pass
#print('商品数量有误')
else:
product_dict[name]={"price":price,"count":count}
write_file(product_dict)
print('添加成功')
else:
print('商品、价格、数量不能为空')

#删除商品
def del_product():
product_dict=read_product(products)#读文件
del_name=input('请输入要删除商品的名称: ').strip()
if del_name!='':
if product_dict.get(del_name) :
product_dict.pop(del_name)
write_file(product_dict)
print('删除成功')
else:
print('商品名称不存在')
else:
print('商品名称不能为空')

#查看商品
def show_product():
product_dict = read_product(products)
for key in product_dict:
print(key,product_dict[key])

#退出
def quit_sys():
message=input('输入q退出程序: ')
if 'q':
exit

choice = input('1、add_product\n'
'2、del_product\n'
'3、show_product \n'
'4、quit_sys \n')
func_map = {"1":add_product,"2":del_product,"3":show_product,"4":quit_sys}
if choice in func_map:
func_map[choice]()#函数调用
else:
print('输入有误!')

每分钟监控服务器日志,IP请求超过200次的,加入黑名单
import time
point=0
while True:
with open('access.log',encoding='utf-8') as fw:
ips = {}
fw.seek(point)
for line in fw.readlines():
#print(line)
ip=line.split()[0]
#print(ip)
if ip not in ips:
ips[ip]=1
else:
ips[ip]+=1
point=fw.tell()
for k,count in ips.items():
if count>200:
print('%s加入黑名单'%k)
time.sleep(60)

#、 写一个函数,传入一个路径和一个关键字(关键字是文件内容),找到文件内容里面有这个关键字的txt文件

# 1、去找到这个目录下面的所有.txt文件
# 2、循环打开所有的txt文件,读到文件内容
# 3、判断关键字是否存在文件里面
import os

def find_content(path,key_word):
for cur_path,dirs,files in os.walk(path):
for file in files:
if file.endswith('log'):
print(file)
abs_file_path = os.path.join(cur_path,file)
res = open(abs_file_path,encoding='utf-8').read()
if key_word in res:
print('文件内容在',abs_file_path)

#2、删除3天前的日志文件
#1、要获取到所有的日志文件 os.walk()
#2、先获取到文件的时间
#3、要判断文件的日期是否在三天前 当天的日期的时间戳 - 60*60*24*3
import time
def timestampToStr(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
#时间戳转格式化好的时间
if timestamp:
time1 = time.localtime(timestamp)
res = time.strftime(format, time1)
else:
res = time.strftime(format)
return res
#20180304153958
def strTotimestamp(str=None,format='%Y%m%d%H%M%S'):
#格式化的时间转时间戳
if str:
timep = time.strptime(str, format)
res = time.mktime(timep)
else:
res = time.time()
return int(res)

def clean_log(path,day=3):
for cur_path, dirs, files in os.walk(path):
for file in files:
if file.endswith('log'):
f_time = file.split('.')[0].split('_')[-1]
file_timestamp = strTotimestamp(f_time,'%Y-%m-%d')
cur_timestamp = strTotimestamp(time.strftime('%Y-%m-%d'),'%Y-%m-%d')
if (cur_timestamp - file_timestamp) >= 60*60*24*day:#判断文件的时间是否大于3天
os.remove(os.path.join(cur_path,file)

 3、写一个注册的功能,要求数据存在数据库里面

        1、名字为空、已经存在都要校验

        2、校验通过之后,密码要存成密文的。

import pymysql
def my_db(sql):
conn = pymysql.connect(host='ip',user='jxz',password='123456',
db='jxz',port=3306,charset='utf8',autocommit=True)
cur = conn.cursor(pymysql.cursors.DictCursor)
cur.execute(sql)
res = cur.fetchone() #{'username':'nhy'} {}
cur.close()
conn.close()
return res
import hashlib
def my_md5(s,salt=''):
s = s+salt
news = str(s).encode()
m = hashlib.md5(news)
return m.hexdigest()

def reg():
for i in range(3):
user =input('username:').strip().upper()
pd = input('password:').strip()
cpd = input('cpwd:').strip()
sql='select username from app_myuser where username = "%s";'%user
if len(user) not in range(6,11) or len(pd) not in range(6,11): # 6 7 8 9 10
print('账号/密码长度错误,6-10位之间')
elif pd != cpd:
print('两次输入密码不一致')
elif my_db(sql):
print('用户已存在')
else:
md5_passwd = my_md5(pd)
insert_sql= 'insert into app_myuser (username,passwd,is_admin) value ("%s","%s",1);'%(
user,md5_passwd
)
my_db(insert_sql)
print('注册成功!')
break
else:
print('失败次数过多!')

 4、登陆的功能

        登录的账号密码从数据库里面取,

        如果输入用户不存在要提示

import pymysql
def my_db(sql):
conn = pymysql.connect(host='ip',user='jxz',password='123456',
db='jxz',port=3306,charset='utf8',autocommit=True)
cur = conn.cursor(pymysql.cursors.DictCursor)
cur.execute(sql)
res = cur.fetchone() #{'username':'nhy'} {}
cur.close()
conn.close()
return res
import hashlib
def my_md5(s,salt=''):
s = s+salt
news = str(s).encode()
m = hashlib.md5(news)
return m.hexdigest()

def login():
for i in range(3):
username = input('请输入用户名:').strip().upper()
password = input('请输入密码:').strip()
sql='select username,passwd from app_myuser where username = "%s";'%username
if username =='' or password =='':
print('账号/密码不能为空')
else:
res = my_db(sql) # {'username':nhy 'passwd':'xxxxx'}
if res:
if my_md5(password) == res.get('passwd'):
print('登陆成功!')
break
else:
print('密码错误!')
else:
print('用户不存在')

else:
print('错误次数过多!')
 

把金牛座.xls中的汉字人名转成用户名,写到后面的单元格中,excel在群文件

        例如:网络-安求凤 : wl_anqiufeng

                   现场-杨帆 : xc_yangfan

                  蹭课-张哲: ck_zhangzhe

import xpinyin
import xlrd
import string
from xlutils import copy
book=xlrd.open_workbook('金牛座.xls')
sheet=book.sheet_by_index(0)
p=xpinyin.Pinyin()
new_book = copy.copy(book)
new_sheet = new_book.get_sheet(0)
for i in range (1,sheet.nrows):#sheet.ncols代表总共有多少行
name=sheet.row_values(i)[0]
name_pinyin=p.get_pinyin(name,"")
name_pinyin=name_pinyin.replace('wangluo','wl').replace('xianchang','xc').replace('cengke','ck')
for n in name_pinyin:
if n not in string.ascii_lowercase:#判断如果不是字母的话,就替换
res=name_pinyin.replace(n,'_')
xhx_count=res.count('_')#取下划线的个数
if xhx_count>1:#判断如果下划线大于1,就把多个下划线替换为一个下划线
res=res.replace('_'*xhx_count,'_')
new_sheet.write(i,1,res)
new_book.save('金牛座.xls')

下载图片
import threading
import requests
import time
from hashlib import md5
res = []
def down_load_pic(url):
#下载图片的url
r = requests.get(url)
file_name = md5(r.content).hexdigest()#把文件md5之后字符串当做文件名
with open(file_name+'.jpg','wb') as fw:
fw.write(r.content)
print('%s下载完成'%file_name)
res.append(file_name)

urls = [
'http://www.nnzhp.cn/wp-content/uploads/2018/12/110405th7jtus7gjjlywnl.jpg',
'http://www.nnzhp.cn/wp-content/themes/QQ/images/thumbnail.png',
'http://www.nnzhp.cn/wp-content/uploads/2018/08/f38a12137574f4333f7686f7e75a06fb8bd9fed537ea59-pRwNuK_fw658.jpeg',
'http://www.nnzhp.cn/wp-content/uploads/2018/08/c1bba9a47cfe8fe7000f137f020ad623.png',
]
start_time = time.time()
#单线程
# for url in urls:
# down_load_pic(url)

#多线程
for url in urls:
t = threading.Thread(target=down_load_pic,args=(url,) )
t.start()
while threading.active_count()!=1:#等待子线程运行完成
pass
print(res)
end_time = time.time()
print('下载完成,下载时间是 %s'% (end_time-start_time))


判断一个IP是否是合法的IP地址
 

 



 
 
 
posted @ 2018-11-29 16:36  会飞的狗子  阅读(699)  评论(0编辑  收藏  举报