Functions
- 8.1 Defining a Function
- 8.1.1 Passing Information to a Function
- 8.1.2 Parameters and Arguments 形参和实参
- 8.2 Passing Arguments 传递实参
- 8.3 Return Values
- 8.4 Using Function with a while Loop
- 8.5 Passing a List
- 8.6 Passing an Arbitrary Number of Arguments
- 8.7 Storing Your Functions in Modules模块
- 8.8 Styling Functions
8.1 Defining a Function
def greet_user():
'''Display a simple greeting.''' #docstring,描述函数功能
print("Hello!")
greet_user() #调用call
冒号
8.1.1 Passing Information to a Function
def greet(username):
'''Display a simple greeting.'''
print(f"Hello,{username.title()}!")
greet('jesse') #引号
information如果是字符串形式,应该要加引号
8.1.2 Parameters and Arguments 形参和实参
如上例中,变量名username为形参parameters,值’jesse’为实参arguments。
8.2 Passing Arguments 传递实参
8.2.1 Positional Arguments 位置实参
the right order (输入时会有形参提示)
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')
8.2.2 Keyword Arguments
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster', pet_name='harry')
8.2.3 Default Values
def describe_pet(pet_name, animal_type='dog'):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('Billy')
8.3 Return Values
8.3.1 Returning a Simple Value
The definition of return values
8.3.2 Making an Argument Optional
def get_formatted_name(first_name, last_name, middle_name=''): #' '为空字符串
"""Return a full name, neatly formatted."""
if middle_name:
full_name = f"{first_name} {middle_name} {last_name}"
else:
full_name = f"{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)
要将可选的argument放在最后。
’ '为空字符串。作为初始值,
8.3.4 Returnig a Dictionary
8.4 Using Function with a while Loop
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!")
8.5 Passing a List
def greet_users(names):
"""Print a simple greeting to each user in the list."""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)
8.5.1 Modifying a List in a Function
8.5.2 Preventing a Function from Modifying a List
8.6 Passing an Arbitrary Number of Arguments
def make_pizza(*toppings):
"""Print the list of toppings that have been requested."""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
8.6.1 Mixing Positional and Arbitrary Arguments
一个星号*
make an empty tuple
Arbitrary arguments放在最后。
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}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.6.2 Using Arbitrary Keyword Arguments
两个星号**
create an empty dictionary,输入name-value pairs
8.7 Storing Your Functions in Modules模块
8.7.1 Importing an Entire Module
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_pizzas.py
import pizza
pizza.make_pizza(16, 'pepperoni') # 文件名.函数名()
pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.7.2 Importing Specific Functions
from module_name import function_name
from module_name import function_0, function_1, function_2
使用时直接用函数名,而不需要“文件名.函数名()”
8.7.3 Using as to Give a Function an Alias
为避免函数重名导致的confuse,或嫌函数名太长。
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
即
from module_name import function_name as fn
8.7.4 Using as to Give a Module an Alias
嫌module名字过长:
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
import module_name as mn
8.7.5 Importing All Functions in a Module
使用*
导入全部函数的优点:调用时不用加“函数名. ”
缺点:导入的函数可能会和project中的函数重名
最好的方法还是仅导入需要的函数,或导入模块。这会使得代码更易读。
from pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
8.8 Styling Functions
模块名、函数名应为描述性的。
每个函数都应有comment,就在def行下面。使用 ‘’’ ‘’’ 格式。目标是:其他人仅读comment就会使用这个函数。
default value赋值号两侧不应有空格
def function_name(parameter_0, parameter_1='default value')
使用时也一样不能有空格:
function_name(value_0, parameter_1='value')
如果def行parameters很多,应写作如下格式:
def function_name(
parameter_0, parameter_1, parameter_2,
parameter_3, parameter_4, parameter_5):
function body...
如果程序或模块中有超过一个函数,每个函数之间可空两行。
import statements应写在file的开头,comments之后。