您的位置:首页 > 编程语言 > Python开发

py练习

2017-09-05 23:31 363 查看
仅用于脚本练习

1 : 三级菜单
2: 购物车

3: 九九乘法表
4: 日志屏幕输出及日志输入
5: 装饰器
6: 验证码_装饰器方式
7: MD5加密
8: 计算器

1: 三级菜单
#!/usr/bin/env python
# -*- coding:utf-8 -*-
menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'Google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
}
},
'昌平':{
'沙河':{
'北航':{}
},
'天通苑':{},
'回龙观':{}
},
'朝阳':{},
'东城':{}
},
'上海':{},
'湖北':{},
'广东':{}
}
# 用于直接操作字典
curret_layer = menu
# 弄一个空列表,保存父级菜单(上一级菜单)
chiose_li=[]
while True:
# 弄一个临时空列表保存打印的字典
menu_list=[]
for nums,i in enumerate(curret_layer,1):
menu_list.append(i)
print(nums,i)
# 输入数字,并去掉空格
chiose=input('请输入序列号: ').strip()
# 判断是否是数字,如果是继续,不是显示没有并继续,B上一级,Q直接退出
if chiose.isdigit():
# 错误判断,正常就执行,错误就打印错误
try:
chiose = int(chiose)
# 保存选择的值,如1是北京,用来做为字典的查询值
address = menu_list[chiose-1]
# 判断如果这个地区不在字典里,那么应该报错
if address in curret_layer:
# 保存每一级字典的打印出来的结果
chiose_li.append(curret_layer)
# 将当前显示的值设置为二级菜单的显示结果
curret_layer = curret_layer[address]
# 清空临时列表,用于打印当前字典
menu_list.clear()
except Exception:
print('没有这个值,请重新输入')
elif chiose == 'b':
# 如果是非空那么执行它,空的就打印错误
if chiose_li:
# 保存了每列打印出来的字典,按一次b就删掉一级
curret_layer = chiose_li.pop()
else:
print("没有这个值,请重新输入")
elif chiose == 'q':
print("程序将退出。。。。")
break
else:
print("无此项")
打印结果:
1 北京
2 上海
3 湖北
4 广东
请输入序列号: 1
1 海淀
2 昌平
3 朝阳
4 东城
请输入序列号: 2
1 沙河
2 天通苑
3 回龙观
请输入序列号: 3
请输入序列号: 4
没有这个值,请重新输入
请输入序列号: b
1 沙河
2 天通苑
3 回龙观
请输入序列号: b
1 海淀
2 昌平
3 朝阳
4 东城


2. 购物车:
思路:
1、先打印出商品列,再输入一个购买商品的总额;
2、判断输入商品的总额是否为数字,如果连数字都不是那就直接退出;
3、再定义一个保存商品的空元组,然后再用一个while弄一个循环让它一直操作;

4、再判断这个元组中是否有这么多变量,如果元组中值没有那就直接判断退出或者再次输入

5、判断输入的商品额度是否小于总额,小于那就直接用总数减去购买的商品,如果成负的了,那就直接让它退出。
6、版本python3.6.1, 使用学习内容:元组,格式化字符串,列表,判断条件,while, for

#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 定义一个列表
buy_cat_list = [
("iphone7s", "7000"),
("mac book", "12000"),
("coffee", "32"),
("py book", "90"),
("bicyle", "1500"),
]
# 定义初始成本
money = input("请输入您的资金: ")

# 打印出menu
for i,v in enumerate(buy_cat_list,1):
print(i,v)
# 弄一个空元组用于保存已经选择的序列号
buy_save_list=[]

# 1、判断输入的数值是否为数字,如果是继续,不是那就退出
if money.isdigit():
money = int(money)

# 定义一个总额的初始值,用于最后减去总额得出花费多少的额度
moneys = money

while True:
# 打印出要选择序列号
buy_num = input("请输入您要选择的商品序列号,按q退出: ")

# 判断输入的是否是数值
if buy_num.isdigit():
buy_num = int(buy_num)

# 判断商品的序列号是否小于0或者大于最大的序列号,如果是那就退出
if buy_num > 0 and buy_num <= len(buy_cat_list):
print("您选择的商品是: ",buy_cat_list[buy_num - 1])

# 将buy_cat_list列表的值赋值给i_buy_cat
i_buy_cat = buy_cat_list[buy_num - 1]

# str类型无法跟int类型对比,先将i_buy_cat强制转换成int格式
if int(i_buy_cat[1]) < money:
money -= int(i_buy_cat[1])

# 将i_buy_cat的值每次都附加到buy_save_list元组中,默认每次laster
buy_save_list.append(i_buy_cat)
print("您还剩余: ",money)
else:
print("资金不足,重新输入,或者按Q退出")
else:
print("没有该商品,重新来一次或者按Q退出: ")
else:
if buy_num == "q":
print("欢迎下次光临")
msg = '''初始额度:%d - 花费的额度:%d = 商品总花费:%d''' % (moneys, money, (moneys - money))
print(msg)
print("您购买的商品如下:")
for buys in buy_save_list:
print(buys[0])
break

else:
print("参数输入错误")
else:
print("输入的序列号有误: ")
else:
print("输入错误")
输出结果如下
C:\Users\xiong\AppData\Local\Programs\Python\Python36\python.exe C:/Users/xiong/Desktop/untitled/py/day2/购物车2.py
请输入您的资金: 1000000
1 ('iphone7s', '7000')
2 ('mac book', '12000')
3 ('coffee', '32')
4 ('py book', '90')
5 ('bicyle', '1500')
请输入您要选择的商品序列号,按q退出: 1
您选择的商品是:  ('iphone7s', '7000')
您还剩余:  993000
请输入您要选择的商品序列号,按q退出: 2
您选择的商品是:  ('mac book', '12000')
您还剩余:  981000
请输入您要选择的商品序列号,按q退出: 3
您选择的商品是:  ('coffee', '32')
您还剩余:  980968
请输入您要选择的商品序列号,按q退出: q
欢迎下次光临
初始额度:1000000 - 花费的额度:980968 = 商品总花费:19032
您购买的商品如下:
iphone7s
mac book
coffee
解法2:
#/usr/bin/env python
# -*- codeing:utf-8 -*-
from functools import reduce

list=[("Iphone","5800"),
("Mac","12000"),
('Tsl','300000'),
('BMW', '300000'),]
for u in enumerate(list,1):
print(u)

money=int(input("自定义money: "))

commodig_list = []
money_list = []
while True:
commodity=input("请输入要购买的商品序列号: ")
if commodity.isdigit():
commodity=int(commodity)-1
if commodity >= len(list):
print("输入的商品不存在,请重新输入")
continue
else:
commodig_list.append(list[commodity][0])
money_list.append(int(list[commodity][1]))
print("您购买的商品列表%s"%commodig_list)
all_money = reduce(lambda x, y: x + y, money_list)
if all_money > money:
print("余额不够,程序将退出.")
break
elif commodity =="q":
print("Quit 已购买的商品 %s 总花费: %s 剩余 %s"%(commodig_list,all_money,money-all_money))
break
else:
print("非法字符")
continue
运算结果:
(1, ('Iphone', '5800'))
(2, ('Mac', '12000'))
(3, ('Tsl', '300000'))
(4, ('BMW', '300000'))
自定义money: 1000000
请输入要购买的商品序列号: 4
您购买的商品列表['BMW']
请输入要购买的商品序列号: 3
您购买的商品列表['BMW', 'Tsl']
请输入要购买的商品序列号: 2
您购买的商品列表['BMW', 'Tsl', 'Mac']
请输入要购买的商品序列号: 1
您购买的商品列表['BMW', 'Tsl', 'Mac', 'Iphone']
请输入要购买的商品序列号: q
Quit 已购买的商品 ['BMW', 'Tsl', 'Mac', 'Iphone'] 总花费: 617800 剩余 382200
3: 九九乘法表
number=1
while number<=9:
tmp = 1
while tmp<=number:
print('%s*%s=%s' % (tmp,number,tmp*number),end="\t")
# print(tmp,"*",number,"=",tmp*number,end="\t")
tmp+=1
print()
number+=1
打印结果
1 * 1 = 1
1 * 2 = 2	2 * 2 = 4
1 * 3 = 3	2 * 3 = 6	3 * 3 = 9
1 * 4 = 4	2 * 4 = 8	3 * 4 = 12	4 * 4 = 16
1 * 5 = 5	2 * 5 = 10	3 * 5 = 15	4 * 5 = 20	5 * 5 = 25
1 * 6 = 6	2 * 6 = 12	3 * 6 = 18	4 * 6 = 24	5 * 6 = 30	6 * 6 = 36
1 * 7 = 7	2 * 7 = 14	3 * 7 = 21	4 * 7 = 28	5 * 7 = 35	6 * 7 = 42	7 * 7 = 49
1 * 8 = 8	2 * 8 = 16	3 * 8 = 24	4 * 8 = 32	5 * 8 = 40	6 * 8 = 48	7 * 8 = 56	8 * 8 = 64
1 * 9 = 9	2 * 9 = 18	3 * 9 = 27	4 * 9 = 36	5 * 9 = 45	6 * 9 = 54	7 * 9 = 63	8 * 9 = 72	9 * 9 = 81
4: 日志屏幕输出及日志输入
#/usr/bin/env python
# -*- codeing:utf-8 -*-

import logging

# 设置一个空的loggin对象
logger=logging.getLogger()

# 定义日志打印格式
logger_format=logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

# 定义日志输入文件
filelog=logging.FileHandler('test.log')
# 定义日志输入文件中的日志格式
filelog.setFormatter(logger_format)

# 定义屏幕输出
fileout=logging.StreamHandler()
# 打印屏幕输出的日志格式
fileout.setFormatter(logger_format)

# 将空的对象增加文件输入的参数
logger.addHandler(filelog)

# 将空的对象增加屏幕输出的参数
logger.addHandler(fileout)

logger.setLevel(logging.DEBUG)
logging.debug('debug test')
logging.info('info test')
logging.warning('warning test')
打印结果 屏幕输出与文件输入结果一样
C:\python36\python.exe C:/Users/xiong/Desktop/py1/day6/login_mouble.py
2017-10-12 23:38:29,301 - DEBUG - debug test
2017-10-12 23:38:29,301 - INFO - info test
2017-10-12 23:38:29,301 - WARNING - warning test


5: 装饰器
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 一个装饰器程序 , home页跟shopping做认证接口
# 增加多重认证功能,如本地文件跟域控登陆

# 设置本地用户帐户密码
user,passwd = 'xiong','xiong123'

# 定义装饰器参数
def auth(auth_path):  # 这是相当于是@auth(auth_path)
# 装饰器的1层输入,  func == local或yu
def out_auth_page(func):
# 定义函数有多个参数
def page_auth(*args, **kwargs):
# 判断是本地登陆的还是yu登陆的
if auth_path == "local":
# 去掉空格,让用户输入帐户密码
Username = input("please enable Username: ").strip()
Password = input("please enable Password: ").strip()
# 认证密码
if user == Username and Password == passwd:
# 返回函数的结果
return func(*args, **kwargs)
else:
# 返回函数不相等的结果
return "login faild"
elif auth_path == "yu":
print("定义一个yu")
# 定义装饰器返回结果的对象,而不是直接返回结果
return page_auth
# 跟里层return一样
return out_auth_page

def index():
print("index page ")

@auth(auth_path="local")
def home():
print("welcome home page")

@auth(auth_path="yu")
def shopping():
print("welcome shopping page")

index()
home()
shopping()
结果:

C:\python36\python.exe C:/Users/xiong/Desktop/untitled/py/作业集合/装饰器.py
index page
please enable Username: xiong
please enable Password: xiong123
welcome home page
定义一个yu


6: 验证码_装饰器方式
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import random

def Ran(func):
def wapper(*args,**kwargs):
nums = ''
res=func(*args,**kwargs)
if res.isdigit():
for i in range(int(res)):
Rans = str(random.choice((chr(random.randint(65, 90)), chr(random.randint(97, 122)),\
random.randint(0, 9))))
nums += Rans
return nums.upper()
else:
return 'not ok'
return wapper

@Ran
def start():
inp=input('请输入验证码的长度(0 - 无穷))').strip()
return inp
while True:
x=start()
print(x)
打印结果:

请输入验证码的长度(0 - 无穷))5
HQHD6
请输入验证码的长度(0 - 无穷))     6
71ESNJ
请输入验证码的长度(0 - 无穷))
not ok
请输入验证码的长度(0 - 无穷))a
not ok
请输入验证码的长度(0 - 无穷))b
not ok
请输入验证码的长度(0 - 无穷))5a
not ok



7: MD5值加密
import hashlib,random

# 循环10次
for u in range(10):
# 保存空字符
chiose_text=''
# 这里循环是控制多少个字符串, 我这里密码只有6位,那么就写成6
for i in range(6):
# 随机挑一个大小写字母或者0到9的字符或数字
chiose=str(random.choice([random.randint(0,9),chr(random.randint(65,90)),chr(random.randint(97,122))]))
# 给它们加到一起,组成一个六位的密码串
chiose_text+=chiose
# 弄一个对象,配置成hashlib.md5格式
c=hashlib.md5()
# 更新对象密码,并且字符串弄成utf-8格式的
c.update(chiose_text.encode(encoding='utf-8'))
# 打印密码以及md5值
print("密码是:%s \t MD5值是: %s" %(chiose_text,c.hexdigest()))
# 打印结果
密码是:wcBLlo 	 MD5值是: 738922290df466b0d5ad14c9812be2ac
密码是:t76KOa 	 MD5值是: 97cb9fc69e41b8bb5a7a199338c3d0e4
密码是:ntnM2q 	 MD5值是: c650ca510e091be271930b6c0584d98c
密码是:KF4EAv 	 MD5值是: 982801a704407a77730d10eb7353ac53
密码是:uz1S5Q 	 MD5值是: a0bcc8c592078d0bd8aee5373c35fd24
密码是:fh5eC7 	 MD5值是: 6e69db2dd0b336d2c84d801dd2c7089b
密码是:fLRj6M 	 MD5值是: c269954b1af4d6d765c17ed15a9ac8b9
密码是:LCe9wA 	 MD5值是: c9b3d1aaa228c025964e201a6030575f
密码是:Mz6JAB 	 MD5值是: d6b92d926ac1c1048af50987616cfaa1
密码是:7y2uiW 	 MD5值是: aaccbfac2c9ce1f5d2c7d7aab1cda680


8: 计算器 方法一,以实现基础功能 debug一直报decoding错误,不知道怎么解决,如有解决办法,请一定告知于我 感谢哒
目前仅实现 加\减\乖\除 法。 表达式暂时不能留空



import re

aa = '1.1-2*(60-30+((40*5)*(9-10.0/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'

# 括号判断
def parentheses_judge(expression):
while True:
# 表达式处理完之后,括号里只有一个数值的去掉左右括号   任何以+-*/开头或者数字开头结尾,并数字后头没有跟随任何的+-*/
handle_remove_parentheses = re.search('\(([\+\-\*\/]*)\d+\.+\d*([^\+\-\*\/])+\)', expression)
if not handle_remove_parentheses:  # 如果同时不满足那么就退出 返回表达式
return expression

# 如果表达式满足那么就处理它并去掉括号
else:
handle_remove_parentheses = handle_remove_parentheses.group()  # 获取()的表达式 如(-8)
remove_parentheses = handle_remove_parentheses[1:-1]  # 在这里处理数值左右两边的括号( )
expression = expression.replace(handle_remove_parentheses, remove_parentheses)  # 将有括号的表达式替换成没有括号的表达式
break
return expression

# 运算符(-- ++)判断
def operator_judge(expression):
while True:
############################ 这段用来处理运算符 ##########################}
operator_dic = {'--': '+', '-+': '-', '+-': '-', ' ': '', '++': '+'}
handle_remove_operator = re.search('([\+\-\*\/]+){2}', expression)
if not handle_remove_operator:
return expression
# 如果处理运算符满足那么就处理它并重新定义运算符
else:
handle_remove_operator = handle_remove_operator.group()  # 获取运算符
# remove_operator = operator_dic[handle_remove_operator]  # 取出键值
# 替换方式  原表达式=原达式重新赋值(旧值,新值)
expression = expression.replace(handle_remove_operator, operator_dic[handle_remove_operator])
break
return expression

# 计算判断
def pd(content):
if len(content.split('*')) > 1:
Left, Right = content.split('*')
result = str(float(Left) * float(Right))
elif len(content.split('/')) > 1:
Left, Right = content.split('/')
result = str(float(Left) / float(Right))
elif len(content.split('-')) > 1:
Left, Right = content.split('-')
result = str(float(Left) - float(Right))
else:
Left, Right = content.split('+')
result = str(float(Left) + float(Right))

content = content.replace(content, result)
return content

# 乘除法判断
def div_mul(arg):
try:
content = re.search(r'\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', arg).group()
except Exception:
return arg

res=pd(content)
arg = arg.replace(content, res)

arg=parentheses_judge(arg)
arg=operator_judge(arg)

return div_mul(arg)

# 加减法判断
def plus_reduce(arg):
try:
content = re.search('\d*\.*\d*[\-\+]+\d*\.*\d*', arg).group()
except Exception:
return arg

res = pd(content)
arg = arg.replace(content, res)

arg=parentheses_judge(arg)
arg=operator_judge(arg)

return plus_reduce(arg)

# 函数调用运行
def comple(expression):
expression = div_mul(expression)                    #先计算括号内所有的乖除法
print(r'除法跟乘法的计算结果: %s' %expression)     # 打印计算出的结果

plus_velus = re.search('\([^()\*\/]+\)', expression)
if plus_velus:
plus_velus=plus_velus.group()
res= plus_reduce(plus_velus)
expression=expression.replace(plus_velus,res)
print(r'减法和加法的计算结果: %s' %expression)     # 打印计算出的结果
return comple(expression)
else:
ret=pd(expression)
print( '最后的一个结果是: %s' %ret)

if __name__ == '__main__':
print(r'代表式: %s' % aa)
comple(aa )
# 打印结果如下:
代表式: 1.1-2*(60-30+((40*5)*(9-10.0/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))
除法跟乘法的计算结果: 1.1-2*(60-30+(200.0*(9-3.3333333333333335+173134.50000000003+405.7142857142857))+12.0/(16-6.0))
减法和加法的计算结果: 1.1-2*(60-30+(200.0*173545.88095238098)+12.0/(16-6.0))
除法跟乘法的计算结果: 1.1-2*(60-30+34709176.190476194+12.0/(16-6.0))
减法和加法的计算结果: 1.1-2*(60-30+34709176.190476194+12.0/10.0)
除法跟乘法的计算结果: 1.1-2*(60-30+34709176.190476194+1.2)
减法和加法的计算结果: 1.1-2*34709207.3904762
除法跟乘法的计算结果: 1.1-69418414.7809524
最后的一个结果是: -69418413.6809524

使用eval计算结果
print(eval(' 1.1-2*(60-30+((40*5)*(9-10.0/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'))
-69418413.6809524


计算器 方法二: 只实现乖除法功能,其它未实现
首先我是使用这个方式来配置的,加减法直接给我return了,后面就将功能给它细分开了就实现功能了,如果有好的想法,请帮忙给点意见,实现这个



#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re

# expression='1-2*((60-30+(    (-40.0*5)      *(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2)))'
aa = r'1-2*((60-30+((--40/5)*(9-10.0/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2)))'

# aa='1-2*1388398.2476190478'

# 括号判断
def parentheses_judge(expression):
while True:
# 表达式处理完之后,括号里只有一个数值的去掉左右括号   任何以+-*/开头或者数字开头结尾,并数字后头没有跟随任何的+-*/
handle_remove_parentheses = re.search('\(([\+\-\*\/]*)\d+\.+\d*([^\+\-\*\/])+\)', expression)
if not handle_remove_parentheses:  # 如果同时不满足那么就退出 返回表达式
return expression

# 如果表达式满足那么就处理它并去掉括号
else:
handle_remove_parentheses = handle_remove_parentheses.group()  # 获取()的表达式 如(-8)
remove_parentheses = handle_remove_parentheses[1:-1]  # 在这里处理数值左右两边的括号( )
expression = expression.replace(handle_remove_parentheses, remove_parentheses)  # 将有括号的表达式替换成没有括号的表达式
break
return expression

# 运算符判断
def operator_judge(expression):
while True:
############################ 这段用来处理运算符 ##########################}
operator_dic = {'--': '+', '-+': '-', '+-': '-', ' ': '', '++': '+'}
handle_remove_operator = re.search('([\+\-\*\/]+){2}', expression)
if not handle_remove_operator:
return expression
# 如果处理运算符满足那么就处理它并重新定义运算符
else:
handle_remove_operator = handle_remove_operator.group()  # 获取运算符
# remove_operator = operator_dic[handle_remove_operator]  # 取出键值
# 替换方式  原表达式=原达式重新赋值(旧值,新值)
expression = expression.replace(handle_remove_operator, operator_dic[handle_remove_operator])
break
return expression

# 乘除法判断
def div_mul(arg):
inp = parentheses_judge(arg)  # 去掉括号
inp = operator_judge(inp)  # 运算符判断
try:
content = re.search('\d+\.*\d*[\*\/]+[\+\-]?\d+\.*\d*', inp).group()
except Exception:
return inp
if len(content.split('*')) > 1:
Left, Right = content.split('*')
result = str(float(Left) * float(Right))
else:
Left, Right = content.split('/')
result = str(float(Left) / float(Right))

inp = inp.replace(content, result)
return div_mul(inp)

def plus_reduce(arg):
try:
content = re.search('\d*\.*\d*[\-\+]+\d*\.*\d*', arg).group()
except Exception:
return arg
if len(content.split('-')) > 1:
Left, Right = content.split('-')
result = str(float(Left) - float(Right))
else:
Left, Right = content.split('+')
result = str(float(Left) + float(Right))

inp_new = arg.replace(content, result)
inp_new = parentheses_judge(inp_new)
return plus_reduce(inp_new)

def comple(expression):
expression = div_mul(expression)
print('除法跟乘法的计算结果: %s' % expression)

#### 在这里处理加减法的操作
try:
inp = re.search('\(([^()\/\*]+)\)', expression).group()  # 找出大括号内的数值,并递归到上个函数
except Exception:
return expression  # 如果没了,那么应该返回表达式
plus_reduce_value = plus_reduce(inp)  # 计算减法
expression = expression.replace(inp, plus_reduce_value)  # 单个数值传递,修改完返回替换再计算
expression = parentheses_judge(expression)  # 单个值的括号如(8)就直接去掉括号
print('加法跟减法的计算 : %s' % expression)
return comple(expression)

if __name__ == '__main__':
print('代表式: %s' % aa)
comple(aa)
代表式: 1-2*((60-30+((--40/5)*(9-10.0/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2)))
除法跟乘法的计算结果: 1-2*((60-30+(+8.0*(9-3.3333333333333335+173134.50000000003+405.7142857142857))+12.0/(16-6.0)))
加法跟减法的计算 : 1-2*((60-30+(+8.0*173545.88095238098)+12.0/(16-6.0)))
除法跟乘法的计算结果: 1-2*((60-30+1388367.0476190478+12.0/(16-6.0)))
加法跟减法的计算 : 1-2*((60-30+1388367.0476190478+12.0/10.0))
除法跟乘法的计算结果: 1-2*((60-30+1388367.0476190478+1.2))
加法跟减法的计算 : 1-2*1388398.2476190478
除法跟乘法的计算结果: 1-2776796.4952380955           # 就在这里加减法的正则没法查询就直接给我return了 苦恼
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python py