Python中的函数-01

07-1函数.py

def greet_user():  # 使用def 来定义一个函数
    print('hello')  # 函数内做的事情,打印hello


greet_user()  # 函数调用


运行结果:
/usr/local/bin/python3.7 /Users/luoye/Desktop/SUM_PROJECTS/Sum_Code/python_code/07-1函数.py
hello

Process finished with exit code 0

07-2向函数传递参数.py

def greet_user(username):   # username 是形参 是变量  jesse传递到username这个变量里面存起来等待被使用
    """显示简单的问候语"""
    print("Hello," + username.title() + "!")


greet_user('jesse') # jesse 是实参


运行结果:
/usr/local/bin/python3.7 /Users/luoye/Desktop/SUM_PROJECTS/Sum_Code/python_code/07-2向函数传递参数.py
Hello,Jesse!

Process finished with exit code 0

07-3位置实参.py

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")


describe_pet('hamster','harry')
# 调用函数多次
describe_pet('dog', 'willie')


运行结果:
/usr/local/bin/python3.7 /Users/luoye/Desktop/SUM_PROJECTS/Sum_Code/python_code/07-3位置实参.py

I have a hamster.
My hamster's name is Harry.

I have a dog.
My dog's name is Willie.

Process finished with exit code 0

07-4关键字实参.py

def describe_pet(animal_type, pet_name):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")


describe_pet(animal_type='hamster',pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster')
# 注意:使用关键字实参时,务必准确地指定函数定义中的形参名。


运行结果:
/usr/local/bin/python3.7 /Users/luoye/Desktop/SUM_PROJECTS/Sum_Code/python_code/07-4关键字实参.py

I have a hamster.
My hamster's name is Harry.

I have a hamster.
My hamster's name is Harry.

Process finished with exit code 0

07-5 关键字实参&位置实参的默认值参数 .py

def describe_pet(pet_name,animal_type='dog'):
    """显示宠物的信息"""
    print("\nI have a " + animal_type + ".")
    print("My " + animal_type + "'s name is " + pet_name.title() + ".")

# animal_type设置了默认值,不给参数,就使用默认的参数
# 在这个函数的定义中,修改了形参的排列顺序。由于给animal_type指定了默认值,
# 无需通过实参来指定动物类型,因此如果函数调用中只包含宠物的名字,这个实参将关联到函数定义中的第一个形参。
# 这就是需要将pet_name放在形参列表开头的原因所在。


describe_pet(pet_name='willie')
describe_pet(animal_type='hamster',pet_name='harry')


运行结果:
/usr/local/bin/python3.7 "/Users/luoye/Desktop/SUM_PROJECTS/Sum_Code/python_code/07-5 关键字实参&位置实参的默认值参数 .py"

I have a dog.
My dog's name is Willie.

I have a hamster.
My hamster's name is Harry.

Process finished with exit code 0

学习小结:函数是带名字的代码块,用于完成具体的工作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值