函数
初识函数
函数:封装具有某种功能的代码块。
函数定义
使用def关键字来定义函数
# 定义函数
def 函数名():
代码块
# 调用函数
函数名()
函数参数
def 函数名(形参)
代码块
# 调用
函数名(实参)
-
位置参数
按参数顺序传参
def func(a, b):
print(a + b)
func(1,2)
-
关键字参数
通过参数名指定值,不用关心参数的顺序
def func1(name, age):
print(f"My name is {name}.I am {age} years old.")func1(age=18, name="17Lin")
-
不定长参数
单星号参数(*args):用于接收任意数量的非关键字参数,这些参数被收集到一个元组中。
def sum_numbers(*args):
total = sum(args)
print(total)sum_numbers(1, 2, 3, 4, 5, 6)
双星号参数(**kwargs):用于接收任意数量的关键字参数,这些参数被收集到一个字典中。
def print_info(**kwargs):
print(kwargs)print_info(name="17Lin", age=18, num=17)
函数返回值
基本返回值
在Python中,函数的返回值是函数执行后提供的输出结果。函数通过return
语句来指定其返回值。当函数执行到return
语句时,它会立即停止执行,并将紧跟在return
后面的表达式的值作为结果返回给调用者。如果没有return
语句,或者return
后面没有跟任何表达式,则函数默认返回None
。
def add(a, b):
return a + bprint(add(1, 5))
多返回值
Python中的一个函数实际上可以返回多个值,这些值会被打包成一个元组。
def calculate(x):
square = x ** 2
cube = x ** 3
return square, cubesquare, cube = calculate(5)
print(f"square:{square} , cube:{cube}.")
无返回值
如果函数没有明确的return
语句,或者return
后没有跟随任何表达式,那么函数将返回None
。
def print_func(name):
print(name)print_func(print_func("17Lin")) # 输出None
作用域
作用域(Scope)在编程语言中是指程序中的某个区域,其中变量、函数或其他命名实体的有效性和可访问性是受限的。
-
局部作用域(Local Scope):
-
在函数内部定义的变量(包括函数参数)具有局部作用域,这意味着它们仅在该函数内部可见,并且在函数调用结束后,这些变量的生命周期也随之结束。局部作用域中的变量不能被函数外部直接访问。
-
-
全局作用域(Global Scope):
-
在函数外部定义的变量,或者使用
global
关键字声明的变量具有全局作用域。全局变量在整个模块中都是可见的,无论在哪个函数内,只要没有同名的局部变量覆盖,都可以访问和修改全局变量。
-
-
嵌套作用域(Enclosing Scope / Nonlocal Scope):
-
在函数内部定义的嵌套函数(即一个函数内部定义另一个函数)的情况下,可能出现嵌套作用域。在这种情况下,嵌套函数可以访问其外部函数(也称为封闭函数)中的变量,但不直接属于全局作用域。若想在嵌套函数中修改封闭函数的变量,需要使用
nonlocal
关键字声明。
-
global全局关键字
x = 10 # 全局变量
def modify_global():
global x # 声明为全局变量
x = 20modify_global()
print(x) # 输出:20
nonlocal非局部变量(也称为“闭包变量”)
def outer():
y = 10def inner():
nonlocal y # 声明y为非局部变量
y = 20inner()
print(y)outer()
代码练习
- 题目:字符串转驼峰命名编写一个名为 to_camel_case 的函数,它接受一个空格分隔的单词串作为参数,返回转换为驼峰命名格式的字符串。例如,“hello world hello python”应转换为“helloWorldHelloPython”。
def to_camel_case(words):if not words:return ""word = words.split()new_words = word[0].lower()for w in word[1:]:new_words += w[0].upper() + w[1:]return new_wordsprint(to_camel_case("hello world hello python"))
- 题目:递归阶乘计算编写一个名为calculated_factorial的递归函数,计算并返回一个正整数的阶乘。
def calculated_factorial(n):sum = 0if n == 1:return 1else:sum += n * calculated_factorial(n - 1)return sumprint(calculated_factorial(10))