[ python ] 练习作业 - 2
2024-09-26 15:30:39
1、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。
lic = [0, 1, 2, 3, 4, 5]
def func(l):
return l[1::2]
print(func(lic))
2、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。
def func(s):
if len(s) > 5:
print('%s > 5' % s)
elif len(s) <= 5:
print('%s <= 5' % s)
3、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
def func(n):
return n[:2]
4、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数,并返回结果。
context = input('>>>') def func(arg):
dic = {'数字':0, '字母':0, '空格':0, '其他':0}
for i in arg:
if i.isdigit():
dic['数字'] += 1
elif i.isalpha():
dic['字母'] += 1
elif i.isspace():
dic['空格'] += 1
else:
dic['其他'] += 1
return dic print(func(context))
5、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容,并返回结果。
l = ['a', ' b', 'c ', 'hel lo', 1, 2, 3]
def func(arg):
for i in arg:
i = str(i)
if ' ' in i:
print('%s 内有空格' % i) else:
print(i)
func(l)
6、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
dic = {1: 123, 'a': 'hello', 'b':['world', 'nice', 'bigbang']} def func(dic):
for k, v in dic.items():
if not isinstance(v, (int, float, bool)):
dic[k] = v[:2]
return dic print(func(dic))
7、写函数,接收两个数字参数,返回比较大的那个数字。
print(max(1, 10))
8、写函数,用户传入修改的文件名,与要修改的内容,执行函数,完成整个文件的批量修改操作(进阶)。
import os file_name = input('文件名:')
be_modify = input('要修改的内容:')
af_modify = input('要替换的内容:') def func(file, be_f, af_f):
with open(file, 'r', encoding='utf-8') as read_f, open(file+'_new', 'w', encoding='utf-8') as write_f:
for line in read_f:
if be_f in line:
new_line = line.replace(be_f, af_f)
write_f.write(new_line)
else:
write_f.write(line)
os.remove(file_name)
os.rename(file_name + '_new', file_name) func(file_name, be_modify, af_modify)
9、写一个函数完成三次登陆功能,再写一个函数完成注册功能
def regist():
while True:
user = input('user:').strip()
if not user: continue
else:
break
pwd = input('pwd:').strip()
dic = ('注册账号:{}, 密码:{}'.format(user, pwd))
return dic # print(regist()) def login():
count = 1
while count < 4:
username = input('username:')
password = input('password:')
if username == 'hkey' and password == '':
print('登录成功.')
return
else:
print('登录失败.')
count += 1 login()
最新文章
- [UML]UML系列——类图class的泛化关系
- Java中的四舍五入
- JSONP跨域数据调用
- CRM 2013 系统设置新功能二:Entity images 图像字段
- C++ STL库之vector
- 【英语】Bingo口语笔记(62) - 生气道歉场景的表达
- 加载gif图过渡效果
- 原生Javascript实现图片轮播效果
- Android checkbox和radiobutton 以及Toast和AlertDialog的使用
- ubuntu 14.04 opencv2.4.13 安装
- DirectFB 之 字体显示
- 在Swift中实现 oc与swift的混编
- st9720-GB 中文编码对照表
- supervisor管理nginx
- vue data中调用图片的相对路径
- spring framework核心框架体系结构(转载)
- Linux巩固记录(4) 运行hadoop 2.7.4自带demo程序验证环境
- Ettercap之ARP+DNS欺骗
- 3D几何图形生成的DEMO
- C# 大文件的复制方法
热门文章
- 深入理解JVM一java堆分析
- Sum of Consecutive Integers LightOJ - 1278(推公式 数学思维)
- 【转】NHibernate 各种数据库配置
- pthread的pthread_join()函数理解实验
- 【算法乱讲】BSGS
- CF487E Tourists 【圆方树 + 树剖 + 堆】
- 流媒体协议之JRTPLIB的使用20170919
- mybatis中的resultMap与resultType、parameterMap与 parameterType的区别
- windows环境libevent搭建和demo分析
- linux jq命令小结