python大全-高级进阶函数

13 篇文章 0 订阅
10 篇文章 1 订阅

这篇文章是python大全第一篇文章,来介绍进阶版函数!如果你们还没有读过之前的文章的话最好回去读一下!

专栏介绍:何为深度聊天?<--包括python大全介绍


目录

一、何为函数

二、带参数的函数

2.1.一般参数

2.2.等于参数

三、递归函数

3.1.斐波那契数列

3.2.三以内数字累加和:

四、包,库函数

四、return

五、类里面的函数

5.1.自制函数

5.2.内置函数

六、深度聊聊python函数

七、总结


好的,咱们废话不多说,进入正题!

一、何为函数

函数,就像下面这样:

def hanshu():
    print("我是一个函数")

这就是最简单的函数。调用函数的方法如下:

hanshu()

打印结果:

"我是一个函数"

这就是函数。可是函数不能只有这些东西,我们要进阶一下。

二、带参数的函数

2.1.一般参数

一般参数如下:

def hanshu(text):
    print(text + "<--输出结果")

调用函数时要在括号内加入参数:

hanshu("我是一个函数!")

结果为:

"我是一个函数 <--输出结果"

2.2.等于参数

先看一下用法:

def hanshu(text = None):
    print(text)

hanshu()

结果不会报错,会写出一个None!

那怎样才能更改text值呢?

下面就是方法!

hanshu(text = "我是一个函数")

参数是不是有很多用法呢?

具体实例(结合两种):

def hanshu(text, n = None):
    print(text, "=", n)
    print("你觉得对吗?")

三、递归函数

何为递归呢?下面内容可以解释(又来自百度百科)


程序调用自身的编程技巧称为递归( recursion)。递归作为一种算法程序设计语言中广泛应用。 一个过程或函数在其定义或说明中有直接或间接调用自身的一种方法,它通常把一个大型复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解,递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算,大大地减少了程序的代码量。递归的能力在于用有限的语句来定义对象的无限集合。一般来说,递归需要有边界条件、递归前进段和递归返回段。当边界条件不满足时,递归前进;当边界条件满足时,递归返回。


那么我们举几个例子吧!

3.1.斐波那契数列

def Fibo(n):
    # 出口
    if n == 1 or n == 2:
        return 1
    else:
        return Fibo(n - 1) + Fibo(n - 2)

这就是一个斐波那契数列。

3.2.三以内数字累加和:

# 3 + 2 + 1
def sum_numbers(num):
    # 1.如果是1,直接返回1 -- 出口
    if num == 1:
        return 1
    # 2.如果不是1,重复执行累加并返回结果
    return num + sum_numbers(num-1)


sum_result = sum_numbers(3)
# 输出结果为6
print(sum_result)

这就是累加和算法

还有很多递归算法等着大家去使用哦。

四、包,库函数

咱们来看一看math库里的函数吧:

import math as _math
import warnings as _warnings
from operator import mul as _mul


def clamp(num, min_val, max_val):
    return max(min(num, max_val), min_val)


class Vec2(tuple):
    """A two dimensional vector represented as an X Y coordinate pair.

    :parameters:
        `x` : int or float :
            The X coordinate of the vector.
        `y`   : int or float :
            The Y coordinate of the vector.

    Vectors must be created with either 0 or 2 values. If no arguments are provided a vector with the coordinates 0, 0 is created.

    Vectors are stored as a tuple and therefore immutable and cannot be modified directly
    """

    def __new__(cls, *args):
        assert len(args) in (0, 2), "0 or 2 values are required for Vec2 types."
        return super().__new__(Vec2, args or (0, 0))

    @staticmethod
    def from_polar(mag, angle):
        """Create a new vector from the given polar coodinates.

        :parameters:
            `mag`   : int or float :
                The magnitude of the vector.
            `angle` : int or float :
                The angle of the vector in radians.

        :returns: A new vector with the given angle and magnitude.
        :rtype: Vec2
        """
        return Vec2(mag * _math.cos(angle), mag * _math.sin(angle))

    @property
    def x(self):
        """The X coordinate of the vector.

        :type: float
        """
        return self[0]

    @property
    def y(self):
        """The Y coordinate of the vector.

        :type: float
        """
        return self[1]

    @property
    def heading(self):
        """The angle of the vector in radians.

        :type: float
        """
        return _math.atan2(self[1], self[0])

    @property
    def mag(self):
        """The magnitude, or length of the vector. The distance between the coordinates and the origin.

        Alias of abs(self).

        :type: float
        """
        return self.__abs__()

    def __add__(self, other):
        return Vec2(self[0] + other[0], self[1] + other[1])

    def __sub__(self, other):
        return Vec2(self[0] - other[0], self[1] - other[1])

    def __mul__(self, other):
        return Vec2(self[0] * other[0], self[1] * other[1])

    def __truediv__(self, other):
        return Vec2(self[0] / other[0], self[1] / other[1])

    def __abs__(self):
        return _math.sqrt(self[0] ** 2 + self[1] ** 2)

    def __neg__(self):
        return Vec2(-self[0], -self[1])

    def __round__(self, ndigits=None):
        return Vec2(*(round(v, ndigits) for v in self))

    def __radd__(self, other):
        """Reverse add. Required for functionality with sum()
        """
        if other == 0:
            return self
        else:
            return self.__add__(other)

    def from_magnitude(self, magnitude):
        """Create a new Vector of the given magnitude by normalizing, then scaling the vector. The heading remains unchanged.

        :parameters:
            `magnitude` : int or float :
                The magnitude of the new vector.

        :returns: A new vector with the magnitude.
        :rtype: Vec2
        """
        return self.normalize().scale(magnitude)

    def from_heading(self, heading):
        """Create a new vector of the same magnitude with the given heading. I.e. Rotate the vector to the heading.

        :parameters:
            `heading` : int or float :
                The angle of the new vector in radians.

        :returns: A new vector with the given heading.
        :rtype: Vec2
        """
        mag = self.__abs__()
        return Vec2(mag * _math.cos(heading), mag * _math.sin(heading))

    def limit(self, max):
        """Limit the magnitude of the vector to the value used for the max parameter.

        :parameters:
            `max`  : int or float :
                The maximum magnitude for the vector.

        :returns: Either self or a new vector with the maximum magnitude.
        :rtype: Vec2
        """
        if self[0] ** 2 + self[1] ** 2 > max * max:
            return self.from_magnitude(max)
        return self

    def lerp(self, other, alpha):
        """Create a new vector lineraly interpolated between this vector and another vector.

        :parameters:
            `other`  : Vec2 :
                The vector to be linerly interpolated to.
            `alpha` : float or int :
                The amount of interpolation.
                Some value between 0.0 (this vector) and 1.0 (other vector).
                0.5 is halfway inbetween.

        :returns: A new interpolated vector.
        :rtype: Vec2
        """
        return Vec2(self[0] + (alpha * (other[0] - self[0])),
                    self[1] + (alpha * (other[1] - self[1])))

    def scale(self, value):
        """Multiply the vector by a scalar value.

        :parameters:
            `value`  : int or float :
                The ammount to be scaled by

        :returns: A new vector scaled by the value.
        :rtype: Vec2
        """
        return Vec2(self[0] * value, self[1] * value)

    def rotate(self, angle):
        """Create a new Vector rotated by the angle. The magnitude remains unchanged.

        :parameters:
            `angle` : int or float :
                The angle to rotate by

        :returns: A new rotated vector of the same magnitude.
        :rtype: Vec2
        """
        mag = self.mag
        heading = self.heading
        return Vec2(mag * _math.cos(heading + angle), mag * _math.sin(heading+angle))

    def distance(self, other):
        """Calculate the distance between this vector and another 2D vector.

        :parameters:
            `other`  : Vec2 :
                The other vector

        :returns: The distance between the two vectors.
        :rtype: float
        """
        return _math.sqrt(((other[0] - self[0]) ** 2) + ((other[1] - self[1]) ** 2))

    def normalize(self):
        """Normalize the vector to have a magnitude of 1. i.e. make it a unit vector.

        :returns: A unit vector with the same heading.
        :rtype: Vec2
        """
        d = self.__abs__()
        if d:
            return Vec2(self[0] / d, self[1] / d)
        return self

    def clamp(self, min_val, max_val):
        """Restrict the value of the X and Y components of the vector to be within the given values.

        :parameters:
            `min_val` : int or float :
                The minimum value
            `max_val` : int or float :
                The maximum value

        :returns: A new vector with clamped X and Y components.
        :rtype: Vec2
        """
        return Vec2(clamp(self[0], min_val, max_val), clamp(self[1], min_val, max_val))

    def dot(self, other):
        """Calculate the dot product of this vector and another 2D vector.

        :parameters:
            `other`  : Vec2 :
                The other vector.

        :returns: The dot product of the two vectors.
        :rtype: float
        """
        return self[0] * other[0] + self[1] * other[1]

    def __getattr__(self, attrs):
        try:
            # Allow swizzed getting of attrs
            vec_class = {2: Vec2, 3: Vec3, 4: Vec4}.get(len(attrs))
            return vec_class(*(self['xy'.index(c)] for c in attrs))
        except Exception:
            raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attrs}'")

    def __repr__(self):
        return f"Vec2({self[0]}, {self[1]})"

只列举一部分内容,谢谢!

好的,咱们来看一看写法:(我拿出我写的mod.system)

记住,文件位置最好在你的c盘中的python3.x文件里的Lib,里面可以新建文件夹,里面可以写上__init__.py,然后再写上另一个程序,名字随便。或者直接在Lib里面创建一个py文件,名字随意。

方法:

def Print(text):
    print(text)

调用(记住,在3.10里面的就要在3.10里面调用。否则要报错。)

>>>import mod.system
>>>mod.system.Print("xxx")
"xxx"
>>>from mod import system
>>>system.Print("xxx")
"xxx"
>>>from mod.system import Print
>>>Print("xxx")
"xxx"

是不是很简单?

四、return

return这个东西,是只能放在函数里面的,否则要报错!

return是干什么的?

来举个例子:

def hanshu(n):
    if n <= 0:
        return False
    else:
        return True

n = hanshu(3)
print(n)

# 结果
True

搞懂了return了吗?return就是返回一个值,可以赋值变量哦~

是不是很神奇?

五、类里面的函数

5.1.自制函数

之前讲过,我就不细讲了。

class Human():
    def say(self):
        print("I am a human")

human = Human()
human.say()

5.2.内置函数

__init__就是最常见的一个函数了:

class Human():
    def __init__(self, age, height):
        self.age = age
        self.height = height

human = Human(12, 35)

六、深度聊聊python函数

python函数十分有用。为什么这么说?

python函数不仅有参数,还有return等等有用的东西。

阶乘,递归,逆推,正推都有用。并且还可以用在类里面。

函数虽然难,但是他功能齐全,真的十分好用!

七、总结

python有很多东西,print, list, tuple, int, str, float, bool, map, sum, eval, lambda, while, for, range...这些东西都是由一样东西做出来的,那就是函数

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python函数是指一些高级特性和用法,它们可以一步提高代码的复用性、可读性和效率。以下是一些常见的Python函数及其用法: 1. 匿名函数(lambda函数):使用lambda关键字定义的匿名函数可以简洁地定义一些简单的函数。例如,lambda x: x**2表示一个接受参数x并返回x的平方的匿名函数。 2. map()函数:map()函数用于将一个函数应用到一个可迭代对象的每个元素上,并返回一个新的可迭代对象。例如,map(lambda x: x**2, [1, 2, 3, 4])将返回一个包含每个元素平方值的列表。 3. filter()函数:filter()函数用于根据指定条件过滤可迭代对象中的元素,并返回一个新的可迭代对象。例如,filter(lambda x: x > 0, [-1, 0, 1, 2])将返回一个包含大于0的元素的列表。 4. reduce()函数:reduce()函数用于对可迭代对象中的元素行累积操作,并返回一个结果。需要先从`functools`模块导入。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4])将返回10,表示1+2+3+4。 5. zip()函数:zip()函数用于将多个可迭代对象的对应元素打包成元组,然后返回一个新的可迭代对象。例如,zip([1, 2, 3], ['a', 'b', 'c'])将返回[(1, 'a'), (2, 'b'), (3, 'c')]。 6. enumerate()函数:enumerate()函数用于为可迭代对象中的元素添加索引,并返回一个新的可迭代对象。例如,enumerate(['a', 'b', 'c'])将返回[(0, 'a'), (1, 'b'), (2, 'c')]。 7. sorted()函数:sorted()函数用于对可迭代对象行排序,并返回一个新的列表。例如,sorted([3, 1, 2])将返回[1, 2, 3]。 8. any()和all()函数:any()函数用于判断可迭代对象中是否存在至少一个为真的元素;all()函数用于判断可迭代对象中的所有元素是否都为真。例如,any([True, False, True])将返回True,而all([True, False, True])将返回False。 这些是Python函数的一些例子,它们可以帮助你更高效地编写代码,增加代码的灵活性和可读性。当然,还有很多其他的函数和技巧可以在Python文档和其他教程中学习到。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值