Python:函数

Python中的函数是执行特定任务的代码块,具有可重用性和模块化的特点。以下是Python函数的一些基础概念和用法:

1. **定义函数**:

  使用`def`关键字后跟函数名和括号内的参数列表来定义函数。

  ```python

  def my_function(param1, param2):

      # 函数体

      return param1 + param2

  ```

2. **调用函数**:

  通过函数名和括号内的参数来调用函数。

  ```python

  result = my_function(5, 10)

  ```

3. **参数和返回值**:

  函数可以接收参数,并使用`return`关键字返回值。

4. **默认参数值**:

  在定义函数时,可以为参数指定默认值。

  ```python

  def greet(name, message="Hello"):

      return f"{message}, {name}!"

  ```

5. **可变参数**:

  使用星号(`*`)定义可变数量的位置参数,使用双星号(`**`)定义可变数量的关键字参数。

  ```python

  def make_pizzas(*toppings):

      print("Making pizza with the following toppings:")

      for topping in toppings:

          print(f" - {topping}")

  make_pizzas('mushrooms', 'green peppers', 'extra cheese')

  ```

6. **函数注解**:

  使用注解可以指定函数参数的类型和返回值的类型,有助于代码的可读性和静态类型检查。

  ```python

  def divide(x: float, y: float) -> float:

      return x / y

  ```

7. **作用域**:

  Python中的变量有自己的作用域,包括局部(local)、嵌套(enclosed)和全局(global)。

8. **闭包**:

  闭包是定义在函数内部的函数,可以记住并访问外部函数的作用域。

  ```python

  def outer_function(x):

      def inner_function():

          print(x)

      return inner_function

  result = outer_function(5)

  result()  # 输出 5

  ```

9. **装饰器**:

  装饰器是Python中的一个高级功能,用于修改或增强函数的行为。

  ```python

  def my_decorator(func):

      def wrapper():

          print("Something is happening before the function is called.")

          func()

          print("Something is happening after the function is called.")

      return wrapper

  @my_decorator

  def say_hello():

      print("Hello!")

  say_hello()

  ```

10. **匿名函数(Lambda)**:

    使用`lambda`关键字可以创建匿名函数,通常用于需要简短函数的地方。

    ```python

    add = lambda x, y: x + y

    print(add(5, 3))  # 输出 8

    ```

11. **生成器**:

    使用`yield`关键字可以创建生成器,它是一种特殊的迭代器,用于惰性计算。

    ```python

    def count_up_to(max):

        count = 1

        while count <= max:

            yield count

            count += 1

    for number in count_up_to(5):

        print(number)

    ```

Python的函数功能非常强大,支持多种编程范式,包括面向对象、函数式编程等。函数是Python编程中不可或缺的一部分,掌握函数的使用对于编写高效、可维护的代码至关重要。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大连赵哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值