函数案例讲解 | 手把手教你入门Python之五十五

简介: 通过案例回顾所学的函数知识点。

上一篇:有关运算的魔法方法 | 手把手教你入门Python之五十四
下一篇:面向对象案例讲解 | 手把手教你入门Python之五十六

本文来自于千锋教育在阿里云开发者社区学习中心上线课程《Python入门2020最新大课》,主讲人姜伟。

函数案例讲解

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

def get_sum(n):
    sum = 0
    for i in range(int(n)):
        sum += i
    return sum

print(get_sum(100)) # 4950
AI 代码解读

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

def get_max(*args):
    x = args[0]
    for arg in args:
        if arg > x:
            x = arg
    return x

print(get_max(1, 9, 6, 3, 4, 5)) # 9
AI 代码解读

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

import random

def get_sum(n):
    m = 0
    for i in range(n):
        x = random.randint(1, 6)
        m += x
    return m

print(get_sum(5))  # 23
AI 代码解读

4.编写一个函数,交换指定字典的key和value
例如:dict1={'a':1, 'b':2, 'c':3} --> dict1={1:'a', 2:'b', 3:'c'}

def swap(dict1):
    dict = {}
    for k, v in dict1.items():
        dict[v] = k
    return dict

dict1 = {'a': 1, 'b': 2, 'c': 3}
print(swap(dict1))
AI 代码解读

5.编写一个函数,提取指定字符串中的所有字母,然后拼接在一起产生一个新的字符串
例如:传入'12a&bc12d-+' -->'abcd'

def get_alphas(word):
    new_str = ''
    for w in word:
        if w.isalpha():
            new_str += w
    return new_str

print(get_alphas('hello123good456')) # hellogood
AI 代码解读

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

def get_averange(*args):
    x = 0
    for arg in args:
        x += arg
    return x / len(args)

print(get_average(1, 2, 3, 4, 5, 6))  # 3.5
AI 代码解读

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

def get_factorial(n=10):
    x = 1
    for i in range(1, n+1):
        x *= i
    return x

print(get_factorial(4)) # 24
AI 代码解读

8.写一个自己的capitalize函数,能够将指定字符串的首字母变成大写字母
例如:'abc' -> 'Abc' '12asd' --> '12asd'

def my_capitalize(word):
    c = word[0]
    if 'z' >= c >= 'a':
        new_str = word[1:]
        return c.upper() + new_str
    return word

print(my_capitalize('hello'))  # Hello
print(my_capitalize('34hello')) # 34hello
AI 代码解读

9.写一个自己的endswith函数,判断一个字符串是否以指定的字符串结束
例如:字符串1:'abc231ab' 字符串2:'ab' 函数结果为:True
字符串1:'abc231ab' 字符串2:'ab1' 函数结果为:False

def my_endswith(old_str, str1):
    return old_str[-len(str1):] == str1

print(my_endswith('hello', 'llo'))  # True
print(my_endswith('hello', 'lxo'))   # False
AI 代码解读

10.写一个自己的isdigit函数,判断一个字符串是否是纯数字字符串
例如:'1234921' 结果:True

  `'23函数' 结果:False`
  `'a2390' 结果:False`
AI 代码解读
def my_digit(old_str):
    for s in old_str:
        if not '0' <= s <= '9':
            return False
    return True

print(my_digit('123hd90'))  # False
print(my_digit('12390'))  # True
AI 代码解读

11.写一个自己的upper函数,将一个字符串中的所有的小写字母变成大写字母
例如:'abH23好rp1' 结果:'ABH23好RP1'

# a==>97  A ==> 65   32
def my_upper(old_str):
    new_str = ''
    for s in old_str:
        if 'a' <= s <= 'z':
            upper_s = chr(ord(s) - 32)
            new_str += upper_s
        else:
            new_str += s
    return new_str

print(my_upper('hello'))  # HELLO
print(my_upper('hel34lo'))  # HEL34LO
AI 代码解读

12.写一个自己的rjust函数,创建一个字符串的长度是指定长度,原字符串在新字符串中右对齐,剩下的部分用指定的字符填充
例如:原字符:'abc' 宽度:7 字符:'^' 结果:'^^^^abc'
原字符:'你好吗' 宽度:5 字符:'0' 结果:'00你好吗'

def my_rjust(s, sub_str, num):
    return sub_str * (num - len(s)) + s

print(my_rjust('aaa', 'r', 4))  # raaa
AI 代码解读

13.写一个自己的index函数,统计指定列表中指定元素的所有下标,如果列表中没有指定元素返回-1
例如:列表:[1, 2, 45, 'abc', 1, '你好', 1, 0] 元素:1 结果:0,4,6
列表:['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素:'赵云' 结果:0,4
列表:['赵云', '郭嘉', '诸葛亮', '曹操', '赵云', '孙权'] 元素:'关羽' 结果:-1

def index(string, s):
    idxs=[]
    for i, st in enumerate(string):
        if st == s:
            idxs.append(i)
    return idxs if len(idxs) > 0 else -1

print(index('ststs', 's'))  # [0,2,4]
print(index('ssss', 't'))  # -1
AI 代码解读

14.写一个自己的len函数,统计指定序列中元素的个数
例如:序列:[1, 3, 5, 6] 结果:4
序列:(1, 34, 'a', 45, 'bbb') 结果:5
序列:'hello w' 结果:7

def my_len(l):
    c = 0
    for a in l:
        c += 1
    return c

print(my_len([ 1, 2, 1, 1]))  # 4
AI 代码解读

15.写一个函数实现自己in操作,判断指定序列中,指定的元素是否存在
例如:序列:(12, 90, 'abc') 元素:'90' 结果:False
序列:[12, 90, 'abc'] 元素:90 结果:True

def my_in(it, ele):
    for i in it:
        if i == ele:
            return True
        else:
            return False

print(my_in(['zhangsan', 'lisi', 'wangwu'], 'lisi'))   # True
print(my_in(['zhangsan', 'lisi', 'wangwu'], 'jack'))   # False
print(my_in({'name': 'zhangsan', 'age': '18'}, 'name'))   # True
AI 代码解读

16.写一个自己的replace函数,将指定字符串中指定的旧字符串转换成指定的新字符串
例如:原字符串:'how are you? and you?' 旧字符串:'you' 新字符串:'me' 结果:'how are me? and me?'

def my_replace(all_str,old_str,new_str):
    return new_str.join(all_str.split(old_str))

print(my_replace('how you and you fine you ok','you','me'))  # how me and me fine me ok
AI 代码解读

第二种解法:

def my_replace(all_str,old_str,new_str):
    result = ''
    i = 0
    while i < len(all_str):
        temp = all_str[i: i + len(old_str)]
        if temp != old_str:
            result += all_str[i]
            i += 1
        else:
            result += new_str
            i += len(old_str)
    return result

print(my_replace('how you and you fine you ok','you','me'))  # how me and me fine me ok
AI 代码解读

1.写一个自己的max函数,获取指定序列中元素的最大值。如果序列是字典,取字典值的最大值
例如:序列:[-7, -12, -1, -9] 结果:-1
序列:'abcdpzasdz' 结果:'z'
序列:{'小明':90, '张三':76, '路飞':30, '小花':98} 结果:98

def get_max2(seq):
    if type(seq) == dict:
        seq = list(seq.values())
    x = seq[0]
    for i in seq:
        if i > x:
            x = i
    return x

print(get_max2([2, 4, 8, 1, 9, 0, 7, 5]))   # 9

print(get_max2({'x':10, 'y':29, 'z':32, 'a':23, 'b':19, 'c':98}))  # 98
AI 代码解读

2.写四个函数,分别实现求两个列表的交集、并集、差集、补集的功能

# 交集

def intersection(list1: list, list2: list):
    """
    求两个列表中的交集
    :param list1:第一个列表
    :param list2:第二个列表
    :return:两个列表的公共部分
    """
    new_list = []
    for item in list1:
        if item in list2:
            new_list.append(item)
    return new_list

# 并集

def union_set(list1: list, list2: list):
    """
    求两个列表中的并集
    :param list1:第一个列表
    :param list2:第二个列表
    :return:并集
    """
    return list(set(list1 + list2))

# 差集

def difference_set(list1: list, list2: list):
    """
    求两个列表中的差集
    :param list1:第一个列表
    :param list2:第二个列表
    :return:差集
    """
    new_list = []
    for item in list1:
        if item in list2 and item not in new_list:
            new_list.append(item) 
    return new_list


# 对称差集

def symmetry_diff_set(list1: list, list2: list):
    """
    求两个列表中的对称差集
    :param list1:第一个列表
    :param list2:第二个列表
    :return:对称差集
    """ 
    new_list = []
    for item in list1+list2:
        if (item in list1 and item not in list2) or (item in list2 and item not in list1):
            new_list.append(item)
    return new_list
AI 代码解读

配套视频

目录
打赏
0
0
0
0
285
分享
相关文章
Python入门:8.Python中的函数
### 引言 在编写程序时,函数是一种强大的工具。它们可以将代码逻辑模块化,减少重复代码的编写,并提高程序的可读性和可维护性。无论是初学者还是资深开发者,深入理解函数的使用和设计都是编写高质量代码的基础。本文将从基础概念开始,逐步讲解 Python 中的函数及其高级特性。
Python入门:8.Python中的函数
Python入门:9.递归函数和高阶函数
在 Python 编程中,函数是核心组成部分之一。递归函数和高阶函数是 Python 中两个非常重要的特性。递归函数帮助我们以更直观的方式处理重复性问题,而高阶函数通过函数作为参数或返回值,为代码增添了极大的灵活性和优雅性。无论是实现复杂的算法还是处理数据流,这些工具都在开发者的工具箱中扮演着重要角色。本文将从概念入手,逐步带你掌握递归函数、匿名函数(lambda)以及高阶函数的核心要领和应用技巧。
Python入门:9.递归函数和高阶函数
Python 编程基础与实战:从入门到精通
本文介绍Python编程语言,涵盖基础语法、进阶特性及实战项目。从变量、数据类型、运算符、控制结构到函数、列表、字典等基础知识,再到列表推导式、生成器、装饰器和面向对象编程等高级特性,逐步深入。同时,通过简单计算器和Web爬虫两个实战项目,帮助读者掌握Python的应用技巧。最后,提供进一步学习资源,助你在Python编程领域不断进步。
6个案例15分钟让你了解Python套路
Python以其简洁易读的语法,成为编程初学者的首选。本文通过7个经典代码案例,带你快速了解Python编程的核心概念和常用技巧: 1. **九九乘法口诀**:使用嵌套循环打印乘法表。 2. **列表求和**:展示两种方法(for循环和内置函数sum())计算列表元素之和。 3. **素数判断**:编写函数判断一个数是否为素数。 4. **斐波那契数列**:生成指定长度的斐波那契数列。 5. **冒泡排序**:实现简单的冒泡排序算法。 6. **汉诺塔问题**:通过递归解决经典的汉诺塔问题。 这些案例不仅展示了Python的基础语法,更体现了编程思维的重要性,帮助初学者逐步掌握编程套路。
34 2
Python学习:内建属性、内建函数的教程
本文介绍了Python中的内建属性和内建函数。内建属性包括`__init__`、`__new__`、`__class__`等,通过`dir()`函数可以查看类的所有内建属性。内建函数如`range`、`map`、`filter`、`reduce`和`sorted`等,分别用于生成序列、映射操作、过滤操作、累积计算和排序。其中,`reduce`在Python 3中需从`functools`模块导入。示例代码展示了这些特性和函数的具体用法及注意事项。
|
1月前
|
Python中的round函数详解及使用示例
`round()`函数是Python内置的用于四舍五入数字的工具。它接受一个数字(必需)和可选的小数位数参数,返回最接近的整数或指定精度的浮点数。本文详细介绍其用法、参数及示例,涵盖基本操作、负数处理、特殊情况及应用建议,帮助你更好地理解和运用该函数。
[oeasy]python069_当前作用域都有些什么_列表dir_函数_builtins
本文介绍了Python中`dir()`函数的使用方法及其作用。`dir()`可以列出当前作用域内的所有变量和成员,类似于`locals()`,但`dir()`不仅限于本地变量,还能显示模块中的所有成员。通过`dir(__builtins__)`可以查看内建模块中的所有内建函数,如`print`、`ord`、`chr`等。此外,还回顾了`try-except-finally`结构在数据库连接中的应用,并解释了为何`print`函数可以直接使用而无需导入,因为它位于`__builtins__`模块中。最后,简要提及了删除`__builtins__.print`的方法及其影响。
35 0
python入门(二)安装第三方包
python入门(二)安装第三方包
122 1
【10月更文挑战第5天】「Mac上学Python 6」入门篇6 - 安装与使用Anaconda
本篇将详细介绍如何在Mac系统上安装和配置Anaconda,如何创建虚拟环境,并学习如何使用 `pip` 和 `conda` 管理Python包,直到成功运行第一个Python程序。通过本篇,您将学会如何高效地使用Anaconda创建和管理虚拟环境,并使用Python开发。
197 4
【10月更文挑战第5天】「Mac上学Python 6」入门篇6 - 安装与使用Anaconda
【10月更文挑战第3天】「Mac上学Python 3」入门篇3 - 安装Python与开发环境配置
本篇将详细介绍如何在Mac系统上安装Python,并配置Python开发环境。内容涵盖Python的安装、pip包管理工具的配置与国内镜像源替换、安装与配置PyCharm开发工具,以及通过PyCharm编写并运行第一个Python程序。通过本篇的学习,用户将完成Python开发环境的搭建,为后续的Python编程工作打下基础。
480 2
【10月更文挑战第3天】「Mac上学Python 3」入门篇3 - 安装Python与开发环境配置