python习题,关于函数的练习01
习题1
写函数,检查获取传入列表或者元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者.
def check_elements(obj):
if isinstance(obj, (tuple, list)):
list1 = []
for index in range(1, len(obj), 2):
list1.append(obj[index])
return list1
return '输入非法,应为元组或者列表类型!'
print(check_elements({3: 5, 4: 6})) # 输入非法,应为元组或者列表类型!
print(check_elements([3, 5, 7, 2, 4, 6])) # [5, 2, 6]
print(check_elements((3, 5, 7, 2, 4, 6))) # [5, 2, 6]
习题2
写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5.
def is_greater_than(obj):
if isinstance(obj, (str, list, tuple)):
if len(obj) > 5:
return True
return False
return '输入非法,应为字符串、列表、元组类型!'
print(is_greater_than([1, 2, 3, 7, 4, 5, 6, 7])) # True
print(is_greater_than((1, 2, 3, 7))) # False
print(is_greater_than(('abcdefg'))) # True
习题3
写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者.
def is_greater_than(obj: list):
if isinstance(obj, list):
if len(obj) > 2:
return obj[:2]
return obj
return '输入非法,应为列表类型!'
print(is_greater_than([1])) # [1]
print(is_greater_than([1, 2, 3, 7, 4, 5, 6, 7])) # [1, 2]
print(is_greater_than(('abcd'))) # 输入非法,应为列表类型!
习题4
写函数,计算传入函数的字符串中[数字]、[字母]以及[其他]的个数,并返回结果.
def my_count(s: str):
if isinstance(s, str):
x = y = z = 0
for i in s:
if i.isdecimal():
x += 1
elif i.isalpha():
y += 1
else:
z += 1
return f'数字:{x},字母:{y},其他:{z}'
return '非法参数,应为字符串类型'
print(my_count([3, 4, 5])) # 非法参数,应为字符串类型
print(my_count('13hello56wo!!@#@')) ## 数字:4,字母:7,其他:5
习题5
写函数,接收两个数字参数,返回比较大的数字.
def my_max(a: int, b: int):
if isinstance(a, int) and isinstance(b, int):
return a if a > b else b
return '非法参数,应都为整数类型!'
print(my_max('name', 18)) # 非法参数,应都为整数类型!
print(my_max(66, 21)) # 66
print(my_max(15, 21)) # 21
习题6
写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者.
from collections.abc import Iterable
def my_dict(dict1: dict):
if isinstance(dict1, dict):
rusult = []
for value in dict1.values():
if isinstance(value, Iterable):
if len(value) > 2:
rusult.append(value[:2])
return rusult
return '非法参数,应为字典类型!'
print(my_dict([33, 44, 55])) # 非法参数,应为字典类型!
print(my_dict({'a': '333', 'b': 'book', 'c': 666})) # ['33', 'bo']
习题7
写函数,此函数只接收一个参数且此参数必须是列表数据类型,此函数完成的功能是返回给调用者一个字典,此字典的键值对为此列表的索引及对应的元素.
例如:
传入列表[11, 22, 33]
返回字典{0: 11, 1: 22, 2: 33}
def my_trans(lst: list):
if isinstance(lst, list):
dict1 = {}
for key, value in enumerate(lst):
dict1[key] = value
return dict1
return '非法参数,应为列表类型!'
print(my_trans((3, 4, 5))) # 非法参数,应为列表类型!
print(my_trans([11, 3, 4, 77, 9])) # {0: 11, 1: 3, 2: 4, 3: 77, 4: 9}
习题8
写函数,函数接收四个参数分别是:姓名,性别,年龄,学历.通过输入这4个内容,然后将这四个内容传入到函数中,此函数接收到这四个内容,将内容追加到一个strdent_msg文件中.
import re
import os
import json
# 检查传入参数是否非法
def check(fun):
def check_parameters(name, gender, age, education):
if not re.match(r'[\w]{2,12}$', name):
raise Exception('非法参数,name:应为2-12的英文或者字符')
if not re.match(r'male$|female$|男$|女$', gender, flags=re.I):
raise Exception('非法参数,gender:应为[male、female、男、女]其中之一')
if not re.match(r'[6-9]$|[1-9][\d]$', str(age)):
raise Exception('非法参数,age:应为6-99的整型')
if not re.match(r'[\w]{2,16}$$', education):
raise Exception('非法参数,education:应为2-16的英文或者字符')
fun(name, gender, age, education, file_name='student_msg')
return check_parameters
@check
def student(name, gender, age, education, file_name='student_msg'):
# 字典数据
info = {}
info.update({"name": name, "gender": gender, "age": age, "education": education})
path = ''
with open(file_name, mode="a+") as f1:
# 判断文件内容是否为空
if not os.path.getsize(file_name):
json.dump([info], f1)
else:
f1.seek(0)
# 读取文件内容
result = json.load(f1)
result.append(info)
path = file_name + '_bak'
with open(path, mode='w') as f2:
json.dump(result, f2)
# 删除源文件并把更新后的文件命名为源文件名
if os.path.isfile(file_name) and os.path.isfile(path):
os.remove(file_name)
os.rename(path, file_name)
name = input('姓名:')
gender = input('性别:')
age = input('年龄:')
education = input('学历:')
student(name=name, gender=gender, age=age, education=education)
with open('student_msg') as f1:
for i in json.load(f1):
print(i)
# 运行结果:
# 姓名:朱古力
# 性别:male
# 年龄:18
# 学历:研究生
# {'name': '朱古力', 'gender': 'male', 'age': '18', 'education': '研究生'}
习题9
对第8题升级:支持用户持续输入,Q或者q退出,性别默认男,如果遇到女学生,则把性别输入为女.
import re
import os
import json
# 检查传入参数是否非法
def check_parameters(flag):
if flag == 0:
if not re.match(r'[\w]{2,12}$', name):
raise Exception('非法参数,name:应为2-12的英文或者字符')
if flag == 1:
if not re.match(r'male$|female$|男$|女$', gender, flags=re.I):
raise Exception('非法参数,gender:应为[male、female、男、女]其中之一')
if flag == 2:
if not re.match(r'[6-9]$|[1-9][\d]$', str(age)):
raise Exception('非法参数,age:应为6-99的整型')
if flag == 3:
if not re.match(r'[\w]{2,16}$$', education):
raise Exception('非法参数,education:应为2-16的英文或者字符')
def student(name, age, education, gender="男", file_name='student_msg'):
# 字典数据
info = {}
info.update({"name": name, "gender": gender, "age": age, "education": education})
path = ''
with open(file_name, mode="a+") as f1:
# 判断文件内容是否为空
if not os.path.getsize(file_name):
json.dump([info], f1)
else:
f1.seek(0)
# 读取文件内容
result = json.load(f1)
result.append(info)
path = file_name + '_bak'
with open(path, mode='w') as f2:
json.dump(result, f2)
# 删除源文件并把更新后的文件命名为源文件名
if os.path.isfile(file_name) and os.path.isfile(path):
os.remove(file_name)
os.rename(path, file_name)
while True:
name = input('姓名:')
if name.upper() == 'Q':
break
check_parameters(flag=0)
gender = input('性别:')
if name.upper() == 'Q':
break
check_parameters(flag=1)
age = input('年龄:')
if name.upper() == 'Q':
break
check_parameters(flag=2)
education = input('学历:')
if name.upper() == 'Q':
break
check_parameters(flag=3)
student(name=name, gender=gender, age=age, education=education)
print('***************************已收入的信息***************************')
with open('student_msg') as f1:
for i in json.load(f1):
print(i)
# 运行结果:
# 姓名:宝庆
# 性别:男
# 年龄:38
# 学历:本科
# ***************************已收入的信息***************************
# {'name': '小丽', 'gender': '男', 'age': '18', 'education': '大专'}
# {'name': '小光', 'gender': '男', 'age': '19', 'education': '高中'}
# {'name': '莉莉', 'gender': '女', 'age': '20', 'education': '本科'}
# {'name': '小雅', 'gender': '女', 'age': '28', 'education': '博士'}
# {'name': '啸天', 'gender': '男', 'age': '68', 'education': '硕士'}
# {'name': '小甜甜', 'gender': '女', 'age': '30', 'education': '高中'}
# {'name': '宝庆', 'gender': '男', 'age': '38', 'education': '本科'}
习题10
写函数,用户传入修改的文件名,与用修改的内容,执行函数,完成整个文件的批量修改操作.
import os
"""
abc源文件内容:
西川
你是一棵望天树
你是一粒金黄的麦子
西川
你是黑暗里向往光明的太阳
你是银河里一条跳跃的黑泥鳅
西川
你是长城上一块大方砖
你是棋盘上战无不胜的车子
西川
你在草原上成了狮子王
你在云上快乐地迎接死亡
"""
def fun(file_name, new_file_name, old_word, new_word):
if not os.path.isfile(file_name):
raise Exception('文件名错误')
with open(file_name, encoding='utf-8') as f1, \
open(new_file_name, encoding='utf-8', mode='w') as f2:
for line in f1:
if old_word in line:
line = line.replace(old_word, new_word)
f2.write(line)
os.remove(file_name)
file_name = input('源文件名:')
new_file_name = input('修改后新文件名:')
old_word = input('要修改的内容:')
new_word = input('修改后的内容:')
fun(file_name, new_file_name, old_word, new_word)
"""
abc.txt内容:
四川
你是一棵望天树
你是一粒金黄的麦子
四川
你是黑暗里向往光明的太阳
你是银河里一条跳跃的黑泥鳅
四川
你是长城上一块大方砖
你是棋盘上战无不胜的车子
四川
你在草原上成了狮子王
你在云上快乐地迎接死亡
"""

浙公网安备 33010602011771号