《Python编程从入门到实践》8

8.1 定义函数

def greet_user():
	"""显示简单的问候语"""
	print("Hello!")


greet_user()

8.1.1 向函数传递信息

def greet_user(username):
	"""显示简单的问候语"""
	print(f"Hello,{username.title()}!")


greet_user('jesse')
这里在定义函数时,在函数中的括号内增加了形参
我们在使用函数时需要给函数传递一个实参

8.1.2 实参和形参

形参:函数完成其工作所需的一项信息
实参:调用函数时传递给函数的信息
实参将值传递给函数,这个值被存储在形参中

8.2 传递实参

位置实参:要求实参的顺序与形参的顺序相同;
关键字实参:其中每个实参都有变量名和值组成;
实参还可使用列表和字典

8.2.1 位置实参

def describe_pet(animal_type, pet_name):
	""""显示宠物的信息"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name}.")


describe_pet('dog', 'wangcai')
describe_pet('dog', 'dahuang')

8.2.2 关键字实参

def describe_pet(animal_type, pet_name):
	""""显示宠物的信息"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name}.")


describe_pet(animal_type='hamster', pet_name='harry')
关键字实参是指我们在定义实参时顺便将实参的值赋给了形参,无需考虑顺序,因为是有对应关系的。

8.2.3 默认值

def describe_pet(pet_name, animal_type='dog'):
	""""显示宠物的信息"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name}.")


describe_pet(pet_name='wangcai')
可以给函数的形参赋默认值,若我们没有给该形参赋实参,那将默认显示默认值。
要注意普通形参和默认值形参的位置关系,如果我们不需要给默认值形参赋实参,我们通常会给其他形参赋值。
那么这里要注意,python赋值是按照顺序赋值的,所以我们要将默认值形参放在函数括号的后面。

8.2.4 等效的函数调用

def describe_pet(pet_name, animal_type='dog'):
	""""显示宠物的信息"""
	print(f"\nI have a {animal_type}.")
	print(f"My {animal_type}'s name is {pet_name}.")


describe_pet('willie')
describe_pet(pet_name='wille')
describe_pet('MiMi', 'cat')
可混合使用位置实参、关键字实参、默认值
赋值实参时也可以按以上方式进行赋值

8.2.5 避免实参错误

实参的数目和位置要与形参匹配。

8.3 返回值

函数并非总是直接显示输出,相反,它可以处理一些数据,并返回一个或一组值。
函数返回的值被称为返回值。
在函数中,可使用return语句将值返回到调用函数的代码行。
返回值让你能够将程序的大部分繁重工作移到函数中去完成,从而简化主程序。

8.3.1 返回简单值

def get_formatted_name(first_name, last_name):
	"""返回全名"""
	full_name = f"\n{first_name} {last_name}"
	return full_name.title()


musician = get_formatted_name('jimi', 'hendrix')
print(musician)

8.3.2 让实参变成可选的

def get_formatted_name(first_name, middle_name, last_name=''):
	"""返回全民"""
	# 检查
	if middle_name:
		full_name = f"\n{first_name} {middle_name} {last_name}"
	else:
		full_name = f"\n{first_name} {last_name}"
	return full_name.title()


musician = get_formatted_name('fule', 'han')
print(musician)
musician = get_formatted_name('1', '2', '3')
print(musician)
实参变为可选的:就得让其对应的形参的默认值赋为空字符串,并放到函数括号的最后位置

8.3.3 返回字典

def build_person(first_name, last_name, age=None):
	person = {'first': first_name, 'last': last_name}
	if age:
		person['age'] = age
	return person


musician = build_person('jimi', 'hendrix', 27)
print(musician)
musician = build_person('jimi', 'hendrix', age=27)
print(musician)
musician = build_person('jimi', 'hendrix', )
print(musician)
函数定义中的None等价于空字符串

8.3.4 结合while循环和函数

 def get_formatted_name(first_name, last_name):

 	"""返回全名"""
 	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.4 传递列表

def greet_users(names):
	"""向列表中的每位用户发出简单的问候"""
	for name in names:
		msg = f"Hello, {name.title()}!"
		print(f"\n{msg}")

8.4.1 在函数中修改列表

函数对列表所做的任何修改都是永久性的
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
while unprinted_designs:
	current_design = unprinted_designs.pop()
	print(f"\nPrinting model: {current_design}")
	completed_models.append(current_design)

print("\nThe following models have been printed:")
for completed_models in completed_models:
	print(completed_models)


def print_models(unprinted_designs, completed_models):
	while unprinted_designs:
		current_design = unprinted_designs.pop()
		print(f"Printing model:{current_design}")
		completed_models.append(current_design)


def show_completed_models(completed_models):
	print("\nThe following models have been printed:")
	for completed_model in completed_models:
		print(completed_model)


unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []

print_models(unprinted_designs[:], completed_models)
show_completed_models(completed_models)

8.4.2 禁止函数修改列表

因为函数对列表的修改是永久性的,若我们不想让函数修改列表,那么只需要将列表的切片赋值给实参,再传递给函数的形参
切片表示法[ : ]创建列表的副本
print_models(unprinted_designs[:], completed_models)
show_completed_models(completed_models)

8.5 传递任意数量的实参

def make_pizza(*toppings):
	"""打印顾客点的所有配料"""
	print("\nMaking a pizza with the following toppings:")
	for topping in toppings:
		print(f"-{topping}")


make_pizza('mushrooms', 'green peppers', 'extra cheese')
*toppings中的星号让python创建一个名为toppings的空元组,元组用圆括号括起来。

8.5.1 结合使用位置实参和任意数量实参

若要让函数接受不同类型的实参,必须在函数定义中将接纳任意数量实参的形参放在最后。
Python先匹配位置实参和关键字实参,再将余下的实参都收集到最后一个形参中。
def make_pizza(size, *toppings):
	"""打印顾客点的所有配料"""
	print(f"\nMaking a {size} pizza with the following toppings:")
	for topping in toppings:
		print(f"-{topping}")


make_pizza(16, 'mushrooms', 'green peppers', 'extra cheese')

8.5.2 使用任意数量的关键字实参

关键字形参类似于键值对,所以我们将形参中的最后一位定义为一个空字典
*:创建一个空列表
**:创建一个空字典
def build_profile(first, last, **user_info):
	"""创建一个字典,其中包含我们知道的有关用户的一切"""
	user_info['first_name'] = first
	user_info['last_name'] = last
	return user_info


user_profile = build_profile('albert', 'einstein', location='princeton',
							 field='physics')
print(user_profile)

8.6 将函数存储在模块中

写好函数的代码,并保存在一个扩展名为.py的文件中

8.6.1 导入整个模块

import module_name.py
mofule_name.function_name()

8.6.2 导入特定的函数

from module_name import function_name
from module_name import function1, function2

8.6.3 使用as给函数指定别名

form module_name import function_name as fn

8.6.4 使用as给模块指定别名

import module_name as mn

8.6.5 导入模块中的所有函数

from pizza import *
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值