1.编写一个函数cacluate, 可以接收任意多个数,返回的是一个元组;元组的第一个值为所有参数的平均值,第二个值是大于平均值的所有数。
def cacluate(*args):
ave = sum(args) / len(args)
up_num=[]
for i in args:
if i > ave:
up_num.append(i)
return ave, up_num
print(cacluate(1, 2, 3, 4, 5))
2.编写一个函数, 接收字符串参数, 返回一个元组,‘hello WROLD’
元组的第一个值为大写字母的个数, 第二个值为小写字母个数。
def fun(x):
upper_count=0
lower_count=0
for item in x:
if item.isupper():
upper_count+=1
elif item.islower():
lower_count+=1
else:
continue
return upper_count,lower_count
print(fun('hello WROLD'))
3.编写函数, 接收一个列表(包含30个整形数)和一个整形数k, 返回一个新列表.
函数需求:
- 将列表下标k之前对应(不包含k)的元素逆序;
- 将下标k及之后的元素逆序;
[1,2,3,4,5] 2 [2,1,5,4,3]
list = []
def fun(new_list, k):
if k < 0 or k > len(new_list):
return 'error'
return new_list[:k][::-1] + new_list[k:][::-1]
print(fun([1,2,3,4,5],2))
4.用函数实现求100-200里面所有的素数。
提示:素数的特征是除了1和其本身能被整除,其它数都不能被整除的数
def test(num):
list = []
i = num - 1
while i > 1:
if num % i == 0:
list.append(i)
i -= 1
if len(list) == 0:
print(num, end=' ')
def test2(start_num, stop_num):
j = start_num
while j < stop_num:
test(j)
j += 1
test2(100, 200)
print('')