Python学习的第十六天:函数的应用实例

Python学习的第十六天

函数模块的使用方法

  • 如果要使用其他文件(模块)中定义的函数
    方法一:可以通过import导入模块,然后通过"模块名.函数名"的方式调用函数;
    方法二:直接从模块中导入函数 —> “from 模块 import 函数” —> 直接通过函数名调用函数

  • import导入函数、模块时,可以使用as关键字(alias)进行别名

  • 做工程化项目开发时,如果项目中的代码文件非常多,我们可以使用"包"(package)来管理"模块"(module),
    再通过模块来管理函数,包其实就是一个文件夹,而模块就是一个Python文件,通过这种方式就可以很好的解决
    大型项目团队开发中经常遇到的命名冲突的问题。

  • Python中的from、import、as关键字就是专门用来处理包和模块导入的操作的。

函数应用实例

生成随机验证码
import random
import string


def get_captcha_code(length: int = 4) -> str:
    """生成随机验证码

    :param length: 验证码的长度
    :return: 随机验证码字符串
    """
    selected_chars = random.choices(string.digits + string.ascii_letters, k=length)
    return ''.join(selected_chars)


for _ in range(10):
    print(get_captcha_code())

在这里插入图片描述

判断是否为正整数
def is_prime(num: int) -> bool:
    """判断一个正整数是不是质数

    :param num: 正整数
    :return: 如果是质数返回True,否则返回False
    """
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            return False
    return num != 1


for n in range(2, 100):
    if is_prime(n):
        print(n, end=' ')

在这里插入图片描述

求最大公约数和最小公倍数
def gcd(x: int, y: int) -> int:
    """求最大公约数"""
    while y % x != 0:
        x, y = y % x, x
    return x


def lcm(x: int, y: int) -> int:
    """求最小公倍数"""
    return x * y // gcd(x, y)


print(gcd(27, 15))
print(lcm(27, 15))

在这里插入图片描述

获取文件的后缀名
# 定义函数时,写在*前面的参数称为位置参数,调用函数传递参数时,只需要对号入座
# 写在*后面的参数称为命名关键字参数,调用函数传递参数时,必须要写成"参数名=参数值"的形式
def get_suffix(filename, *, has_dot=False) -> str:
    """获取文件的后缀名

    :param filename: 文件名
    :param has_dot: 后缀名是否包含.
    :return: 后缀名
    """
    position = filename.rfind('.')
    if position <= 0:
        return ''
    if not has_dot:
        position = position + 1
    return filename[position:]

import utils

print(utils.get_suffix(filename='hello.py'))
# 调用函数传递参数时,可以给参数带上名字,这种参数称为关键字参数
print(utils.get_suffix('hello.py', has_dot=True))
print(utils.get_suffix('hello.py.txt'))
print(utils.get_suffix('hello.py.txt', has_dot=True))
print(utils.get_suffix('hello'))
print(utils.get_suffix('hello.'))
print(utils.get_suffix('.hello'))

在这里插入图片描述

获取A班和B班考试成绩的描述性统计
import math
import random


def ptp(data):
    """求极差(全距)"""
    return max(data) - min(data)


def average(data):
    """求均值"""
    return sum(data) / len(data)


def variance(data):
    """求方差"""
    x_bar = average(data)
    temp = [(num - x_bar) ** 2 for num in data]
    return sum(temp) / (len(temp) - 1)


def standard_deviation(data):
    """求标准差"""
    return math.sqrt(variance(data))


def median(data):
    """找中位数"""
    temp, size = sorted(data), len(data)
    if size % 2 != 0:
        return temp[size // 2]
    else:
        return average(temp[size // 2 - 1:size // 2 + 1])
from random import randrange

from utils.stats import average as avg, median, variance, standard_deviation as std

class_a_scores = [randrange(50, 101) for _ in range(50)]
class_b_scores = [randrange(50, 101) for _ in range(50)]
print('A班考试成绩描述性统计信息')
print(f'平均分: {avg(class_a_scores)}')
print(f'中位数: {median(class_a_scores)}')
print(f'方差: {variance(class_a_scores)}')
print(f'标准差: {std(class_a_scores)}')
print('B班考试成绩描述性统计信息')
print(f'平均分: {avg(class_b_scores)}')
print(f'中位数: {median(class_b_scores)}')
print(f'方差: {variance(class_b_scores)}')
print(f'标准差: {std(class_b_scores)}')

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

踏墟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值