python function函数

 

位置实参

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"\nI have a {animal_type}.")
    print(f"My {animal_type}'s name is {pet_name.title()}.")


describe_pet(pet_name='willie')

 

有返回值的函数

def sum(a, b):
    return a+b


print(sum(2, 5))

输出:7

 

有返回值 且有默认值参数 的函数

复制代码
def get_formatted_name(first_name, last_name, middle_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('jimi', 'hendrix')
print(musician)

musician = get_formatted_name('john', 'hooker', 'lee')
print(musician)
复制代码

 

返回一个字段,并可根据age的实际情况来决定是否添加 这个对键值

复制代码
def build_person(first_name, last_name, age=None):             #可将None视为占位值。在if条件测试中,None相当于False
    """返回一个字典,其中包含有关一个人的信息。"""
    person = {'first': first_name, 'last': last_name}
    if age:
        person['age'] = age  
    return person

musician
= build_person('jimi', 'hendrix') print(musician)
输出:{'first': 'jimi', 'last': 'hendrix'}

musician = build_person('jimi', 'hendrix', 30) print(musician)
输出:{'first': 'jimi', 'last': 'hendrix', 'age': 30}
复制代码

 

 

结合使用函数和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', 'ty', 'margot']
greet_users(usernames)
复制代码

 

在函数中修改列表

复制代码
def print_models(unprinted_designs, completed_models):
    """
   模拟打印每个设计,直到没有未打印的设计为止。
   打印每个设计后,都将其移到列表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 = []

print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)
复制代码

 

禁止函数修改列表

如上例子中修改为:

print_models(unprinted_designs[:], completed_models)   #以切片的方法来传递一个列表的副本,但是对于庞大的列表数据 慎用

 

 

 

传递任意数量的实参    *msg   单*表示一个元祖

形参名  *msg  中的星号让Python创建一个名为 msg 的空元组,并将收到的所有值都封装到这个元组中。函数体内的函数调用print()通过生成输出,证明Python能够处理使用一个值来调用函数的情形,也能处理使用三个值来调用函数的情形。它以类似的方式处理不同的调用。注意,Python将实参封装到一个元组中,即便函数只收到一个值

复制代码
def show_message(*msgs):

    for msg in msgs:

        print(f"--{msg}")


show_message('a')

show_message('a', 'b', 'c')
复制代码

 

 

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

如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中

复制代码
def show_message(size, *msgs):
    print(f"\nMaking a {size}-inch pizza with the following toppings:")
    for msg in msgs:

        print(f"--{msg}")


show_message(20, 'a')
show_message(30, 'a', 'b', 'c')

输出:

Making a 20-inch pizza with the following toppings:
--a

Making a 30-inch pizza with the following toppings:
--a
--b
--c

复制代码

 

 

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

** user_info     双* 表示一个字典

函数build_profile()的定义要求提供名和姓,同时允许根据需要提供任意数量的名称值对。形参**user_info中的两个星号让Python创建一个名为user_info的空字典,并将收到的所有名称值对都放到这个字典中。在这个函数中,可以像访问其他字典那样访问user_info中的名称键值对。

复制代码
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)
复制代码

 

 作业1:

def food(*a):
    print(f"\nyour's food is :")
    for foods in a:
        print(f'\t--{foods}')


food('b')
food('b', 'c', 'd', 'e')

 

作业2:

复制代码
def build_profile(first, last, **user_info):
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info


a = build_profile('zhang', 'san', like='games', job='singe', mobile='phone',age=23 )
print(a)

输出:{'like': 'games', 'job': 'singe', 'mobile': 'phone', 'age': 23, 'first_name': 'zhang', 'last_name': 'san'}
复制代码

 

 将函数存储在模块中

使用函数的优点之一是可将代码块与主程序分离。通过给函数指定描述性名称,可让主程序容易理解得多。你还可以更进一步,将函数存储在称为模块的独立文件中,再将模块导入到主程序中import语句允许在当前运行的程序文件中使用模块中的代码。

 

※ 导入整个模块

在同级别目录中创建了一个build_profile()的函数,保存在了function.py的页面中,如下就是调用该函数方法的例子 ,就可在程序中使用该模块中的所有函数

function.py

def build_profile(first, last, **user_info):
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info

 

index.py

import function

a = function.build_profile(
    'zhang', 'san', like='games', job='singe', mobile='phone', age=23)

print(a)

 

 

※ 导入特定的函数

导入模块中的特定函数,这种导入方法的语法如下:

from module_name import function_name

 

用上面的例子来导入一个函数

from function import build_profile

a = build_profile(
    'zhang', 'san', like='games', job='singe', mobile='phone', age=23)
print(a)

 

使用as给函数指定别名

from module_name import function_name as fn

 

下面给函数build_profile()指定了别名bp()。这是在import语句中使用make_pizza as mp实现的,关键字as将函数重命名为指定的别名:

from function import build_profile as bp

a = bp(
    'zhang', 'san', like='games', job='singe', mobile='phone', age=23)
print(a)

 

使用as给模块指定别名

还可以给模块指定别名。通过给模块指定简短的别名(如给模块pizza指定别名p),让你能够更轻松地调用模块中的函数。相比于pizza.make_pizza(),p.make_pizza()更为简洁:

import pizza as p

p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

 

 

导入模块中的所有函数

使用星号(*)运算符可让Python导入模块中的所有函数

from module_name import *

  最好不要采用这种导入方法。这是因为如果模块中有函数的名称与当前项目中使用的名称相同,可能导致意想不到的结果:Python可能遇到多个名称相同的函数或变量,进而覆盖函数,而不是分别导入所有的函数。

 

 

函数编写指南

形参指定默认值时,等号两边不要有空格:

def function_name(parameter_0, parameter_1='default value')

 

五中引入模块的方法

import module_name
from module_name import function_name
from module_name import function_name as fn
import module_name as mn
from module_name import *

 

 

 

 

 

posted @   茶叶蛋蛋  阅读(340)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示