湖南建设监理员报名网站,windows2008 网站部署,外贸产品推广网站,金华市建设局网站职称函数
初识函数
函数#xff1a;封装具有某种功能的代码块。
函数定义
使用def关键字来定义函数 # 定义函数 def 函数名(): 代码块 # 调用函数 函数名() 函数参数 def 函数名(形参) 代码块 # 调用 函数名(实参) 位置参数
按参数顺序传参 def func(a, b): print(a b)…函数
初识函数
函数封装具有某种功能的代码块。
函数定义
使用def关键字来定义函数 # 定义函数 def 函数名(): 代码块 # 调用函数 函数名() 函数参数 def 函数名(形参) 代码块 # 调用 函数名(实参) 位置参数
按参数顺序传参 def func(a, b): print(a b) func(1,2) 关键字参数
通过参数名指定值不用关心参数的顺序 def func1(name, age): print(fMy name is {name}.I am {age} years old.) func1(age18, name17Lin) 不定长参数
单星号参数(*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(name17Lin, age18, num17) 函数返回值
基本返回值
在Python中函数的返回值是函数执行后提供的输出结果。函数通过return语句来指定其返回值。当函数执行到return语句时它会立即停止执行并将紧跟在return后面的表达式的值作为结果返回给调用者。如果没有return语句或者return后面没有跟任何表达式则函数默认返回None。 def add(a, b): return a b print(add(1, 5)) 多返回值
Python中的一个函数实际上可以返回多个值这些值会被打包成一个元组。 def calculate(x): square x ** 2 cube x ** 3 return square, cube square, cube calculate(5) print(fsquare:{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 20 modify_global() print(x) # 输出20 nonlocal非局部变量也称为“闭包变量” def outer(): y 10 def inner(): nonlocal y # 声明y为非局部变量 y 20 inner() 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))