《python编程:从入门到实践》极简笔记:函数

定义函数

打印问候语

def greet_user():
    print('hello!')
greet_user()
hello!

向函数传递信息

def greet_user(username):
    print('hello!'+username.title())
greet_user('jesse')
hello!Jesse

实参和形参

上述username是形参,‘jesse’是实参,在greet_user(‘jesse’)中,将实参’Jesse‘传递给了函数greet_user(),这个值被存储在形参username中。

传递实参

位置实参

基于实参的顺序关联到形参,称为位置实参
例如,用一个形容词描述一个人

def greet_user(username,adj):
    print('hello!'+username.title()+'!'+"you are so "+adj+'.')
greet_user('jesse','handsome')
hello!Jesse!you are so handsome.

关键字实参

关键字实参是传递给函数的名称-值对,直接将形参与实参关联

def greet_user(username,adj):
    print('hello!'+username.title()+'!'+"you are so "+adj+'.')
greet_user(username='jesse',adj='handsome')
hello!Jesse!you are so handsome.

默认值

编写函数时,可以给每个形参默认值,若不提供实参则使用默认值。
例如将adj的默认值设为handsome

def greet_user(username,adj='handsome'):
    print('hello!'+username.title()+'!'+"you are so "+adj+'.')
greet_user('jesse')
hello!Jesse!you are so handsome.

若提供adj的形参,则忽略默认值
可混合使用位置实参、关键字实参和默认值

等效的函数调用

以下调用均可

def greet_user(username,adj='handsome'):
    print('hello!'+username.title()+'!'+"you are so "+adj+'.')
greet_user(username='jesse')
greet_user('jesse')
greet_user(username='jesse',adj='ugly')
greet_user('jesse','ugly')
hello!Jesse!you are so handsome.
hello!Jesse!you are so handsome.
hello!Jesse!you are so ugly.
hello!Jesse!you are so ugly.

但不可使用greet_user(username=‘jesse’,‘ugly’)

返回值

返回简单值

下面看一个函数,接受名和姓,返回姓名

def formatted_name(first,last):
    fullname=first+" "+last
    return fullname.title()
print(formatted_name('zhao','yongyan'))
Zhao Yongyan

让实参变成可选的

def formatted_name(first,last,middle=''):
    if middle:
        fullname=first+" "+middle+" "+last
    else:
        fullname=first+" "+last
    return fullname.title()

print(formatted_name('xiang','yang'))
print(formatted_name('zheng','feng','hao'))
Xiang Yang
Zheng Hao Feng

Python将非空字符串解读为true。将可选的中间名设置为空字符串。注意中间名的顺序,应该将其放在最后一个参数里。

返回字典

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

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

print(formatted_name('zhou','yizhuo'))
{'firstname': 'zhou', 'lastname': 'yizhuo'}

输出字典中包含有可选参数

def formatted_name(first,last,age=''):
    fullname={'firstname':first,'lastname':last}
    if age:
        fullname['age']=age
    return fullname

print(formatted_name('zhou','yizhuo'))
print(formatted_name('zhou','yizhuo',27))
{'firstname': 'zhou', 'lastname': 'yizhuo'}
{'firstname': 'zhou', 'lastname': 'yizhuo', 'age': 27}

传递列表

向函数传递列表很有用,这种列表包含的可能是名字、数字或更复杂的对象(如字典)
将一个名字列表传递给一个名为greet_users()的函数,这个函数问候列表中的所有人

def greet_users(names):
    for name in names:
        print("hello,"+name.title()+"!")

usernames=['huwenhao','xiangyang','zhengfenghao']
greet_users(usernames)
hello,Huwenhao!
hello,Xiangyang!
hello,Zhengfenghao!

在函数中修改列表

在函数中对列表的修改是永久性的

def print_models(unprinted_designs,completed_models):
    while unprinted_designs:
        current=unprinted_designs.pop()
        print("Printing model: "+current)
        completed_models.append(current)
def show_completed_model(completed_models):
    print("\nThe following models have been printed:")
    for completed_model in completed_models:
        print(completed_model)

unprinted_designs=['iphone case','robot pendant','dodecahedron']
completed_models=[]

print_models(unprinted_designs,completed_models)
show_completed_model(completed_models)
Printing model: dodecahedron
Printing model: robot pendant
Printing model: iphone case

The following models have been printed:
dodecahedron
robot pendant
iphone case

上述程序将需要打印的设计存储在一个列表中,打印后移到另一个列表中

禁止函数修改列表

禁止函数修改列表,可将列表的副本传递给函数:

function_name(list_name[:])

上述程序中即为:

print_models(unprinted_designs[:],completed_models)

此时,不会修改列表中的值

传递任意数量的实参

Python允许函数从调用语句中收集任意数量的实参。

def make_pizza(*toppings):
    print(toppings)

make_pizza('mushrooms','popcorns','pepper')
('mushrooms', 'popcorns', 'pepper')

用for循环

def make_pizza(*toppings):
    for topping in toppings:
        print(topping)

make_pizza('mushrooms','popcorns','pepper')
mushrooms
popcorns
pepper

不管一个值还是三个值,这个函数都能妥善处理

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

任意数量实参的形参放在最后。Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。

def make_pizza(size,*toppings):
    print("making a "+str(size)+" -inch pizza with the following toppings:")
    for topping in toppings:
        print("_"+topping)

make_pizza(14,'mushrooms','popcorns','pepper')
make_pizza(13,'najiao')
making a 14 -inch pizza with the following toppings:
_mushrooms
_popcorns
_pepper
making a 13 -inch pizza with the following toppings:
_najiao

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

将函数编写成能够接受任意数量的键—值对,可用两个星号**info让Python创建一个名为info的空字典。

def build_profile(fisrt,last,**user_info):
    profile={}
    profile['first_name']=fisrt
    profile['last_name']=last
    for key,value in user_info.items():
        profile[key]=value
    return profile
user=build_profile('zheng','fenghao',location='princeton',field='physics')
print(user)
{'first_name': 'zheng', 'last_name': 'fenghao', 'location': 'princeton', 'field': 'physics'}

将函数存储在模块中

导入整个模块

先创建一个名为pizza.py的文件,写一个make_pizza的函数。该文件即为创建的模块。

def make_pizza(size,*toppings):
    print("making a "+str(size)+" -inch pizza with the following toppings:")
    for topping in toppings:
        print("_"+topping)

再在pizza.py所在的目录中创建另一个文件,用import导入pizza模块,并使用其中的make_pizza()函数。调用函数时要在模块名与函数名之间加句点

import pizza
pizza.make_pizza(14,'mushroom')

导入特定的函数

导入make_pizza函数

from pizza import make_pizza
make_pizza(14,'mushroom')
making a 14 -inch pizza with the following toppings:
_mushroom

此时不需要在模块名与函数名之间加句点。

使用as给函数指定别名

from pizza import make_pizza as mp
mp(14,'mushroom')

给模块名指定别名同理

导入模块中的所有函数

使用星号*导入模块中所有的函数

from pizza import *
make_pizza(14,'mushroom')
making a 14 -inch pizza with the following toppings:
_mushroom
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值