初学python(三)——基础中的基础(函数)

自己按照书《Python编程从入门到实践》进行学习,一个小阶段后进行一点点整理,仅供参考。编译器为Geany。

函数

函数的定义和使用(def

def greet_user():
	print("Hello")

greet_user()

def greet_user(username):
	print("Hello, "+username.title()+"!")
	
greet_user('alice')

在传递实参的过程中有位置实参和关键字实参。位置实参的顺序很重要,它关系到传递时候各个参数对应的值是什么;而关键字实参因为有关键字进行限定所以不必考虑顺序问题
可以在定义函数的时候写定函数的默认值

#有默认值时,先写没有默认值的
def describe_pet(pet_name,animal_type='dog'):
	print("\nI have a "+animal_type+".")
	print("My "+animal_type+"'s name is "+pet_name.title()+".")
	
describe_pet('hamster','harry')
#关键字实参的顺序无关紧要
describe_pet(animal_type='hamster',pet_name='harry')
describe_pet(pet_name='harry',animal_type='hamster')

函数的返回值
函数可以返回任何类型包括字典等

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

在函数中传递、列表的值
用切片表示法创建了列表的副本,这样做就不会修改原本列表的值

def print_models(unprinted_designs,completed_models):
	while unprinted_designs:
		current_design = unprinted_designs.pop()
		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 = ['a','b','c']
completed_models = []

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

print(unprinted_designs)

运用*可以传递任意数量的实参

def make_pizza(size,*toppings):
	print("\nMaking a "+str(size)+
		  "-inch pizza with the following toppings:")
	for topping in toppings:
		print(topping)
make_pizza(12,'mushrooms','green peppers')

使用**可以传字典

#**创建一个名为user_info的空字典,并将收到的所有名称_值对都封装到这个字典中,并返回这个字典
def build_profile(first,last,**user_info):
	profile={}
	profile['frst_name']=first
	profile['last_name']=last
	for key,value in user_info.items():
		profile[key]=value
	return profile
user_profile = build_profile('albert','einstein',location='princeton',field='physics')
print(user_profile)

import关键字导入函数

import pizza;
pizza.make_pizza(12,'mashroom','green_pepper')
#module_name.function_name()

#导入特定的函数
from module_name import function_name
from module_name import fuction_0,function_1,function2

#显式调用时无需使用句点,只需指定其名称
#as 给函数或模块指定别名
#from pizza import* 导入模块中的所有函数 不建议使用
from pizza import make_pizza as mp
make_pizza(12,'mashroom')
mp(12,'mashroom')
发布了14 篇原创文章 · 获赞 11 · 访问量 2531

猜你喜欢

转载自blog.csdn.net/qq_43425914/article/details/98665973