# python函数可分为内置函数和自定义函数 # 可在模块中但在类之外定义,作用域是当前模块,称之函数; # 在函数中定义称为嵌套函数 # 在类中定义称为方法 # 语法格式: # def 函数名(形式参数列表): # 函数体 # return返回值 (没有返回值可以省略return语句) # 定义函数时的参数为形式参数,调用函数时传递的实际参数为实参 # 调用函数时传递的实参要和定义函数时的形参顺序一致 # 调用函数时也可采用“关键字=实参”的形式 # 定义函数love() def love(): print("想你的心好苦") # 调用函数love() love() # 位置传参,形参和实参顺序一致 def rect_area(width,height): area = width * height return area r_area = rect_area(320,480) print("{0} x {1} 长方形的面积是:{2:.2f}".format(320,480,r_area)) # 关键字=实参 def area(a,b,c): p = (a b c) / 2 s = (p * (p-a) * (p-b) * (p-c)) ** 0.5 return s s = area(a = 3, c = 5,b = 4) print('三角形面积为:%0.2f'%s) # 默认传参 def ScommodityPrice(commodity,price = 155): print("今日新品:",commodity) print("价格是:",price) ScommodityPrice("三文鱼") ScommodityPrice("鲍鱼") ScommodityPrice("澳洲龙虾",280) ScommodityPrice("小龙虾") # 不定长传参 # 默认传参,把数据放到元组里,成为元组的数据(index) def scommdity(prname,*other): print(prname) print(other) scommdity("华为P50","骁龙888 4G","8GB","HarmonyOS 2","128GB","5000万像素","1300万像素") scommdity("戴尔3000","intel i7","Windows","1TB-2TB","16GB") # 字典方式 关键字传参 def scommdity(prname,**other): print(prname) print(other) scommdity("华为P50",处理器 = "骁龙888 4G",运行内存 = "8GB",系统 = "HarmonyOS 2",机身内存 = "128GB") scommdity("戴尔3000",处理器 = "intel i7",系统 = "Windows",硬盘容量 = "1TB-2TB",内存容量 = "16GB") # 以上实例说明函数是单一的,组织好的可以重复使用的以英文的冒号开始,现在小编就来说说关于python自定义函数入门教程?下面内容希望能帮助到你,我们来一起看看吧!

python自定义函数入门教程(也说说python自定义函数)

python自定义函数入门教程

# python函数可分为内置函数和自定义函数 # 可在模块中但在类之外定义,作用域是当前模块,称之函数; # 在函数中定义称为嵌套函数 # 在类中定义称为方法 # 语法格式: # def 函数名(形式参数列表): # 函数体 # return返回值 (没有返回值可以省略return语句) # 定义函数时的参数为形式参数,调用函数时传递的实际参数为实参 # 调用函数时传递的实参要和定义函数时的形参顺序一致 # 调用函数时也可采用“关键字=实参”的形式 # 定义函数love() def love(): print("想你的心好苦") # 调用函数love() love() # 位置传参,形参和实参顺序一致 def rect_area(width,height): area = width * height return area r_area = rect_area(320,480) print("{0} x {1} 长方形的面积是:{2:.2f}".format(320,480,r_area)) # 关键字=实参 def area(a,b,c): p = (a b c) / 2 s = (p * (p-a) * (p-b) * (p-c)) ** 0.5 return s s = area(a = 3, c = 5,b = 4) print('三角形面积为:%0.2f'%s) # 默认传参 def ScommodityPrice(commodity,price = 155): print("今日新品:",commodity) print("价格是:",price) ScommodityPrice("三文鱼") ScommodityPrice("鲍鱼") ScommodityPrice("澳洲龙虾",280) ScommodityPrice("小龙虾") # 不定长传参 # 默认传参,把数据放到元组里,成为元组的数据(index) def scommdity(prname,*other): print(prname) print(other) scommdity("华为P50","骁龙888 4G","8GB","HarmonyOS 2","128GB","5000万像素","1300万像素") scommdity("戴尔3000","intel i7","Windows","1TB-2TB","16GB") # 字典方式 关键字传参 def scommdity(prname,**other): print(prname) print(other) scommdity("华为P50",处理器 = "骁龙888 4G",运行内存 = "8GB",系统 = "HarmonyOS 2",机身内存 = "128GB") scommdity("戴尔3000",处理器 = "intel i7",系统 = "Windows",硬盘容量 = "1TB-2TB",内存容量 = "16GB") # 以上实例说明函数是单一的,组织好的可以重复使用的。以英文的冒号开始。

,