实战一:编写函数实现计算列表中元素的最大值
需求:随机产生10个元素,存储到列表中,编写函数获取这个列表中元素的最大值(不能使用内置函数max())。
import random
def get_max(lst):
x=lst[0]
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)
实战二:编写函数实现提取指定字符串中的数字并求和需求:
使用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)
实战三:编写函数实现将字符串中字母的大小写转换
需求:使用input()获取一个字符串,编写并传参,将字符串中所有的小写字母转成大写字母,将大写字母转成小写字母
def lower_upper(x):
lst=[]
for item in x:
if 'A'<=item<='Z':
lst.append(chr(ord(item)+32))
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)
实战四:编写函数实现操作符in的功能需求:
使用input()从键盘获取一个字符串,判断这个字符串在列表中是否存在(函数体不能使用in),返回结果为True或False
def get_find(s,lst):
for item in lst:
if s==item:
return True
return False
lst=['hello','world','python']
s=input('请输入您要判断的字符串:')
result=get_find(s,lst)
print('存在' if result else '不存在')
注:本文中的内容及实例均出自@Python_子木的视频