目录
定义函数
#——————定义函数——————————
def user():
print('hello!')
user()
#——————向函数传递信息————————
def user(username):
print('hello,'+ username)
user('jack')
#——————实参和形参————————————
def user(username): #username 形参
print('hello,'+ username)
user('jack') # jack 实参
传递实参
# #—————————位置实参————————————
def user(name,age):
print('使用者的名字是'+name)
print('他/她的年龄是'+age+'岁。')
# user('张三','18') #函数可调用多次,需注意位置实参顺序
# #————————关键字实参————————————
def user(name,age):
print('使用者的名字是'+name)
print('他/她的年龄是'+age+'岁。')
user(age = '18',name='张三') # 关键字实参的顺序无关紧要,但需注意准确指定形参名
# #————————默认值————————————————-
def user(age,name='张三'): #给形参name指定了默认值'张三'。这样,调用这个函数时,
#如果没有给name指定值,Python将把这个形参设置为'张三':
print('使用者的名字是'+name)
print('他/她的年龄是'+age+'岁。')
user(age = '18') #这个函数调用的输出与前一个示例相同。只提供了一个实参——'18',这个实参将关联
#到函数定义中的第一个形参——age。由于没有给name提供实参,因此使用其默认值'张三'。
user('18','法外狂徒') #由于显式地给animal_type提供了实参,
#因此Python将忽略这个形参的默认值。
注意 使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的实参。
返回值
# ——————返回简单值——————————
def get_fomatted_name(first_name,last_name):
full_name = first_name + ' ' +last_name
return full_name.title()
someone = get_fomatted_name('jack','lenn')
print(someone)
# #在需要分别存储大量名和姓的大型程序中,像get_formatted_name()这样的函数非常有用。
# #你分别存储名和姓,每当需要显示姓名时都调用这个函数。
# #————————让实参变成可选的————————————
def get_fomatted_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()
someone = get_fomatted_name('faker','deft')
print(someone)
someone = get_fomatted_name('faker','uzi','deft')
print(someone)
#可选值让函数能够处理各种不同情形的同时,确保函数调用尽可能简单。
#——————————返回字典————————————————
def summoner_name(first_name,second_name):
person = {'first':first_name.title(),'second':second_name.title()}
return person
summoner = summoner_name('deft','faker')
print(summoner)
#——————结合使用函数和 while 循环——————————
def summoner_name(first_name,second_name):
person = first_name+ ' ' +second_name
return person.title()
while True:
print('\nPlease tell me your name!')
print("(enter 'q' at any time to quit.)")
summ_name = input('First_name: ')
if summ_name == 'q':
break
oner_name = input('Second_name: ')
if oner_name == 'q':
break
summoner = summoner_name(summ_name,oner_name)
print('Hello!'+summoner_name + '.')
# #添加了一条消息来告诉用户如何退出,然后在每次提示用户输入时,都检查他输入的是
# # 否是退出值,如果是,就退出循环。现在,这个程序将不断地问候,直到用户输入的姓或名为'q'
# # 为止
传递列表
def user_name(names):
for name in names:
msg = print('hello,'+name.title()+'!')
print(msg)
usernames = ['uzi','deft','faker']
user_name(usernames)
#————————在函数中修改列表————————————
def printing(print_file,print_over):
while print_file:
p_file = print_file.pop()
print('Printing:'+p_file)
print_over.append(p_file)
def printed(print_over):
print('以下是打印好的文件:')
for over in print_over:
print(over)
print_file = ['健康膳食表','运动计划表','读书书单']
print_over = []
'''这个程序还演示了这样一种理念,即每个函数都应只负责一项具体的工作。第一个函数打印
每个文件,而第二个显示打印好的文件;这优于使用一个函数来完成两项工作。编写函数时,如
果你发现它执行的任务太多,请尝试将这些代码划分到两个函数中。别忘了,总是可以在一个函
数中调用另一个函数,这有助于将复杂的任务划分成一系列的步骤'''
#————————禁止函数修改列表————————————————
#向函数传递列表副本而不是原件
#msg = print_file[:] #切片表示法[:]创建列表的副本。
传递任意数量的实参
#————————————————————传递任意数量的实参————————————————————————————————————————
def take_exercise(*exercise):
print(exercise)
take_exercise('打乒乓球')
take_exercise('跑步','打羽毛球','引体向上')
#形参名*exercise中的星号让Python创建一个名为exercise的空元组,
# 并将收到的所有值都封装到这个元组中。
#———————— 结合使用位置实参和任意数量实参——————
#如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
#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')
#————————使用任意数量的关键字实参————————————
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)
将函数存储在模块中
#————————————————将函数存储在模块中——————————————————————————————————————————
#——————导入整个模块——————
#创建一个名为pizza.py的文件储存以下函数
def make_pizza(size, *toppings):
"""概述要制作的比萨"""
print("\nMaking a " + str(size) +
"-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
#新建文件导入上述函数
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
#——————导入特定的函数—————————————————
#from (模块名) import (函数名)
from pizza import make_pizza
#——————使用 as 给函数指定别名——————————
from pizza import make_pizza as mp
#——————使用 as 给模块指定别名——————
import pizza as p
#——————导入模块中的所有函数——————————
from pizza import * #使用星号(*)运算符可让Python导入模块中的所有函数
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
函数编写指南
编写函数时,需要牢记几个细节。
1.应给函数指定描述性名称,且只在其中使用小写字母和下 划线。描述性名称可帮助你和别人明白代码想要做什么。给模块命名时也应遵循上述约定。
2.每个函数都应包含简要地阐述其功能的注释,该注释应紧跟在函数定义后面,并采用文档字 符串格式。文档良好的函数让其他程序员只需阅读文档字符串中的描述就能够使用它:他们完全 可以相信代码如描述的那样运行;只要知道函数的名称、需要的实参以及返回值的类型,就能在自己的程序中使用它。
3.给形参指定默认值时,等号两边不要有空格,于函数调用中的关键字实参,也应遵循这种约定。
本文详细介绍了Python函数的基础概念和使用方法,包括定义函数、传递参数、返回值、操作列表等内容,并探讨了函数在实际编程中的应用。
2万+

被折叠的 条评论
为什么被折叠?



