1. def greet_user(username): # parameter
  2. """Display a simple greeting.""" # docstring 文档字符串
  3. print(f"Hello, {username.title()}!")
  4. greet_user('Jesse') # argument

parameters and arguemnts

  1. def make_shirt(size='L', message='hello world'): # 形参给默认值
  2. print(f"size: {size}, message: {message}")
  3. make_shirt('M', 'dog') # positional arguments 按形参顺序传参
  4. make_shirt(message='cat', size='L') # keyword arguments 按形参名称传参
  5. make_shirt('S') # 不传参则为默认值
  6. make_shirt(message='I love Python')

return

  1. def make_album(artist, album, number=None):
  2. albums = {'artist': artist, 'album': album}
  3. if number:
  4. albums['number'] = number
  5. return albums
  6. while True:
  7. artist = input("Please enter a artist, press 'q' to quit: ")
  8. if artist == 'q':
  9. break
  10. album = input("Please enter an album, press 'q' to quit: ")
  11. if album == 'q':
  12. break
  13. information = make_album(artist, album)
  14. print(information)

passing a list

向函数传list,在函数内部可以修改传入的list
如果要阻止函数修改list,在函数调用传参时,可以传入这个list的副本

  1. function_name(list_name[:])
  1. messages = ['hello', '你好', 'hi', "what's up"]
  2. sent_messages = []
  3. def show_messages(messages, sent_messages):
  4. while messages:
  5. sent_message = messages.pop()
  6. sent_messages.append(sent_message)
  7. print(sent_message)
  8. show_messages(messages[:], sent_messages)
  9. print(messages)
  10. print(sent_messages)

tips: every function should have only one specific job

Passing an Arbitrary Number of Arguments

函数接受任意个参数,这些参数被存储在元组(tuple)里

  1. def function_name(*args)
  1. def make_sandwich(*items):
  2. """Make a sandwich with the given items."""
  3. print("\nI'll make you a great sandwich:")
  4. for item in items:
  5. print(f" ...adding {item} to your sandwich.")
  6. print("Your sandwich is ready!")
  7. make_sandwich('roast beef', 'cheddar cheese', 'lettuce', 'honey dijon')
  8. make_sandwich('turkey', 'apple slices', 'honey mustard')
  9. make_sandwich('peanut butter', 'strawberry jam')

接受任意多个keyword arguments

  1. def function_name(**kwargs)

当传入任意多个keyword arguments时,python会自动创建一个与**后名字相同的字典,将传入的键值对参数存入这个字典,这个字典可以被访问

  1. def build_profile(first, last, **user_info): # 会自动创建user_info字典
  2. """Build a dictionary containing everything we know about a user."""
  3. user_info['first_name'] = first
  4. user_info['last_name'] = last
  5. return user_info
  6. user_profile = build_profile('albert', 'einstein',
  7. location='princeton', # 自动存入user_info字典
  8. field='physics')
  9. print(user_profile)
  10. # {'location': 'princeton', 'field': 'physics',
  11. # 'first_name': 'albert', 'last_name': 'einstein'}

Storing Your Functions in Modules

import整个文件
在pizza.py文件里声明一个函数

  1. def make_pizza(size, *toppings):
  2. """Summarize the pizza we are about to make."""
  3. print(f"\nMaking a {size}-inch pizza with the following toppings:")
  4. for topping in toppings:
  5. print(f"- {topping}")

在making_pizza.py文件里import pizza,所有函数都可通过.访问并使用
pizza.py和making_pizza.py需要在相同的文件夹下?

  1. import pizza
  2. pizza.make_pizza(16, 'pepperoni')
  3. pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

如果只想从module中import特定的函数,用下列语法

  1. from module_name import function_0, function_1, function_2
  1. from pizza import make_pizza
  2. # 导入后,函数直接使用
  3. make_pizza(16, 'pepperoni')
  4. make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

as为import的函数指定别名

  1. from pizza import make_pizza as mp
  2. mp(16, 'pepperoni')
  3. mp(12, 'mushrooms', 'green peppers', 'extra cheese')

为module指定别名

  1. import pizza as p
  2. p.make_pizza(16, 'pepperoni')
  3. p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

从module中import所有的函数

  1. from module_name import *

以上方法,除了函数,变量也是可以import
如果要从piz文件夹里导入pizza模组,语法如下

  1. from piz.pizza import *
  2. make_pizza(16, 'pepperoni')
  3. make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
  4. print(fruits)

styling functions

  1. 函数名应具有说明性,用小写字母和下划线组成
  2. 没有函数都应该有文档字符串注释说明函数的功能
  3. 函数参数给默认值或keyword传参时,等号两边不要有空格
  4. 如果参数过多,则从左括号开始另起一行,空8格(2次tab)

    1. def function_name(
    2. parameter_0, parameter_1, parameter_2,
    3. parameter_3, parameter_4, parameter_5):
    4. function body...
  5. 程序或module中的每个函数之间,空2行隔开