1. 定义函数
#定义一个名为 function 的函数
def function():
print("Hello World!")
function() #调用函数
1.1 向函数传递信息
def function(string):
print(string)
function('Hello World!\n')
1.2 形参和实参
根据1.1的代码,其中function函数在定义时,string变量为形成,没有实际的值代表;在调用function函数时,传入实际参数(实参),并由函数内print函数输出显示。
2. 传递实参
2.1 位置实参
def info(name, age):
print("Your name is " + name)
print("Your age is ", age)
info("Mars", 24)
2.2 关键字实参
def info(name, age):
print("Your name is " + name)
print("Your age is ", age)
info(name = "Mars", age = 24)
2.3 默认值
def info(name, age = 24):
print("Your name is " + name)
print("Your age is ", age)
info(name = "Mars")
2.4 等效的函数调用
def info(name, age = 24):
print("Your name is " + name)
print("Your age is ", age)
info("Mark")
info(name = "Mars")
info("Bill", 20)
info(age = 25, name = "Mars")
3. 返回值
3.1 返回简单值
def get_name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name.title()
print('My name is '+ get_name('Mars','Zhang'))
3.2 让实参变成可选的
通过if判断传入参数是否为空,如果为空,不处理;
def get_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()
print('My name is '+ get_name('Mars','Zhang'))
3.3 返回字典
def Get_Person(first_name, last_name, age = ''):
person = {'First':first_name, 'Last':last_name}
if age:
person['Age'] = age
return person
print(Get_Person('Mars', 'Zhang', age = 24))
3.4 结合使用函数的while循环
无限次的输入名字及输出。
def Get_Name(first_name, last_name):
full_name = first_name + ' ' + last_name
return full_name
Flag = True
while(Flag):
print("\n Please input youer name:")
first_name = input("First name: ")
last_name = input("Last name: ")
print("\nHello, " + Get_Name(first_name, last_name) + "!")
4. 传递列表
def Greet_Users(name_list):
for name in name_list:
message = "Hello, " + name.title() + "!"
print(message)
usersname_list = ['mars', 'mark', 'bill']
Greet_Users(usersname_list)
4.1 在函数中修改列表
name_list = ['mars', 'mark', 'bill', 'nancy']
temp_list = []
while(name_list):
temp = name_list.pop()
print("temp: " + temp)
temp_list.append(temp)
print(name_list)
print(temp_list)
4.2 禁止函数修改列表
禁止修改函数列表可以通过向函数传递列表的副本的方式来解决。
def Copy_List(F_list, A_list):
while(F_list):
temp = F_list.pop()
A_list.append(temp)
name_list = ['mars', 'mark', 'bill', 'nancy']
copy_list = []
Copy_List(name_list[:], copy_list)
print(name_list)
print(copy_list)
5. 传递任意数量的实参
如果要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
5.1 结合使用位置实参和任意数量实参
def make_pizza(size, *toppings):
print("\n Making 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')
5.2 使用任意数量的关键字实参
接受任意数量的实参,但预先不知道传递给函数的会是什么样的值,在这种情况下可以将函数编写成能够接受任意数量的键-值对
def Get_UserInfo(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
print(Get_UserInfo('albert', 'einstein', location = 'shanghai', age = 24))
6. 将函数存储在模块中
6.1 导入整个模块
新建一个包含模块的的.py文件。例如:make_pizza.py
def make_pizza(size, *toppings):
print("\n Making a " + str(size) + "-inch pizza with the following toppings:")
for topping in toppings:
print("- " + topping)
在同一目录下,新建文件pizza.py
import make_pizza
make_pizza.make_pizza(16, 'pepperoni')
make_pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
6.2 导入特定的函数
形如from module_name import function_0, function_1, function_2
from make_pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
6.3 使用 as 给函数指定别名
如果导入的函数名称与当前程序中现有的名称冲突时(或太长),可以指定简短而独一无二的别名;这种方式需要在导入时操作。
from make_pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')
6.4 使用 as 给模块指定别名
import make_pizza as mp
mp.make_pizza(16, 'pepperoni')
mp.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')
6.5 导入模块中的所有函数
from make_pizza import *
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')