python-Function基础知识

以下为python中的函数的基础知识:

1.传递实参:
	(1).位置实参  #位置要和函数定义时的形参一一对应
		def descirbe_pet(animal_type, pet_name):
			"""显示宠物的信息"""
			print("\nI have a " + animal_type + ".")
			print("My " + animal_type + " 's name is " + pet_name)

		descirbe_pet('cat', 'Harry') #函数调用,传入实参
		descirbe_pet('dog', 'Tom')	
	(2).关键字实参
			传递给函数的名称-值对。这种方法无需考虑函数调用中的实参顺序,并且
		清楚地指出了函数调用中各个值的用途。
		def descirbe_pet(animal_type, pet_name):
			"""显示宠物的信息"""
			print("\nI have a " + animal_type + ".")
			print("My " + animal_type + " 's name is " + pet_name)

		#下面两种调用方法是等价的
		descirbe_pet(animal_type = 'cat', pet_name = 'Harry')
		descirbe_pet(pet_name = 'Harry', animal_type = 'cat')
	(3).形参默认值
		在进行函数定义时直接指定形参的默认值
		def descirbe_pet(animal_type, pet_name = 'Harry'):
			"""显示宠物的信息"""
			print("\nI have a " + animal_type + ".")
			print("My " + animal_type + " name is " + pet_name + ".")			
		descirbe_pet(animal_type = 'cat')
		Output:
		I have a cat.
	    My cat name is Harry.
		descirbe_pet('cat') #简单调用形式
		Output:
		I have a cat.
		My cat  name is Harry.
		descirbe_pet(animal_type = 'cat', pet_name = 'Tom')
		Output:  #提供实参,忽略默认值
		I have a cat.
		My cat  name is 'Tom'.

		#在使用默认值时,在形参列表中必须先列出没有默认值的形参,再列出有默认值的
		#形参,这让python可以正确地解读位置实参。
	(4).等效的函数调用
	def descirbe_pet(pet_name, animal_type = 'hamster'):
		#一只名为Harry的仓鼠
		descirbe_pet('Harry')
		descirbe_pet(pet_name = 'Harry')
		#一只名为Harry的狗
		descirbe_pet('Harry', 'dog')
		descirbe_pet(pet_name = 'Harry', animal_type = 'dog')
		descirbe_pet(animal_type = 'dog', pet_name = 'Harry')	
2.返回值
	(1).返回简单值		
		def get_formatted_name(first_name, last_name):
			"""返回整洁的姓名"""
			full_name = first_name + ' ' + last_name
			return full_name.title()
		musician = get_formatted_name('alex','shaw')
		print(musician)
		Output:
			Alex Shaw	
	(2).可选实参
		#输出一个人的名字,根据有没有中间名输出不同的结果
		def get_formatted_name(first_name, last_name, middle_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()
		musician = get_formatted_name('alex','shaw')
		print(musician)
		musician = get_formatted_name('alex','shaw','poison')
		print(musician)		
		Output:
		Alex Shaw
		Alex Poison Shaw
	(3).返回字典
		def build_person(first_name, last_name):
			"""返回一个字典,其中包含一个人的信息"""
			person = {'first': first_name, 'last':last_name}
			return person
		musician = build_person('alex', 'shaw')
		print(musician)		
		Output:
		{'first': 'alex', 'last': 'shaw'}


		#扩展,新增可选参数age,并设置默认值为空字符串
		def build_person(first_name, last_name, age = ''):
			"""返回一个字典,其中包含一个人的信息"""
			person = {'first': first_name, 'last':last_name}
			if age:
				person['age'] = age
			return person
		musician = build_person('alex', 'shaw',age = 17)
		print(musician)	

(4).结合使用while,if-else,函数,用户输入
"""对上述程序进行升级改造,让用户输入参数并可以选择是否输入age"""
def build_person(first_name,last_name, age = ''):
	person = {'first': first_name, 'last':last_name}
	if age:
		person['age'] = age
	return person

f_name = input("\nEnter your first name : \n")
l_name = input("\nEnter your last name : \n")
age_t = input("\nWould you like tell me your age?(yes / no)")

#判断用户输入
while True: #设置无限循环,确保用户可以正确输入
	if age_t == 'yes' :  #同意输入年龄
		age_get = input("\nEnter your age: ")
		musician = build_person(f_name.title(), l_name.title(), age_get)
		break
	elif age_t == 'no':  #不同意输入年龄
		musician = build_person(f_name.title(), l_name.title())
		break
	else :   #输入违法选项,重新输入,直到输入正确选项为止
 		age_t = input("\nEnter a right word(yes / no)")
print(musician)	

3.传递列表
	def greet_users(names):
		for name in names:
			print("\nHello ," + name.title() + "!")
	usernames = ['alex','shaw','poison']	
	greet_users(usernames)	
	(1).在函数中修改列表
		在将列表传递给函数后,函数就可以对其进行修改。在函数中对这个列表所做的
	任何修改都是永久性的。
	

	#一家为用户提交的设计制作3D打印模型的公司。需要打印的设计存储在一个列表中,
	#打印后转移到另一个列表中。
	
	#不使用函数:
	#创建列表,包含需要打印的设计
	unprinted_designs = ['iphone case','robot pendant','dodecahedron']
	completed_models = []

	#模拟打印每个设计,直到没有未打印的设计为止
	#打印每个设计后,都将其转移到表completed_models中
	while unprinted_designs:
		current_design = unprinted_designs.pop()

		#模拟根据设计制作3D打印模型的过程
		print("Pringting model: " + current_design)
		completed_models.append(current_design)

	#显示打印好的所有模型
	print("\nThe following models have been printed: ")
	for completed_model in completed_models:
		print(completed_model)	

	#使用函数:
	def print_models(unprinted_designs,completed_models):
		'''
		模拟打印每个设计,直到没有未打印的设计为止
		打印好每个设计后,将其转移到列表completed_models
		'''	
		while unprinted_designs:
			current_design = unprinted_designs.pop()

			#模拟根据设计制作3D打印模型的过程
			print("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 = ['iphone case','robot pendant','dodecahedron']
	completed_models = []

	print_models(unprinted_designs,completed_models)
	show_completed_models(completed_models)	
	'''
	相对于未使用函数的版本,使用函数可以让程序更容易扩展和维护。
	如果以后需要打印其他设计,只需再次调用print_models()即可。
	如果我们需要对打印代码进行修改,只需要修改这些代码一次,就能影响所有调用该
	函数的地方,而不必一个个查找修改。
	其次,每个函数都应只负责一项具体的工作。所以在编写代码时如果发现一个函数需要
	完成的任务过多,应该及时考虑划分成两个函数来完成这些任务。
	'''
	(2).禁止函数修改列表(思路:创建表的副本,修改副本而不修改原始列表)
		function.name(list[:])
		切片表示法[:]创建表的副本。
		例如,在上面的程序中,如果不想清空未打印的设计列表,可做如下修改:
		print_models(unprinted_designs[:], completed_models)
		函数仍然可以完成功能,但是不会修改原始列表,因为它操作的是表的副本。
		注:除非有充分的理由需要传递副本,否则还是应该将原始列表传递给函数,
	因为让函数使用现成列表可以避免花时间和内存创建副本,从而提高效率。

4.传递任意数量的实参
	def make_pizza(*topping):
		print(topping)
	make_pizza('hello')	
	make_pizza('ha','lo','oh')

	使用*可以创建一个名为topping的空元组。并将收到的所有值都封装到这个元组中。
	(1).结合使用位置实参和任意数量实参	
	def make_pizza(size, *topping):
		print("\nMaking a " + str(size) + 
			"-inch pizza with the following toppings:")
		for topping in toppings:
			print("- " + topping)

	make_pizza(16, 'hello')	
	make_pizza(27, 'ha','lo','oh')
	Output:
	Making a 16-inch pizza with the following toppings:
	- hello

	Making a 27-inch pizza with the following toppings:
	- ha
	- lo
	- oh
	(2).使用任意数量的关键字实参
	#创建用户简介
	def build_profile(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

	user_profile = build_profile('alex','shaw',
							location = 'China',
							field = 'Computer')
	print(user_profile)									
	Output:
	{'first_name': 'alex', 'last_name': 'shaw', 'location': 'China', 
												'field': 'Computer'}

5.存储函数到模块
	(1).导入整个模块:模块是扩展名为.py的文件,包含要导入到程序中的代码。
	使用方法:import xxx.py
	可以在当前文件中使用xxx.py中的所有的函数:xxx.function_name()
	(2).导入特定函数
	from moudle_name import function_name 
	导入任意数量的函数,使用逗号分隔:
	from moudle_name import function_1, function_2, function_3
	(3).使用as给函数指定别名
	from moudle_name import function_name as fn
	(4).使用as给模块指定别名
	import moudle_name as mn
	(5).导入模块中的所有函数
	from moudle_name import *
	使用:直接写moudle_name模块中的function_name即可,无需再加moudel_name
	例如:from xxx import *
		  yyy()
6.每个函数都应包含简要的阐述其功能的注释,该注释应该紧跟在函数定义后面,并采用文档
字符串形式。此外,需要注意:给形参指定默认值时以及函数调用中的关键字实参,
等号两边不要有空格;形参较多时应该分行,便于阅读



		

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值