程序员文章、书籍推荐和程序员创业信息与资源分享平台

网站首页 > 技术文章 正文

Python 函数,一文掌握

hfteth 2025-03-13 15:47:47 技术文章 12 ℃

函数是编程中的一个基本概念,Python 是一种通用且广泛使用的编程语言,为使用函数提供了丰富的功能集。

Python 函数基础知识

1. 定义

在 Python 中,函数是执行特定任务的可重用代码块。可以使用关键字def定义函数,后跟函数名称和一对括号。函数体在定义下方缩进。

def greet():
    print("Hello, codeswithpankaj!")

2. 函数调用

定义函数后,可以使用其名称后跟括号来调用

greet()

输出:

Hello, codeswithpankaj!

3.参数

函数可以采用参数(输入)以使其更加灵活。在函数定义中,参数在括号内指定。

def greet_person(name):
    print("Hello, " + name + "!")

然后,可以在调用函数时将参数传递给该函数:

greet_person("Nishant")

例:

def greet_with_code(name, code):
    print(f"Hello, {name}! Your code, {code}, is awesome!")

# Example usage
name = "codeswithpankaj"
code = "123ABC"
greet_with_code(name, code)

4. 返回值

函数可以使用该语句返回值。

def add_numbers(a, b):
 return a + b

可以在调用函数时获得结果:

result = add_numbers(5, 3)
print(result)
 # 输出: 8

高级功能概念

1. 默认值

可以为函数参数提供默认值。这允许使用较少的参数调用函数,使用任何省略参数的默认值。

def greet_with_message(name, message="Good day!"):
    print("Hello, " + name + ". " + message)

现在,可以在提供或不提供自定义消息的情况下调用该函数:

greet_with_message("Bob")
# Output: Hello, Bob. Good day!

greet_with_message("Alice", "How are you?")
# Output: Hello, Alice. How are you?

2 变量作用域

在函数中定义的变量具有局部作用域,这意味着它们只能在该函数中访问。在任何函数之外定义的变量都具有全局作用域。

global_variable = "I am global"

def local_scope_function():
    local_variable = "I am local"
    print(global_variable)  # Accessing global variable
    print(local_variable)   # Accessing local variable

local_scope_function()

# This would raise an error since local_variable is not accessible here
# print(local_variable)

3. Lambda 函数

Lambda 函数(也称为匿名函数)是简洁的单行代码。它是使用关键字lambda定义的。

multiply = lambda x, y: x * y
print(multiply(3, 4)) # 输出: 12

Lambda 函数通常用于短期的小型操作。

4. 递归函数

函数可以调用自身,这称为递归。这种技术对于解决可以分解为更简单、相似的子问题的问题特别有用。

def factorial(n):
    if n == 0 or n == 1: 
        return 1 else:
  
 
 return n * factorial(n -  1 )

5. 装饰器

装饰器是 Python 中一项强大而高级的功能。它们允许修改或扩展函数的行为,而无需更改其代码。装饰器是使用语法@decorator定义的。

def uppercase_decorator(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result.upper()
    return wrapper

@uppercase_decorator
def greet():
    return "hello, world!"

print(greet())  # Output: HELLO, WORLD!

示例:GST计算器使用功能

def calculate_gst(original_amount, gst_rate):
    """
    Calculate the total amount including GST.

    Parameters:
    - original_amount (float): The original amount before GST.
    - gst_rate (float): The GST rate as a percentage.

    Returns:
    float: The total amount including GST.
    """
    gst_amount = (original_amount * gst_rate) / 100
    total_amount = original_amount + gst_amount
    return total_amount

def main():
    # Example usage
    original_amount = float(input("Enter the original amount: "))
    gst_rate = float(input("Enter the GST rate (%): "))

    total_amount = calculate_gst(original_amount, gst_rate)

    print(f"Original Amount: ${original_amount:.2f}")
    print(f"GST Rate: {gst_rate:.2f}%")
    print(f"Total Amount (including GST): ${total_amount:.2f}")

# Run the program
if __name__ == "__main__":
    main()

以下是该程序的工作原理:

  1. 该函数将calculate_gstoriginal_amount 作为参数,计算 GST 金额,将其添加到原始金额中,然后返回总金额。gst_rate
  2. main函数提示用户输入原始金额和 GST 税率,调用calculate_gst函数,然后打印原始金额、GST 税率和总金额(包括 GST)。
  3. main程序的结构是在直接执行时运行的。它调用函数来启动 GST 计算。

运行示例:

Enter the original amount: 100
Enter the GST rate (%): 18
Original Amount: $100.00
GST Rate: 18.00%
Total Amount (including GST): $118.00

最近发表
标签列表