python中函数的定义与使用

本文详细介绍了Python函数的使用,包括函数定义、实参传递(位置实参、关键字实参、默认值)、返回值(返回简单值、可选参数、返回复杂数据结构)、列表操作(在函数中修改列表及防止修改)以及处理任意数量实参的方法。同时,讲解了如何将函数存储在模块中并进行导入,包括导入整个模块、导入特定函数、给函数指定别名以及导入模块中的所有函数。
摘要由CSDN通过智能技术生成

1、函数的定义

greet_user为函数名,username为形参,melody为实参

def greet_user(username):
    print("Hello, "+username.title()+"!")
    
greet_user('melody')

在这里插入图片描述

2、传递实参

2.1 位置实参

你调用函数时,python必须将函数调用的每个实参都关联到函数定义中的一个形参。
最简单的关联方式是基于实参的顺序,这种关联方式为位置实参
所以位置实参实参的顺序很重要。

def greet_user(username,location):
    print(username.title()+" is from "+location.title()+".")
    
greet_user('melody','china')

在这里插入图片描述

2.2 关键字实参

关键字实参是传递给函数的名称-值对。在实参中直接将名称和值关联起来,所以无需考虑函数调用中的实参顺序。

def greet_user(username,location):
    print(username.title()+" is from "+location.title()+".")
    
greet_user(username='melody',location='china')

在这里插入图片描述

def greet_user(username,location):
    print(username.title()+" is from "+location.title()+".")
    
greet_user(location='china',username='melody')

在这里插入图片描述

2.3 默认值

编写函数时,可以给每个形参指定默认值。
在调用函数时,若给形参提供了实参,python将使用指定的形参值;否则,使用默认值。

def greet_user(username,location='china'):
    print(username.title()+" is from "+location.title()+".")
    
greet_user('melody')

在这里插入图片描述

3、返回值

函数返回的值称为返回值;
在函数中,可以使用return语句将值返回到调用函数的代码行。

3.1 返回简单值

def get_fullname(firstname,lastname):
    fullname=firstname+' '+lastname
    return fullname.title()

person_fullname=get_fullname('cao','lu')
print(person_fullname)

在这里插入图片描述

3.2 让实参变为可选的

def get_fullname(firstname,lastname,middlename=''):
    if middlename:
        fullname=firstname+' '+middlename+' '+lastname
    else:
        fullname=firstname+' '+lastname
    return fullname.title()

person_fullname=get_fullname('cao','lu','yu')
print(person_fullname)
person_fullname=get_fullname('cao','lu')
print(person_fullname)

在这里插入图片描述

3.3 返回字典

函数可以返回任何类型的值,包括列表和字典等复杂的数据结构。

def get_fullname(firstname,lastname):
    fullname={'first':firstname,'last':lastname}
    return fullname

person_fullname=get_fullname('cao','lu')
print(person_fullname)

在这里插入图片描述

4、传递列表

4.1 在函数中修改列表

将列表传递给函数后,函数就可以对其进行修改。
在函数中对这个列表所做的修改是永久性的。

#邀请人的函数
def invite_people(uninvited,invited):
    while uninvited:
        current_person=uninvited.pop()
        invited.append(current_person)

#打印已邀请人的函数
def show_invited(invited):
    for person in invited:
        print(person)

#主程序
uninvited=['melody','fancy','hello']  #未邀请人的列表
invited=[]  #已邀请人的列表
invite_people(uninvited,invited)
show_invited(invited)

在这里插入图片描述

4.2 禁止函数修改列表

为了不影响原来的列表,可以向函数传递列表的副本而不是原件,这样函数所做的修改只影响副本,不影响原件。可以这样调用函数:

function_name(list_name[:])

4.1中做修改

#邀请人的函数
def invite_people(uninvited,invited):
    while uninvited:
        current_person=uninvited.pop()
        invited.append(current_person)

#打印已邀请人的函数
def show_person(people):
    for person in people:
        print(person)

#主程序
uninvited=['melody','fancy','hello']  #未邀请人的列表
invited=[]  #已邀请人的列表
invite_people(uninvited[:],invited)
print("已邀请的")
show_person(invited)
print("原先未邀请的")
show_person(uninvited)

在这里插入图片描述

5、传递任意数量的实参

预先不知道函数需要接受多少个实参,Python允许函数从调用语句中收集任意数量的实参。
形参名*people 中的星号让Python创建一个名为people的空元组,并将收到的所有值都封装到这个元组中。
注意:Python将实参封装到一个元组中,即便函数只收到一个值也如此。

def invite_people(*people):
    print(people)

invite_people('melody')
invite_people('melody','fancy','hello')

在这里插入图片描述

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

必须在函数定义中将接纳任意数量实参的形参放在最后
python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中

def invite_people(num,*people):
    print('We invite '+str(num)+' people:')
    for person in people:
        print('-'+person)
    
invite_people(1,'melody')
invite_people(3,'melody','fancy','hello')

在这里插入图片描述

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

def build_profile(first,last,**userinfo):
    print(userinfo)
    profile={}
    profile['firstname']=first
    profile['lastname']=last
    for key,value in userinfo.items():
        profile[key]=value
    return profile

user_profile=build_profile('cao','lu',location="xi'an",major="computer science and technology")
print(user_profile)

在这里插入图片描述

6、将函数存储在模块中

将函数存储在被称为模块的独立文件中,再将模块导入到主程序中。
项目结构:
在这里插入图片描述

6.1 导入整个模块

模块是为扩展名为.py的文件,包含要导入到程序中的代码
导入:import module_name
调用:module_name.function_name()使用该模块中的所有函数
invite_people.py

def hello():
    print("hello")

def invite_people(num,*people):
    print("We invite "+str(num)+" people")
    for person in people:
        print("-"+person)

main.py

import  invite_people

invite_people.hello()
invite_people.invite_people(1,'melody')
invite_people.invite_people(3,'melody','fancy','hello')

在这里插入图片描述

6.2 导入特定的函数

导入一个函数:from module_name import function_name
导入多个函数:from module_name import function_0,function_1,function_2
调用:function_name()调用
main.py

from invite_people import  hello,invite_people

hello()
invite_people(1,'melody')
invite_people(3,'melody','fancy','hello')

在这里插入图片描述

6.3 使用as给函数指定别名

导入:from module_name import function_name as fn
调用:fn()
main.py

from invite_people import  invite_people as in_peo

in_peo(1,'melody')
in_peo(3,'melody','fancy','hello')

在这里插入图片描述

6.4 使用as给模块指定别名

导入:import module_name as mn
调用:mn.function_name()
main.py

import  invite_people as mn

mn.hello()
mn.invite_people(1,'melody')
mn.invite_people(3,'melody','fancy','hello')

在这里插入图片描述

6.5 导入模块中的所有函数

导入:from module_name import *
调用:function_name()
main.py

from invite_people import *

hello()
invite_people(1,'melody')
invite_people(3,'melody','fancy','hello')
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值