1.函数基本使用
1.定义函数
def print_hello():
print('hello')
2.调用函数:通过函数名来调用
print_hello()
输出结果:
2.函数的嵌套
def hello():
print('hello')
def python():
print('python')
hello()
此函数的输出结果是hello,则pytho()子函数没有执行
def hello():
print('hello')
def python():
print('python')
# 在函数中定义的子函数,必须在函数中进行调用.
python()
hello()
输出结果为:
hello
pyhton
3.参数
python中一切皆对象,函数中传递的是对象的引用
1.形参/实参:
# 在定义函数时需要的变量.称为形参(形参名任意)
def hello(a):
print('hello', a)
# 在调用函数时传递的参数称为实参
hello('python')
输出结果:
hello pyhton
4.形参详细说明
形参的类型有:位置参数, 默认参数,可变参数, 关键字参数
1.位置参数: 即形参和实参的位置一 一对应
def info(name, age):
print('Name:', name)
print('age:', age)
# 调用
info('hello', 18)
输出结果为:
Name: hello
age: 18
# 调用
info(18, 'hello')
输出结果为:
Name: 18
age: hello
# 调用
info(name='python', age=19)
输出结果为:
Name: python
age: 19
2.默认参数: 当无实参传递时,则使用默认参数;当有参数传递时,则使用实参
def my_pow(x, y=2):
print(x ** y)
my_pow(2)
输出结果为: 4
my_pow(2, 5)
输出结果为:32
3.可变参数:可以接受多个参数传递
# args是一个新的引用(类似一个数组指针,指向一个指针数组,指针数组中存贮的指针指向原实参中的元素)
def my_sum(*a