python基础函数练习题

  • Post author:
  • Post category:python


一、编写函数包含 位置参数,关键字参数,可变元组参数,可变字典参数
def fun(a, b=10, *args, **kwargs):
    print(a, b, args, kwargs)


fun(10, 5, 60, kw=789)
二、编写函数验证 全局变量, 局部变量, gloabl与nonlocal关键字使用
v = 10
print(v)


def fun(v1):
    print(v1)


    global v2
    v2 = 80
    print(v2)


    v3 = 90


    def fun2():
        nonlocal v3
        v3 = 70
        print(v3)

    fun2()
    print(v3)


fun(10)
print(v)
三、编写推导式案例 列表 元组 字典 集合
# l = [1, 2, 3]#列表
# l1 = [e for e in l]
# print(l)
# s = (1, 2, 3) #元组
# s1 = (c for c in s)
# print(s1)
# d = {"name":"小明","old":"15"} #字典
# d1 = {k:k for k in d}
# print(d1)
# s = {1, 2, "hello"}
# s1 = {e for e in s}
# print(s1)
四.编写函数求从a,b 相差为c的质数对
 def fun(a, b, c):
     for i in range(a, b + 1):
         for j in range(2, i):
             if i % j == 0:
                 break
         else:
             for x in range(a, i + 1):
                 for y in range(2, x):
                     if x % y == 0:
                         break
                 else:
                     if i - x == c:
                         print(i, x, c)
     return


 fun(10, 50, 6)
import random
 五、随机10000个位于50-100之间的整数,80%的概率放入列表1,20%的概率放入列表2
 求列表1平均数与列表2平均数的差值
l1 = []
l2 = []
total1 = 0
total2 = 0
count1 = 0
count2 = 0
for i in range(10000):
    value = random.randint(50, 100)
    if random.random() <= 0.8:
        l1.append(value)
        total1 += 1
        count1 += value
    else:
        l2.append(value)
        total2 += 1
        count2 += value
print((count1/total1)- (count2/total2))
六、现有一个列表 [1,5,3,2,8,9,4,6]
  不适用sort函数 对其进行排序
l = [1, 5, 3, 2, 8, 9, 4, 6]
l1 = []
for i in range(len(l), 0, -1):
    value = min(l)
    l1.append(value)
    l.remove(value)
print(l1)



版权声明:本文为qq_61952259原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。