Python学习之Part06.函数初识

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值