- 验证随机验证码:
1 def check_code(): 2 import random 3 checkcode = '' 4 for i in range(4): 5 current = random.randrange(0,4) 6 if current != i: 7 temp = chr(random.randint(65,90)) 8 else: 9 temp = random.randint(0,9) 10 checkcode += str(temp) 11 return checkcode 12 while True: 13 code = check_code() 14 print(code) 15 v = input('>>>') 16 if v.lower() == code.lower(): 17 print('输入正确!') 18 break 19 else: 20 continue
- 替换敏感词汇:
1 a = '老师' 2 b = '学生' 3 content = input('请输入内容:') 4 if content == a or content == b: 5 content = a.replace('老师','**') 6 content = b.replace('学生','**') 7 print(content)
- 根据用户输入内容制作表格: (!!! 例子中如果输入的是中文,所占用的位数比英文的位数要长,导致对位不整齐,留后期解决)
1 content = '账户 密码 邮箱 ' 2 while True: 3 name = input('请输入用户名:') 4 if name.lower() == 'q': 5 break 6 password = input('请输入密码:') 7 email = input('请输入邮箱:') 8 form = '{0} {1} {2} ' 9 v = form.format(name.title(),password,email) 10 content = content + v 11 print(content.expandtabs(20)) 12 13 输出: 14 账户 密码 邮箱 15 Jack 123 jack@163.com 16 Alen 456 alen@163.com 17 Tom 789 tom@163.com
- 九九乘法表:先取i为1,进入内循环,循环所有内容后返回上一层循环,继续内循环。当 i=2,v=1,2,3;i=3,v=1,2,3,4每次一轮循环结束后输出值,print默认换行处理。
1 例: 2 for i in range(1,10): 3 count = '' 4 for v in range(1,i+1): 5 count += str(v) + '*' + str(i) + '='+ str(i*v) + ' ' 6 print(count) 7 8 输出: 9 1*1=1 # 第一次循环结束; 10 1*2=2 2*2=4 # 第二次循环结束; 11 1*3=3 2*3=6 3*3=9 12 1*4=4 2*4=8 3*4=12 4*4=16 13 1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 14 1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 15 1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 16 1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 17 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
-
简单的购物车:(输入总资产,显示商品列表,根据序号选择商品进行购买,如果购买总额大于总资产,提示账户余额不足,否则成功购买。不考虑金额有小数位。 是否继续购买在输入非'yes/no'的值时暂未做处理。)
1 total = input('请输入总资产:') 2 while not total.isdigit(): 3 total = input('输入有误,请输入正确的金额:') 4 total = int(total) 5 goods = [ 6 {'name':'电脑','price':1999}, 7 {'name':'鼠标','price':10}, 8 {'name':'键盘','price':20}, 9 {'name':'音箱','price':998}, 10 ] 11 # 索引:goods[0]['name']=电脑,goods[0]['price']=1999; 12 print('欢迎进入本店:') 13 while True: 14 #先制作产品表格; 15 16 print('商品类型'.center(50,'*')) 17 print('编号'.ljust(8,' '),'品类'.center(30,' '),'价格'.rjust(8,' ')) 18 #使用enumerate方法,进行for循环goods列表; 19 for x,y in enumerate(goods,1): 20 # 索引获取goods列表中的值,后可加参数表示开始的编号。x为编号,赋予1开始,y为goods。 21 print(str(x).ljust(8,' '),str(y['name']).center(34,' '),str(y['price']).rjust(8,' ')) 22 i = input('请根据序号选择商品:') 23 if i.lower() == 'q': 24 print('欢迎下次光临!') 25 break 26 #判断输入的值是否为数字。 27 while not i.isdigit() or int(i) > len(goods): 28 i = input('请输入有效编号:') 29 #总额大于购买物品的金额的情况,后面的值表示用'i'的取值来索引到金额的值;'z'表余额; 30 if int(total) >= int(goods[int(i) - 1]['price']): 31 z = int(total) - int(goods[int(i) - 1]['price']) 32 total = int(z) 33 print('购买成功,剩余金额为:' + str(z) + '元。') 34 a = input('是否继续购买(yes/no):') 35 if a == 'yes': 36 continue 37 else: 38 print('谢谢购买,欢迎下次光临!') 39 break 40 else: 41 z = int(total) 42 print('余额不足,无法购买此商品,剩余余额为' + str(z) + '元。') 43 b = input('是否退出(yes/no):') 44 if b == 'yes': 45 print('谢谢购买,欢迎下次光临!') 46 break 47 else: 48 continue
-
求某个元素在字符串中出现的位置
1 def index_words(text): #将‘jack is a boy.’替入text中 2 result = [] 3 if text: #返回0后,result = [0] 4 result.append(0) 5 for index,letter in enumerate(text,1): #index 取编号‘1’开始,letter取text中的值。两者形成对应关系,进行循环取值 6 if letter == 'a': #当letter为a时,将所对应的index值添加到result列表中 7 result.append(index) 8 return result 9 10 print(index_words('jack is a boy.')) 11 12 输出: 13 [0, 2, 9]
1 #使用生成器函数: 2 def index_words(text): 3 if text: 4 yield 0 5 for index,letter in enumerate(text,1): 6 if letter == 'a': 7 yield index 8 9 count = index_words('jack is a boy.') 10 print(count.__next__()) 11 print(count.__next__()) 12 print(count.__next__())
- 以字典方式统计字符串的各种大小写有多少个
1 #统计字符串中有多少个大写。小写字母或数字跟其它字符,以字典形式返回 2 def count(test): 3 upper = 0 4 lower = 0 5 digit = 0 6 other = 0 7 dic = {} 8 for i in test: 9 if i.isupper(): 10 upper += 1 11 if i.islower(): 12 lower += 1 13 if i.isdigit(): 14 digit += 1 15 if not i.isalnum(): 16 other += 1 17 #字典默认时的参数 18 dic.setdefault('大写字母',upper) 19 dic.setdefault('小写字母',lower) 20 dic.setdefault('数字', digit) 21 dic.setdefault('其它',other) 22 return dic 23 test = 'Jack ID is 012345' 24 print(count(test)) 25 26 输出: 27 {'大写字母': 3, '小写字母': 5, '数字': 6, '其它': 3}
- 杨辉三角
1 # 杨辉三角 2 # _*_ coding: utf-8 _*_ 3 def triangles(): 4 s = [1] 5 while True: 6 yield s #得到s的值再进行下一行的生成器操作 7 s =[1] + [s[n] + s[n-1] for n in range(1,len(s))] + [1] 8 #利用列表生成器,根据行数的不同将每一行的前后两个值进行相加 9 n = 0 10 for i in triangles(): 11 print(i) 12 n = n + 1 13 if n == 10: 14 break
- 获取用户输入的日期和时间如
2015-1-21 9:01:30
,以及一个时区信息如UTC+5:00
,均是str
,编写一个函数将其转换为timestamp:1 import re 2 from datetime import datetime, timezone, timedelta 3 def to_timestamp(dt_str, tz_str): 4 # 先转换时间:H = int(re.split(r'[C:]',tz_str)[1]) 使用正则表达式的切分取值 5 # 时区:zone =timezone(timedelta(hours=H)) 6 # 设置dt的UTC时间:dt.replace(tzinfo=zone) 7 dt = datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S') #先将str转为datetime; 8 tz = dt.replace(tzinfo=timezone(timedelta(hours=int(re.split(r'[C:]', tz_str)[1])))).timestamp() 9 return tz 10 11 # 测试: 12 t1 = to_timestamp('2015-6-1 08:10:30', 'UTC+7:00') 13 assert t1 == 1433121030.0, t1 14 15 t2 = to_timestamp('2015-5-31 16:10:30', 'UTC-09:00') 16 assert t2 == 1433121030.0, t2 17 18 print('ok')
- 根据用户输入的登录名和口令模拟用户注册,计算更安全的MD5,(登录名作为Salt的一部分来计算MD5,从而实现相同口令的用户也存储不同的MD5)
1 db = {} 2 def register(username, password): 3 db[username] = get_md5(password + username + 'the-Salt')
1 #Hmac算法,得到更安全的口令(比Salt更好) 2 h = hmac.new(key, message, digestmod='MD5').hexdigest()
1 # -*- coding: utf-8 -*- 2 import hmac, random 3 4 def hmac_md5(key, s): 5 return hmac.new(key.encode('utf-8'), s.encode('utf-8'), 'MD5').hexdigest() 6 7 class User(object): 8 def __init__(self, username, password): 9 self.username = username 10 self.key = ''.join([chr(random.randint(48, 122)) for i in range(20)]) 11 self.password = hmac_md5(self.key, password) 12 13 db = { 14 'michael': User('michael', '123456'), 15 'bob': User('bob', 'abc999'), 16 'alice': User('alice', 'alice2008') 17 } 18 19 def login(username, password): 20 user = db[username] 21 return user.password == hmac_md5(user.key, password) 22 # 测试: 23 assert login('michael', '123456') 24 assert login('bob', 'abc999') 25 assert login('alice', 'alice2008') 26 assert not login('michael', '1234567') 27 assert not login('bob', '123456') 28 assert not login('alice', 'Alice2008') 29 print('ok')