python编程:从入门到实践学习笔记-函数

定义函数

举个简单的例子

def greet_user(username):
    """先是简单的问候语"""
    print("Hello! " + username.title() + "!")

greet_user("mike")

运行结果:
Hello! Mike!

由上所示,关键字def定义一个函数,后面跟着函数名以及用来输入参数的括号,定义以冒号结束,而print("Hello!")为其函数体。
调用函数时,则依次指定函数名以及用括号括起的必要信息,如参数等。
实参和形参
在函数greet_user(username)的定义中,变量username是一个形参。形参是一个函数完成其工作所需的一个参数。
在代码greet_user("mike")中,值"mike"是一个实参。实参是调用函数时传递给函数的参数。
调用greet_user("mike")函数时,我们将实参"mike"传递给了函数greet_user(),这个值被存储在形参username。

传递实参

位置实参:调用函数时,必须将函数调用中的每个实参都采用基于实参顺序的方式关联到函数定义中的一个形参中。
关键字实参:调用函数时,直接传递给函数名称-值对。此时不用考虑实参顺序。

def printID(ID, sname):
    print(ID + ":" + sname)

printID('14', 'mike') #位置实参
printID(sname='lili', ID='15') #关键字实参

运行结果:
14:mike
15:lili

默认值:给形参指定默认值。在调用函数中给形参提供了实参时,则用指定的实参值。如果没有提供则使用形参默认值。
PS:使用默认值时,在形参列表中必须Ian列出没有默认值的形参,再列出有默认值的实参。才能让python正确解读位置实参。

def printID(ID, sname = 'mike'):
    print(ID + ":" + sname)

printID('14')  #<-here
printID(sname='lili', ID='15')

运行结果:
14:mike
15:lili

返回值

返回简单值

def get_formatted_name(first_name, last_name):
    full_name = first_name + ' ' + last_name
    return full_name.title()
    
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

运行结果:
Jimi Hendrix

我们可以使用return语句在函数中返回值。

让实参可选

def get_formatted_name(first_name, last_name, middle_name=''):
    if middle_name:
        full_name = first_name + ' ' + middle_name + ' ' + last_name    
    else:
        full_name = 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)

运行结果:
Jimi Hendrix
John Lee Hooker

如上所示,使用if条件语句,并将实参作为判断条件即可让实参可选。

传递列表

将列表传递给函数后,不仅可以遍历列表,还能修改列表,并且这种修改时永久性的。
如果要禁止函数修改列表,可以传递列表的副本,比如:function_name(list_name[:])

传递任意数量的实参

def make_pizza(*toppings):
    print(toppings)

make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

运行结果:
('pepperoni',)
('mushrooms', 'green peppers', 'extra cheese')

形参名*toppings中的星号表示创建一个名为 toppings 的空元组,并把所有收到的值封装在这个元组中。我们还可以使用循环语句将所有值打印出来。

扫描二维码关注公众号,回复: 3966526 查看本文章

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

def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) + "-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
    
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

运行结果:
Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

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

def build_profile(first, last, **user_info):
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    return profile

user_profile = build_profile('albert', 'einstein',location='princeton',field='physics')
print(user_profile)

形参**user_info中的两个星号表示创建一个名为user_info的空字典,并将收到的所有名称-值对都封装到这个字典中。

将函数存储在模块中

导入整个模块
模块时扩展名为.py的文件,包含要导入到程序中的代码。使用import语句可以将模块导入。

#pizza.py
def make_pizza(size, *toppings):
    print("\nMaking a " + str(size) +"-inch pizza with the following toppings:")
    for topping in toppings:
        print("- " + topping)
    
#making_pizzas.py
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12,'mushrooms', 'green peppers', 'extra cheese')

运行结果:
Making a 16-inch pizza with the following toppings:
- pepperoni
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

如果导入的是整个模块,调用的时候就要指定模块名:module_name.function_name()

导入特定的函数
导入模块中特定的函数,可以使用以下方法:from module_name import function_name
用逗号分隔函数名,可导入任意数量函数:from module_name import function_0, function_1, function_2
这时候调用函数,无需使用句点,直接指定函数名,因为我们在import语句中显示导入了函数。

使用as给函数指定别名
为了防止冲突,或者函数名太长,可指定一个独一无二的别名,函数的另外一个名称,通用语法为:from module_name import function_name as fn

导入模块中的所有函数
使用星号(*)运算符可以导入模块中的所有函数,此时不用使用句点来调用函数。不过最好不要这样。语法为:from module_name import *

猜你喜欢

转载自blog.csdn.net/qq_40925239/article/details/83687919
今日推荐