def greet_user(username): # parameter
"""Display a simple greeting.""" # docstring 文档字符串
print(f"Hello, {username.title()}!")
greet_user('Jesse') # argument
parameters and arguemnts
def make_shirt(size='L', message='hello world'): # 形参给默认值
print(f"size: {size}, message: {message}")
make_shirt('M', 'dog') # positional arguments 按形参顺序传参
make_shirt(message='cat', size='L') # keyword arguments 按形参名称传参
make_shirt('S') # 不传参则为默认值
make_shirt(message='I love Python')
return
def make_album(artist, album, number=None):
albums = {'artist': artist, 'album': album}
if number:
albums['number'] = number
return albums
while True:
artist = input("Please enter a artist, press 'q' to quit: ")
if artist == 'q':
break
album = input("Please enter an album, press 'q' to quit: ")
if album == 'q':
break
information = make_album(artist, album)
print(information)
passing a list
向函数传list,在函数内部可以修改传入的list
如果要阻止函数修改list,在函数调用传参时,可以传入这个list的副本
function_name(list_name[:])
messages = ['hello', '你好', 'hi', "what's up"]
sent_messages = []
def show_messages(messages, sent_messages):
while messages:
sent_message = messages.pop()
sent_messages.append(sent_message)
print(sent_message)
show_messages(messages[:], sent_messages)
print(messages)
print(sent_messages)
tips: every function should have only one specific job
Passing an Arbitrary Number of Arguments
函数接受任意个参数,这些参数被存储在元组(tuple)里
def function_name(*args)
def make_sandwich(*items):
"""Make a sandwich with the given items."""
print("\nI'll make you a great sandwich:")
for item in items:
print(f" ...adding {item} to your sandwich.")
print("Your sandwich is ready!")
make_sandwich('roast beef', 'cheddar cheese', 'lettuce', 'honey dijon')
make_sandwich('turkey', 'apple slices', 'honey mustard')
make_sandwich('peanut butter', 'strawberry jam')
接受任意多个keyword arguments
def function_name(**kwargs)
当传入任意多个keyword arguments时,python会自动创建一个与**后名字相同的字典,将传入的键值对参数存入这个字典,这个字典可以被访问
def build_profile(first, last, **user_info): # 会自动创建user_info字典
"""Build a dictionary containing everything we know about a user."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info
user_profile = build_profile('albert', 'einstein',
location='princeton', # 自动存入user_info字典
field='physics')
print(user_profile)
# {'location': 'princeton', 'field': 'physics',
# 'first_name': 'albert', 'last_name': 'einstein'}
Storing Your Functions in Modules
import整个文件
在pizza.py文件里声明一个函数
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
在making_pizza.py文件里import pizza,所有函数都可通过.访问并使用
pizza.py和making_pizza.py需要在相同的文件夹下?
import pizza
pizza.make_pizza(16, 'pepperoni')
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
如果只想从module中import特定的函数,用下列语法
from module_name import function_0, function_1, function_2
from pizza import make_pizza
# 导入后,函数直接使用
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
用as为import的函数指定别名
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
为module指定别名
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
从module中import所有的函数
from module_name import *
以上方法,除了函数,变量也是可以import
如果要从piz文件夹里导入pizza模组,语法如下
from piz.pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
print(fruits)
styling functions
- 函数名应具有说明性,用小写字母和下划线组成
- 没有函数都应该有文档字符串注释说明函数的功能
- 函数参数给默认值或keyword传参时,等号两边不要有空格
如果参数过多,则从左括号开始另起一行,空8格(2次tab)
def function_name(
parameter_0, parameter_1, parameter_2,
parameter_3, parameter_4, parameter_5):
function body...
程序或module中的每个函数之间,空2行隔开