Python__函数习题,,1、简述普通参数、指


1、简述普通参数、指定参数、默认参数、动态参数的区别

技术分享
 1 # ######### 定义函数 #########  2  3 # name 叫做函数func的形式参数,简称:形参 4 def func(name): 5     print name 6  7 # ######### 执行函数 #########  8 #  ‘wupeiqi‘ 叫做函数func的实际参数,简称:实参 9 func(‘wupeiqi‘)10 11 def func(name, age = 18):12     13     print "%s:%s" %(name,age)14 15 # 指定参数16 func(‘wupeiqi‘, 19)17 # 使用默认参数18 func(‘alex‘)19 20 注:默认参数需要放在参数列表最后21 22 23 def func(*args):24 25     print args26 27 28 # 执行方式一29 func(11,33,4,4454,5)30 31 # 执行方式二32 li = [11,2,2,3,3,4,54]33 func(*li)34 35 def func(**kwargs):36 37     print args38 39 40 # 执行方式一41 func(name=‘wupeiqi‘,age=18)42 43 # 执行方式二44 li = {‘name‘:‘wupeiqi‘, age:18, ‘gender‘:‘male‘}45 func(**li)46 47 def func(*args, **kwargs):48 49     print args50     print kwargs
View Code

2、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数

技术分享
1 def my_len(my_def):2      my_def.split()3      return len(my_def)4 res = my_len(‘hfweiie8832  fej中文‘)5 print(res)
View Code

3、写函数,判断用户传入的对象(字符串、列表、元组)长度是否大于5。

技术分享
 1 def my_fun(func): 2     my_count = 0 3     for i in func: 4         my_count = my_count + 1 5     if my_count > 5: 6         print(‘你传入的对象的长度大于5‘) 7     else: 8         print(‘你传入的对象的长度不大于5‘) 9 10 my_fun([1,2,‘jdi‘,‘中文‘])
View Code

4、写函数,检查用户传入的对象(字符串、列表、元组)的每一个元素是否含有空内容。

技术分享
1 def my_fun(func):2     for i in func:3         if i.isspace():4              print(‘这个元素含有空内容‘)5         else:6             continue7 8 my_fun([‘ ‘,‘12‘,‘3‘,‘4‘,‘diw‘])
View Code

5、写函数,检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

技术分享
1 def my_fun(func):2     my_count = 03     for i in func:4         my_count = my_count + 15     if my_count > 2:6         func = func[0:2]7         return func8 res = my_fun([1,2,3,‘edj‘])9 print(res)
View Code

6、写函数,检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者。

技术分享
1 def my_fun(func):2     my_count = 03     func1 = []4     for i in func:5         my_count = my_count + 16         if my_count % 2 == 0:7             func1.append(i)8     print(func1)9 my_fun([1,2,3,‘edj‘])
View Code

7、写函数,检查传入字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。

123dic={"k1":"v1v1","k2": [11,22,33,44]}PS:字典中的value只能是字符串或列表

技术分享
 1 def my_dict(dic): 2     for key in dic: 3         if len(dic[key]) > 2: 4             dic[key] = dic[key][0:2] 5         else: 6             continue 7     return dic 8 dic = {"k1": "v1v1", "k2": [11,22,33,44]} 9 res = my_dict(dic)10 print(res)
View Code

8、写函数,利用递归获取斐波那契数列中的第 10 个数,并将该值返回给调用者。

技术分享
 1 def my_feb(n): 2     my_count = 0 3     arg1 = 1 4     arg2 = 1 5     for k in range(1,(n+1)): 6         if my_count < n and my_count >= 2: 7             my_count = my_count + 1 8             arg3 = arg1 + arg2 9             arg1 = arg210             arg2 = arg311         else:12             my_count = my_count + 113             arg3 = 114     return arg315 res = my_feb(10)16 print(res)
View Code

Python__函数习题

评论关闭