Python3函数定义、调用、作用及传参方式详解
发表时间: 2023-07-11 19:43
示例
# 定义函数def greet(name): print("Hello, " + name + "!")# 调用函数greet("Alice") # 输出:Hello, Alice!
# 位置参数def add(x, y): return x + y# 默认参数def greet(name, msg="Hello"): print(msg + ", " + name + "!")# 可变参数def multiply(*args): result = 1 for num in args: result *= num return result# 关键字参数def print_info(**kwargs): for key, value in kwargs.items(): print(key + ": " + value)# 命名关键字参数def person_info(name, age, *, city, job): print(name, age, city, job)# 返回值def square(x): return x ** 2# 调用函数add(3, 5) # 输出:8greet("Alice") # 输出:Hello, Alice!multiply(2, 3, 4) # 输出:24print_info(name="Bob", age="30") # 输出:name: Bob, age: 30person_info("Alice", 25, city="New York", job="Engineer") # 输出:Alice 25 New York Engineerresult = square(4) # result 变量的值为 16
示例:
def greet(name): message = "Hello, " + name + "!" print(message)greet("Alice") # 输出:Hello, Alice!# 在函数外部访问 message 变量将会引发 NameError 错误
示例
def greet(name, age): print("Hello, " + name + "! You are " + str(age) + " years old.")greet("Alice", 25) # 输出:Hello, Alice! You are 25 years old.greet(age=30, name="Bob") # 输出:Hello, Bob! You are 30 years old.
参数解构:在函数调用时,可以使用*和**对可迭代对象进行解构,将元素传递给函数。
示例
def greet(name, age): print("Hello, " + name + "! You are " + str(age) + " years old.")person = ("Alice", 25)greet(*person) # 输出:Hello, Alice! You are 25 years old.info = {"name": "Bob", "age": 30}greet(**info) # 输出:Hello, Bob! You are 30 years old.
作用域是变量在程序中的可见性和生命周期。Python中有以下作用域:
def my_func(): local_var = "I am a local variable" print(local_var)global_var = "I am a global variable"my_func() # 输出:I am a local variableprint(global_var) # 输出:I am a global variable# 尝试访问局部变量print(local_var) # 引发 NameError 错误