python作业练习
#1、猜字游戏
用if分支完成猜数字游戏
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。 -- 先通过键盘输入一个数字算作出题
-- 在键盘输入答案
-- 正确:猜对 | 误差3以内:接近了 | 误差外小值:太小 | 误差外大值:太大

queste=int(input('请输入数字》:')) #答案 enu=int(input('请输入答案》:')) #作答 erro_value=3 #误差值 if enu == queste: print('恭喜你猜对了') elif abs(enu - queste ) < 3 : print('接近了') elif (enu-queste) <= -3: print('误差太小') else: print('误差太大')View Code
#2、循环完成多次猜字游戏
-- 一次循环完成一次出题和猜题
-- 当出题输入Q或q时结束游戏

queste=input('请输入数字(输入Q或者q退出猜字)》:') #答案 erro_value = 3 # 误差值 while True: if queste == 'Q' or queste == 'q':break #优化写法 #if queste in ['Q','q']:break queste = int(queste) enu = input('请输入答案》:') # 作答 enu=int(enu) if enu == queste: print('恭喜你猜对了') break elif abs(enu - queste) < 3: print('接近了') elif (enu - queste) <= -3: print('误差太小') else: print('误差太大')View Code
#3、继续优化猜字游戏
-------完成一次出题可以最多进行三次猜题
------- 一次出题,进入猜题,猜对进入下一次出题
------- 猜错进入下一次猜题,最多错三次,三次全错自动进入下一次出题

erro_value = 3 # 误差值 while True : queste = input('请输入数字(输入Q或者q退出猜字)》:') # 答案 if queste == 'Q' or queste == 'q': break queste=int(queste) count = 0 while count <3: enu = int(input('请输入答案》:')) # 作答 if enu == queste: print('恭喜你猜对了') break elif abs(enu - queste) < 3: print('接近了') count+=1 continue elif (enu-queste) <= -3: print('误差太小') count+=1 continue else: print('误差太大') count += 1 continueView Code
#4、循环输入10条信息,如果输入的是自然数,就存放到名为nums的列表中,如果不是,就存放到名为strs列表中
-- nums中存放的数据都是int类型
-- strs中存放的都是字符串类型
-- 最终打印两个列表以及个列表的中元素的个数

nums = [] # 存放str的list strs = [] # 循环10次 for i in range(10): info = input('info:') # 如果是自然数,转换成整型存放到nums列表汇总 if info.isdigit(): num = int(info) nums.append(num) else: # 不是自然数,就直接存储字符串数据 strs.append(info) print(nums, len(nums)) print(strs, len(strs))View Code
#5、完成用list存放注册用户信息的功能:可以循环来完成注册,先输入账号,再输入密码,密码需要二次确认,两次密码一致才能往下进行注册,如果不一致返回重新注册输入
-- 账号输入Q或q,退出整个程序
-- 账号成功,进行两次密码验证,验证失败直接进入下一次注册
-- 账号必须全部是英文字母3个长度及以上,密码必须是英文或数字3个长度及以上
-- 两次密码验证成功,就注册信息存放到列表中
-- 假设注册成功了Owen,123 | Zero,000两个信息,最终形成的注册结果为
[['Owen', '123'], ['Zero', '000']]

# 存放数字的list # 存放注册信息的列表 user_info = [] # 用来循环注册 while True: # 账号 usr = input('usr: ') if usr == 'Q' or usr == 'q': break # 账号不合法,直接进入下一次注册循环 if not (usr.isalpha() and len(usr) >= 3): print('账号不合法,重新输入') continue # 账号合法,循环再输入密码,确保密码合法 while True: pwd = input('pwd: ') # 密码不合法,直接进入下一次密码输入循环 if not (pwd.isalnum() and len(pwd) >= 3): print('密码不合法,重新输入密码') continue re_pwd = input('re_pwd: ') if pwd != re_pwd: print('两次密码不一致,重新输入密码') continue # 走到这代表密码已合法,可以结束密码输入的循环 break # 安装指定格式添加到容器里 user_info.append([usr, pwd]) print('注册成功!') # 当注册重新退出时,就可以打印所有结果 print(user_info)View Code
#6、将几个指定字符串形成目标字符串
指定字符串:'I' | 'am' | 'you are a good boy' | '!'
目标字符串:'I am a good boy!'

# res = "%s %s %s%s" % ('I', 'am', 'you are a good boy'[8:], '!') # print(res)View Code
#7、写出你可以想到的所有按要求格式输出列表的解决方案
指定列表:[1, 2, 3, 4, 5]
输出结果:[5, 4, 3, 2, 1]

alist=[1,2,3,4,5] #方法一:使用切片技术 new_alist=alist[::-1] print(new_alist) #方法二:使用reversed函数,返回结果是一个反转的迭代器,需要list进行转换 new_alist1=list(reversed(alist)) print(new_alist1) #方法三:使用sorted函数,排序后生产一个新的列表,reverse等于True,则反转,默认是False new_alist2=sorted(alist,reverse=True) print(new_alist2) #方法四 # ls.sort(reverse=True) # print(ls)View Code
#8、遍历删除包含 Bi词汇(脏话) 的目标
指定列表:['Owen', 'BobSB', 'SBen', 'ZeroS', 'OSBO']
输出结果:['Owen', 'ZeroS']

source = ['Owen', 'BobSB', 'SBen', 'ZeroS', 'OSBO'] res = [] for i in source: if 'SB' in i: # source.remove(i) continue res.append(i) source = res print(source)View Code
#9、求得指定元组中是字符串数据的总个数
指定元组:(1, 2, '3', '4', 5, '6', 7, 8, 9)
求的结果:3

t1=(1, 2, '3', '4', 5, '6', 7, 8, 9) count=0 for i in t1: if isinstance(i,str): count+=1 print(count)View Code
#10、求得指定元组中 str数据的个数 与 int数据的个数,存储到字典存放
指定元组:(1, 2, '3', '4', 5, '6', 7, 8, 9)
求的结果:{'str': 3, 'int': 6}

c1 = 0 c2 = 0 for v in (1, 2, '3', '4', 5, '6', 7, 8, 9): if isinstance(v, str): c1 += 1 elif isinstance(v, int): c2 += 1 res = {'str': c1, 'int': c2} res = {}.fromkeys(['str', 'int'], 0) for v in (1, 2, '3', '4', 5, '6', 7, 8, 9): if isinstance(v, str): res['str'] += 1 elif isinstance(v, int): res['int'] += 1 print(res)View Code
#11、列表数据的去重
指定列表:[3, 1, 2, 2, 1, 5, 9, 7]
求的结果:[3, 1, 2, 5, 9, 7]

#方法一: l=[3, 1, 2, 2, 1, 5, 9, 7] alist=set(l) alist=list(alist) print(alist) #方法二: l=[3, 1, 2, 2, 1, 5, 9, 7] alist=[] for i in l: if i not in alist: alist.append(i) print(alist)View Code
#12、修改所有以 Bi词汇(脏话) 开头或结尾的字符串,将 Bi词汇 替换为**
指定列表:['Owen', 'BobSB', 'SBen', 'ZeroS', 'OSBO']
运行结果:['Owen', 'Bob**', '**en', 'ZeroS', 'OSBO']

source = ['Owen', 'BobSB', 'SBen', 'ZeroS', 'OSBO'] for v in source: if v.startswith('SB') or v.endswith('SB'): index = source.index(v) source[index] = source[index].replace('SB', '**') print(source)View Code
#13、判断实现将所有能转换为数字类型的字符串都转换为对应类型的数字
int: '10'=>10 | '-10'=>-10
float: '0.1'=>0.1 | '-0.1'=>-0.1 | '.1'=>0.1 | '-.1'=>-0.1

# 整数 num = '+10' if num.strip().isdigit(): print('int: ', int(num)) if num[0] in ['-', '+'] and num[1:].isdigit(): # '-10' print('int: ', int(num)) if num.isdigit(): # '10' print('int: ', int(num)) # num = '-0.1' # nums = num.split('.') # if len(nums) == 2 and nums[0].isdigit() and nums[1].isdigit(): # 0.1 # print('float: ', float(num)) # if len(nums) == 2 and nums[0] == '' and nums[1].isdigit(): # .1 # print('float: ', float(num)) # # # nums = ["+-0", "1"] # if len(nums) == 2 and nums[0][0] in ['-', '+'] and nums[0][1:].isdigit() and nums[1].isdigit(): # +-0.1 # print('float: ', float(num)) # 小数 num = '1.0+5' temp_num = num.replace('.', '0', 1) if num.startswith('+'): temp_num = temp_num.replace('+', '0', 1) elif num.startswith('-'): temp_num = temp_num.replace('-', '0', 1) if temp_num.isdigit(): print('float: ', float(num))View Code
#14、将以下数据存储为字典类型
数据:info = "name:Owen|age:18|gender:男"
结果:{'name': 'Owen', 'age': 18, 'gender': '男'}
注:年龄存储为int类型

info = "name:Owen|age:18|gender:男" dic = {} for k_v in info.split('|'): k, v = k_v.split(':') if v.isdigit(): v = int(v) dic[k] = v print(dic)View Code
#15、完成上一道题的逆运算,将字典重新转换成字符串

dic = {'name': 'Owen', 'age': 18, 'gender': '男'} #方法一 # ls = [] # for k, v in dic.items(): # ls.append('%s:%s' % (k, v)) # print('|'.join(ls)) #方法二 info = '' for k, v in dic.items(): if isinstance(v, int): v = str(v) info += k + ':' + v + '|' info = info[:-1] print(info)View Code
#16、将字典数据转换为目标list
原数据:dic = {'name': 'Owen', 'age': 18, 'gender': '男'}
处理后:info = [('name', 'Owen'), ('age', 18), ('gender', '男')]

dic = {'name': 'Owen', 'age': 18, 'gender': '男'} info = [('name', 'Owen'), ('age', 18), ('gender', '男')] # print(list(dic.items())) # print(dict(info)) ls = [] for k, v in dic.items(): ls.append((k, v)) print(ls)View Code
#17、完成100以内的大写汉字转换为对应的阿拉伯数字
可能的区间划分:
一个汉字的 - 壹~拾
二个汉字拾开头 - 拾壹~拾玖
二个汉字拾结尾 - 贰拾|叁拾|...|玖拾
三个字的

num_map = { "壹": 1, "贰": 2, "叁": 3, "肆": 4, "伍": 5, "陆": 6, "柒": 7, "捌": 8, "玖": 9, "拾": 10, } info = '玖拾陆' if len(info) == 1 and info in num_map: print(num_map[info]) if len(info) == 2 and info.startswith('拾') and info[1] in num_map and info[1] != '拾': b = info[1] res = 10 + num_map[b] print(res) if len(info) == 2 and info.endswith('拾') and info[0] in num_map and info[0] != '拾': a = info[0] res = num_map[a] * 10 print(res) if len(info) == 3: a = info[0] b = info[1] c = info[2] res_a = a in num_map and a != '拾' res_b = b == '拾' res_c = c in num_map and c != '拾' if res_a and res_b and res_c: res = num_map[a] * 10 + num_map[c] print(res)View Code
#18、完成元组的去重操作,操作后得到的还是元组类型
指定列表:(3, 1, 2, 2, 1, 5, 9, 7)
要求有序、无序两种操作方式下的去重

t = (3, 1, 2, 2, 1, 5, 9, 7) print(tuple(set(t))) ls = [] for v in t: if v not in ls: ls.append(v) print(tuple(ls))View Code
#19、完成对数据的格式化
原数据:[1, 3, 2, 9, 12, 23]
运行结果:['奇数', '奇数', '偶数', '奇数', '偶数','奇数']

ll = [1, 3, 2, 9, 12, 23] # ls = ['奇数' if v % 2 != 0 else '偶数' for v in ll] # print(ls) ls = [] for v in ll: if v % 2 != 0: ls.append('奇数') else: ls.append('偶数') print(ls)View Code
#20、完成数据格式的个数记录
原数据:[1, 3, 2, 9, 12, 23]
运行结果:{'奇数': 4, '偶数': 2}

dic = {} for v in ll: if v % 2 != 0: dic.setdefault('奇数', 0) dic['奇数'] += 1 else: dic.setdefault('偶数', 0) dic['偶数'] += 1 print(dic)View Code
#21、打印
"今天天气真好" utf-8编码下的二进制字符串
b'\xe5\x85\xab\xe6\x9c\x9f\xe6\x97\xa0\xe6\x95\x8c' tf-8编码下的普通字符串

s='今天天气真好' print(s.encode('utf-8'))#编码 存操作 将普通字符串转为二进制字符串 ##b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\xa4\xa9\xe6\xb0\x94\xe7\x9c\x9f\xe5\xa5\xbd' res=b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\xa4\xa9\xe6\xb0\x94\xe7\x9c\x9f\xe5\xa5\xbd' print(res.decode('utf-8'))#解码 读操作 将二进制字符串转为普通字符 ##八期无敌View Code
#22、
综合题:完成录入电话本-- 从键盘中录入姓名(不区分大小写):
-- 姓名必须是全英文组成,不是则重新录入姓名,如果是q,代表退出
-- 从键盘中再录入电话:
-- 电话必须为数字且长度必须是11位(不能转换为数字)
-- 如果出现姓名相同,则保留最后一次电话号码
-- 形成的数据是有电话分组的,如:第一次录入Owen,13355667788,则会形成
-- {
'O': {
'Owen': '13355667788'
}
} 最终数据,分组名一定大写:
{
'E': {
'egon': '17788990000',
'engo': '16633445566'
},
'O': {
'Owen': '13355667788'
}
}

phone_dic = { } while True: name = input('name: ').strip().lower() if name == 'q': break if not name.isalpha(): continue while True: phone = input('phone: ').strip().lower() if not (phone.isdigit() and len(phone) == 11): continue # 分组名: group = name[0].upper() # phone_dic[group] = {} phone_dic.setdefault(group, {}) phone_dic[group][name] = phone # 一次录入成功 print('录入成功') break print(phone_dic)View Code
