"""
function
函数的内容
定义函数名+参数+函数体+返回值
def funcName(elements):
funcBody
return
定义函数之后需要调用函数才可以使用函数。
"""
我是分割线
# 一个比较简单的函数例子
def sayHello():
print("Hello")
sayHello()
上面代码运行结果:
Hello
# 向函数传递信息
# 用到了函数的重载
def sayHello(name):
print(name + ",Hello")
sayHello("Mike")
上面代码运行结果:
Mike,Hello
# 带默认值的形参
def pet(name="Pluto"):
print("The pet's name is " + name)
pet()
pet("Bunny")
上面代码运行结果:
The pet’s name is Pluto
The pet’s name is Bunny
# 带多个参数的函数
def petDes(type, name):
print("The pet's type is " + type + ",its name is " + name + ".")
petDes("Dog", 'Pluto')
# 如果参数过多,顺序记不住时可以形参实参同时上送
# 参数可以多写并附加默认值,但是不可以少写。
petDes(name='Molly', type="dog")
上面代码运行结果:
The pet’s type is Dog,its name is Pluto.
The pet’s type is dog,its name is Molly.
# return 返回值
# 当需要函数返回一些内容,如字符串、列表、字典等
def returnName(firstName, lastName):
name = firstName.title() + " " + lastName.lower()
return name
print(returnName('mike', 'tang'))
上面代码运行结果
Mike tang
# 无限参数的实现
def people(name, *others):
print(name)
for other in others:
print(other)
print(others[2])
# people方法在读取参数的时候
# 将第一个实参赋值给name
# 将后面的实参全部填装进一个列表
# *others == others['23岁', '175CM', 'male']
people('张三', '23岁', '175CM', 'male')
上面代码运行结果:
张三
23岁
175CM
male
male
函数最大的优势就是复用。
函数最大的优势就是复用。
函数最大的优势就是复用。
# 将函数存储到模块中
# 也就是单独存储到一个py文件中
# 使用import 导入
# 绝对路径,相对路径
# as 别名
# 这里就不细讲了。
# 函数编写指南
# 驼峰命名法
# 形参默认值
# 下划线分割
# 多参数换行......