python学习之路---函数

本文详细介绍了Python函数的使用,包括定义函数、传递实参(位置实参、关键字实参、默认值)、返回值、处理列表、传递任意数量的实参(位置和关键字)以及将函数存储在模块中。还探讨了如何防止函数修改列表,展示了如何结合使用函数和while循环。此外,还展示了如何通过*和**操作符接收任意数量的位置和关键字实参。
摘要由CSDN通过智能技术生成


一、 定义函数

定义一个函数,并且调用它。

def greet_user():
    print("hello")

greet_user()

向函数传递信息

def greet_user(name):
    print(f"hello {name}")
greet_user('hh')

二、传递实参

位置实参

要求实参的顺序和形参的顺序一致

def describe_pet(animal_type,pet_name):
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet('hamster','harry')

关键字实参

def describe_pet(animal_type,pet_name):
    print(f"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")

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

此时实参的顺序就没有关系了

默认值

使用此种方式时,默认值的变量要放后面,没被指定默认值的变量要放前面。

def describe_pet(pet_name,animal_type='dog'):
    print(f"My {animal_type}'s name is {pet_name.title()}.")

describe_pet(pet_name='harry')

三、返回值

通过return语句返回函数值

返回简单值

def get_formatted_name(first_name,last_name):
    full_name = f"{first_name} {last_name}"
    return full_name.title()
musician = get_formatted_name('jimi','hendrix')
print(musician)

让参数变成可选

实现手段是添加默认值,因此并不是新的东西。
当要实现有中间名和没有中间名都能够输出全名的要求,我们在构造函数的时候就要对中间名给出默认值

def get_formatted_name(first_name,middle_name,last_name):
    full_name = f"{first_name} {middle_name} {last_name}"
    return full_name.title()
musician = get_formatted_name('john','lee','hooker')
print(musician)
def get_formatted_name(first_name,last_name,middle_name=''):
    full_name = f"{first_name} {middle_name} {last_name}"
    if middle_name:
        full_name = f"{first_name} {middle_name} {last_name}"
    else:
        full_name = f"{first_name} {last_name}"
    return full_name.title()
musician = get_formatted_name('john','hooker')
print(musician)

返回字典

def build_person(first_name,last_name):
    person = {'first':first_name,'last':last_name}
    return person
musician = build_person('jimi','hendrix')
print(musician)

在这里插入图片描述

结合使用函数和while循环

def get_formatted_name(first_name,last_name):
    full_name = f"{first_name} {last_name}"
    return full_name.title()
while True:
    print('\nplease tell me your name:')
    f_name = input('first_name:')
    l_name = input('last_name:')

    formatted_name = get_formatted_name(f_name,l_name)
    print(f"\nHello,{formatted_name}!")

四、传递列表

# 将列表作为实参传递给函数
def greet_users(names):
    for name in names:
        msg = f"hello,{name.title()}"
        print(msg)
usernames = ['hannah','try','margot']
greet_users(usernames)

在函数中修改列表

在函数中对列表的修改都是永久性的,这样就可以高效的处理大量数据

unprinted_designs = ['phone case','robot pendant','dodecahedron']
completed_models = []
while unprinted_designs:
    current_design = unprinted_designs.pop()
    print(f"printing model:{current_design}")
    completed_models.append(current_design)
print("\nthe following models have been printed")
for completed_model in completed_models:
    print(completed_model)
def printed_models(unprinted_designs,completed_models):
    """ 模拟打印每个设计,直到没有未打印的设计为止"""
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"printing model:{current_design}")
        completed_models.append(current_design)
def show_completed_models(completed_models):
    print("\nthe following models have been printed")
    for completed_model in completed_models:
        print(completed_model)
unprinted_designs = ['phone case','robot pendant','dodecahedron']
completed_models = []
printed_models(unprinted_designs,completed_models)
show_completed_models(completed_models)

禁止函数修改列表

通过传一份副本给形参,保证了实参列表不被修改。

def printed_models(unprinted_designs,completed_models):
    """ 模拟打印每个设计,直到没有未打印的设计为止"""
    while unprinted_designs:
        current_design = unprinted_designs.pop()
        print(f"printing model:{current_design}")
        completed_models.append(current_design)
def show_completed_models(completed_models):
    print("\nthe following models have been printed")
    for completed_model in completed_models:
        print(completed_model)
unprinted_designs = ['phone case','robot pendant','dodecahedron']
completed_models = []
printed_models(unprinted_designs[:],completed_models)
show_completed_models(completed_models)
print(unprinted_designs)

五、传递任意数量的实参

# 通过形参*variable可以接收任意数量的实参,
# *variable实际上就是一个元组

def make_pizza(*toppings):
    print(toppings)
make_pizza("pepperoni")
make_pizza("mushrooms",'green peppers','extra cheese')
# 输出元组

结合使用位置实参和任意数量实参

先接受位置实参,任意数量实参放在最后

# 函数定义时,位置形参放前面,任意数量形参放最后
def make_pizza(size,*toppings):
    print(f"\nmaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
         print(topping)
make_pizza(12,"pepperoni")
make_pizza(16,"mushrooms",'green peppers','extra cheese')

使用任意数量的关键字实参

通过**variable接收关键字实参,可以任意多,但是函数定义时要放在最后

def build_profile(first,last,**user_info):
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info
user_profile = build_profile('albert','einstein',location = 'princeton',field = 'physics')

print(user_profile)

六、将函数存储在模块中

函数存储在模块中可以隐藏细节,还能让其他人共用这个函数。

# pizza.py
def make_pizza(size,*toppings):
    print(f"\nmaking a {size}-inch pizza with the following toppings:")
    for topping in toppings:
         print(topping)
# 引用pizza.py的程序。
from charpter8 import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(13,'a','b','c')

起别名的操作较简单不在代码中进行展示。


总结

python函数总结。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值