Python函数练习

有错误之处,欢迎指出,我会及时修改的,谢谢

1.编写函数,求1+2+3+…N的和

# 不可使用sum函数
# def get_sum(n):
#     if n == 1:
#         return 1
#     return n + get_sum(n - 1)
def get_sum(n):
    s = 0
    for i in range(1,n+1):
        s += i
    return s
print(get_sum(100))# 5050
# print(sum(range(101)))# 5050 我只是演示

2.编写一个函数,求多个数中的最大值

前面就说过可变位置参数,当很多数值传入函数时,多出来的位置参数是以元组的形式保存在arg里的

# 不得使用max函数
def get_max(*args):
    x = args[0] 
    for arg in args:
        if arg > x: # 只要有比x大的数,就将这个数赋值给x
            x = arg 
    return x
print(get_max(1, 2, 4, 5, 6, 77, 9, 5))# 77

3.编写一个函数,实现摇骰子的功能,打印N个骰子的点数和

这里要使用到random模块,random模块是用来产生随机数,随机选择等操作的
这里我们会用到randint方法,产生一个[n,m]之间的随机整数,都是闭区间

# 由于是随机数我就不写出答案了,
# 不过大家可以把每一次的point打印一下,验证一下
def get_count(n):
    s = 0
    for i in range(n):
        point = random.randint(1, 6)
        # print(point)
        s += point
    return s
print(get_count(6))

4.编写一个函数,交换指定字典的key和value

我在函数基础哪里讲过,调用函数在传参时,多出来的关键字参数会以字典的形式保存到kwargs里面,字典的item方法我也在前面讲过,要是还是不知道它是什么,大家可以直接用字典调用这个方法在打印一下就好了

def swap(**kwargs):
    # new_dict={}
    # for key in kwargs:
    #     new_dict[kwargs[key]]=key
    # return new_dict
    return {
    
    x:y for y,x in kwargs.items()}# 字典推导式
print(swap(a=1, b=2, c=3))# {1: 'a', 2: 'b', 3: 'c'}

5.编写一个函数,提取指定字符串中所有的字母,然后拼接在一起产生一个新的字符串

# 例如:传入' 12a&bc12d-+' -->' abcd'
def get_ABC(word):
    new_str = ''
    for x in word:
        if x.isalpha():
            new_str += x
    return new_str
print(get_ABC('hello456world'))# helloworld

6.写一个函数,求多个数的平均值

def get_average(*args):
    i = 0
    for arg in args:
        i += arg
    return i / len(args)
print(get_average(10, 20, 30, 40))# 25.0

7.写一个函数,默认求10的阶乘,也可以求其他数字的阶乘

# 简易少使用递归
# def get_factorials(x=10):
#     if x == 1:
#         return 1
#     return x * get_factorials(x - 1)
def get_factorials(n=10):
    s = 1
    for i in range(1,n+1):
        s *= i
    return s
print(get_factorials(5))# 120

8.写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母

# 例如: 'abc' -> ' Abc'' 12asd' --> ' 12asd'
def my_capitallize(word):
    i = word[0]
    if 'a' <= i <= 'z':
        new_word = word[1:]
        i = i.upper()
        return i + new_word
    return word
print(my_capitallize('123words'))# 123words
print(my_capitallize('abc'))# Abc

9.写一个自己的endswith函数,判断一个字符串是否由指定的字符串结尾

def my_endswith(word, factor):
	# 直接切长度为需要判断字符串长度的最后几个字符
    return word[-len(factor):] == factor
print(my_endswith('123aba', 'b'))# False
print(my_endswith('123aba', 'ba'))# True

10.写一个自己的函数isdigit函数,判断一个字符串是否全部由数字组成

def my_isdigit(words):
    for word in words:
        if not'0'<=word<='9':
            return False
    return True
print(my_isdigit('12a'))# False
print(my_isdigit('12'))# True

11.写一个自己的upper函数,将字符串里的所有小写字母变成大写

def my_upper(old_str):
    # a==>97,A==>65
    new_str=''
    for i in old_str:
        if 'a'<=i<='z':
            i=chr(ord(i)-32)# 先转编码值再转字符
            new_str += i
        else:
            new_str += i
    return new_str
print(my_upper('123hello'))# 123HELLO

12.写一个自己的rjust函数,创建一个字符串的长度时指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充

def my_rjust(word,long,fillchar):# 原字符串,长度,填充字符
    long_char = fillchar*(long-len(word))
    return long_char + word
print(my_rjust('abc', 7,'!'))# !!!!abc

13.写一个自己的index函数,打印指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1

def my_index(lists,m):
    if m in lists:
        for i,j in enumerate(lists):# 带下表的遍历
            if j == m:
                print(i,end=',')
        print()
    else:
        print('-1')

my_index([1, 2, 45, 'abc', 1, '你好', 1, 0],1)   # 0,4,6,
my_index(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'],'赵云')  # 0,4
my_index(['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'],'关羽')  # -1

14.写一个自己的len函数,统计指定序列元素的个数

def my_len(sequence):
    count = 0
    for x in sequence:
        count += 1
    return count
b = my_len('hello w')
c = my_len([1, 3, 5, 6])
d = my_len((1, 34, 'a', 45, 'bbb'))
print(b,c,d)  # 7 4 5

15.写一个函数实现in操作的函数,判断指定的序列中,指定元素是否存在

def my_in(a,b):
    for x in a:
        if x == b:
            return True
    return False
print(my_in((12, 90, 'abc'), '90'))# False
print(my_in((12, 90, 'abc'), 90))# True

16.写一个自己的replace函数,将指定的字符串中的旧字符串转换成指定的新字符串

def my_replace(all_str, old_str, new_str):
    # 先将原字符串按旧字符串分割成一个列表
    # 再用新字符串讲这个列表进行分割
    return new_str.join(all_str.split(old_str))
print(my_replace('how do you do', 'o', '*'))# h*w d* y*u d*

17.写自己的一个max函数,获取指定序列中元素的最大值,如果序列是字典,取字典的最大值

def my_max(seq):
    # if type(seq) == dict:
    if isinstance(seq,dict):#看对象是否通过dict类创建出来的
        seq = list(seq.values())
    x = seq[0]
    for i in seq:
        if i > x:
            x = i
    return x
x = my_max([-7, -12, -1, -9])
y = my_max('abcdpzasdz')
z = my_max({
    
    '小明':90, '张三': 76, '路飞':30, '小花': 98})
print(x,y,z)# -1 z 98

每一个练习都可以多种方法能够做出来,相信大家做出来的方法回比我的还要漂亮
加油,学习是一个长久的过程,虽然枯燥,但不乏有那么一丁点的快乐
虽然我还没发现那一丁点快乐,但我相信你,也找不到,哈哈哈
今日份‘皮’就到这了,记得点赞哦

猜你喜欢

转载自blog.csdn.net/hmh4640219/article/details/112322871
今日推荐