1.编写函数 实现计算列表中元素的最大值
需求:
随机产生10个元素,存储到列表中,编写函数获取这个列表中元素的最大值
(不能使用内置函数 max())
def get_max(lst):x=lst[0] # x存储的是元素的最大值# 遍历for i in range(1,len(lst)):if lst[i]>x:x=lst[i] # 对最大值进行重新赋值return x#调用
lst=[random.randint(1,100) for item in range(10)]
print(lst)#计算元素的最大值
max=get_max(lst)
print('max:',max)
运行结果:
D:\Python_Home\venv\Scripts\python.exe D:\Python_Home\chap8\实战1-编写函数实现计算列表中元素的最大值.py
[64, 44, 64, 91, 59, 9, 31, 3, 21, 64]
max: 91
2. 编写函数实现提取指定字符串中的数字并求和
需求:
使用 input() 获取一个字符串,编写并传参,使用 isdigit()方法提取字符串中所有的数字
并对提取的数字进行求和计算,最后将存储的数字的列表 做累加和 并且返回
def get_digit(x):s = 0 # 存储累加和lst = []for item in x:if item.isdigit(): # 如果字符是数字的话lst.append(int(item))# 求和s = sum(lst)return lst, s# 准备函数的调用
s = input('请输入一个字符串:')# 调用
lst, x = get_digit(s)
print('提取的数字列表为:',lst)
print('累加和为:',x)
运行结果:
D:\Python_Home\venv\Scripts\python.exe D:\Python_Home\chap8\实战2-编写函数实现提取指定字符串中的数字并求和.py
请输入一个字符串:hello123world456
提取的数字列表为: [1, 2, 3, 4, 5, 6]
累加和为: 21
3.编写函数实现将字符串中字母的大小写转换
需求:
使用 input() 获取一个字符串,编写并传参,
将字符串中所有的小写字母转换成大写字母, 将大写字母转换成小写字母
def lower_upper(x):lst = []for item in x:if 'A' <= item <= 'Z':lst.append(chr(ord(item) + 32)) # ord()是将字母转换成 Unicode码整数, 加上32就变成大些了, chr()整数码转换成字符elif 'a' <= item <= 'z':lst.append(chr((ord(item) - 32)))else: #其他内容的话直接加进来,不做处理lst.append(item)return ''.join(lst)# 准备调用
s=input('请输入一个字符串:')
new_s=lower_upper(s)
print(new_s)
运行结果:
D:\Python_Home\venv\Scripts\python.exe D:\Python_Home\chap8\实战3-编写函数实现将字符串中字母的大写小转换.py
请输入一个字符串:hello123WORLD
HELLO123world
4. 编写函数实现操作字符 in 的功能
需求:
使用 input()从键盘获取一个字符串,判断这个字符串在列表中是否存在(函数体不能使用 in )
判断结果返回为 True 或 False
def get_find(s,lst):for item in lst:if s==item:return Truereturn Falselst=['hello','world','python']
s=input('请输入一个需要判断的字符串:')
result= get_find(s,lst)
print('存在' if result else '不存在') # if..else 的简写,三元运算符, if result==True 利用到对象的布尔值
运行结果:
D:\Python_Home\venv\Scripts\python.exe D:\Python_Home\chap8\实战4-编写函数实现操作符in的功能.py
请输入一个需要判断的字符串:hello
存在