网站首页 > 技术文章 正文
函数是编程中的一个基本概念,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()
以下是该程序的工作原理:
- 该函数将calculate_gst 和original_amount 作为参数,计算 GST 金额,将其添加到原始金额中,然后返回总金额。gst_rate
- main函数提示用户输入原始金额和 GST 税率,调用calculate_gst函数,然后打印原始金额、GST 税率和总金额(包括 GST)。
- 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
- 上一篇: 使用Python获取某网站基金实时估值
- 下一篇: 高阶Python|返回类型提示技巧 (1)
猜你喜欢
- 2025-03-13 python基础函数
- 2025-03-13 Python 中的海象运算符 (:=)
- 2025-03-13 AI 编程指南
- 2025-03-13 有趣的Swift特性之:多个返回值
- 2025-03-13 2-Python注释
- 2025-03-13 python中zip()函数
- 2025-03-13 Python | range()详解
- 2025-03-13 高阶Python|返回类型提示技巧 (1)
- 2025-03-13 使用Python获取某网站基金实时估值
- 2025-03-13 9-Python自定义函数
- 265℃Python短文,Python中的嵌套条件语句(六)
- 264℃python笔记:for循环嵌套。end=""的作用,图形打印
- 263℃PythonNet:实现Python与.Net代码相互调用!
- 259℃Python实现字符串小写转大写并写入文件
- 257℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 117℃原来2025是完美的平方年,一起探索六种平方的算吧
- 98℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 90℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)