函数,模块,模块包
1.函数
为了简化编程工作量和代码结构,可提取编程时重复使用的类似代码,将其定义为一个函数
#定义函数格式:
——————————————————
def 函数名(参数表):
函数体
return 返回值
#函数的参数
- 必需参数
例1:
def hello(a):
print(“hello”,a)
hello (“python”)
例2:
def hello(a):
print(“hello”,a)
hello()
<TypeError: hello() missing 1 required positional argument: ‘a’>
#required argument实参(实际参数,如:“python”) parameter形参(a)
2)默认参数
例1:
def add(a,b = 1): #注意必需参数写在前,默认参数写在后
print(a + b)
add(1)
<2> #只输入一个参数时,优先赋值给必需参数
例2:
def add(a,b = 1):
print(a + b)
add(1,2)
<3> #1,2按顺序赋值给a,b
3)关键字参数
def show_person(name=“姓名”,age=“年龄”):
print(name,age)
show_person(“张三”,“30”) #可利用