Python之 函数的定义,调用,传递实参,使用位置实参和关键字实参,显示函数,有返回值的函数,将函数与列表,字典,while,if结合,导入模块
注意:以下代码均可正常运行,下附有运行实现代码,以及导入的模块
#函数
#问候函数
def greet(): #无参数
"""显示简单的问候语""" #文档字符串的注释
print("hello")
greet() #调用
def greet(username): #有参数
print("hello,"+username.title()+'!')
greet('jenney')
#传递实参的多种方式
#1.位置实参--顺序千万不乱
def pet(type,name):
"""显示宠物信息"""
print("I have a "+type+'. '+"name is "+name+'.')
pet('hamster','honey')
pet('dog','dyiny') #可以多次调用函数
#2.关键字实参--传递给函数的名称-值对,在实参中将名称和值关联起来了,无需关心顺序
pet(name='dyu',type='cat')
#默认值--给形参指定默认值,若提供了实参,那么用实参,否则用形参默认值;所以调用函数时可以省略
def pets(name,type='dog'):
print("I have a "+type+'. '+"name is "+name+'.')
pets(name='jen')
pets(name='colin',type='cat')
#返回值--任何类型的值,包括列表和字典等复杂的数据结构
def name(first,last):
"""返回整洁的姓名"""
full_name=first+' '+last
return full_name.title() #注意缩进
student=name('tian','yan')
print(student)
#让实参可选--位置实参与默认值的结合
def name(first,last,middle=' '):
"""返回整洁的姓名"""
if middle: #非空字符串为True
fullname=first+' '+middle+' '+last
else:
fullname=first+' '+last
return fullname.title()
teacher=name('juli','jeneny')
print(teacher)
#返回字典
def person(first_name,last_name):
"""返回一个字典,其中包含一个人的信息"""
data={'first':first_name,'last':last_name}
return data
student=person('jenni','honey')
print(student)
#while与函数
while True:
print('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=person(f_name,l_name)
print(formatted_name)
#向函数传递列表
def greet(names):
"""向列表中的每一位用户都发出简单的问候"""
for name in names:
msg="hello,"+name.title()+'!!'
print(msg)
users_name=['jenney','diana','colin']
greet(users_name)
#在函数中修改列表---永久性的
def print_models(unprinted,completed):
"""打印每个设计,直到没有设计
然后移动到completed列表中"""
while unprinted:
current=unprinted.pop()
print("Printing models:"+current)
completed.append(current)
def show(completed):
"""显示打印好的模型"""
print("the following models have been printed: ")
for model in completed:
print(model)
unprinted=['robot','dog','cat']
completed=[]
print_models(unprinted,completed)
show(completed)
#禁止函数修改列表--向函数传递副本,不影响原件
print_models(unprinted[:],completed) #切片表示法[:]创建列表副本
#传递任意数量的实参--修改形参的表示
def make(*toppings):
"""打印顾客点的配料"""
print("making a pizza with following toppings")
for topping in toppings:
print('- '+topping)
make('peper')
make('mushroom','green peeper')
#原理:*让Python创建一个叫做toppings的空元组,并将收到的所有实参值都封装到这个元组
#结合使用位置实参和任意数量实参
#必须要将 接纳任意数量的实参放在最后,先匹配位置实参以及关键字实参
def make_pizza(size,*toppings):
"""概述要制作的比萨"""
print("Making a "+str(size)+"-inch pizza with following toppings:")
for topping in toppings:
print("- "+topping)
make_pizza(16,'pepper')
make_pizza(12,'mushrooms','extra cheese')
#使用任意数量的关键字实参--需要接受任意数量的实参,而且可能不知道传递给函数的是什么信息
#此时可以将函数编写为可以接受任意数量的键值对--连用两个**决定了任意数量的键值对
def profile(first,last,**user):
"""创建一个字典,其中包含我们知道的一切"""
profile={}
profile['first_name']=first
profile['last_name']=last
for key,value in user.items():
profile[key]=value
return profile
user_profile=profile('jenney','einstern',location='princeton',field='physics',love='programe')
print(user_profile)
#将函数存储在模块(独立文件)中:import允许在当前的程序文件中使用模块中的代码
#导入整个模块,模块是扩展名是.py的文件
import pizza #导入模块
pizza.make_pizza(15,'great pepper') #调用方式:模块名称.函数名称()
pizza.make_pizza(32,'red pepper','extra cheese')
#导入特定函数
from pizza import make_pizza #from 模块名 import 函数名,函数名,函数名
make_pizza(111,'red') #调用方式:函数名()
make_pizza(234,'green')
#使用as给函数指定别名 from 模块名 import 函数名 as 别名
from pizza import make_pizza as mp
make_pizza(456,'ugh')
make_pizza(67,'great','ujg')
#导入模块中所有的函数-- *运算符可以实现,但是尽量不要用,因为函数名称可能重合
from pizza import *
make_pizza(234,'erg')
make_pizza(234,'ujkl')
#格外注意:1.给形参指定默认值以及函数调用中的关键字实参,等号两边不要有空格
#2.PEP8建议代码长度不超过 79字符,如果超过,那么:一个回车加上一个Tab
def function_name(
parameter_0,parameter_1,
parameter_2,parameter_3):
function body...
#3.所有的import语句都应该放在开头,除非,文件开头用了注释
测试区:代码区的实现
hello
hello,Jenney!
I have a hamster. name is honey.
I have a dog. name is dyiny.
I have a cat. name is dyu.
I have a dog. name is jen.
I have a cat. name is colin.
Tian Yan
Juli Jeneny
{'first': 'jenni', 'last': 'honey'}
tell me your name:
(enter 'q' at any time to quit)
First name:q
hello,Jenney!!
hello,Diana!!
hello,Colin!!
Printing models:cat
Printing models:dog
Printing models:robot
the following models have been printed:
cat
dog
robot
making a pizza with following toppings
- peper
making a pizza with following toppings
- mushroom
- green peeper
Making a 16-inch pizza with following toppings:
- pepper
Making a 12-inch pizza with following toppings:
- mushrooms
- extra cheese
{'first_name': 'jenney', 'last_name': 'einstern', 'location': 'princeton', 'field': 'physics', 'love': 'programe'}
Making a15-inch pizza with the following toppings:
- great pepper
Making a32-inch pizza with the following toppings:
- red pepper
- extra cheese
Making a111-inch pizza with the following toppings:
- red
Making a234-inch pizza with the following toppings:
- green
Making a456-inch pizza with the following toppings:
- ugh
Making a67-inch pizza with the following toppings:
- great
- ujg
Making a234-inch pizza with the following toppings:
- erg
Making a234-inch pizza with the following toppings:
- ujkl
导入的模块–注意要和需求文件放在同一个目录中
def make_pizza(size,*toppings):
"""概述所要制作的披萨"""
print("Making a"+str(size)+
"-inch pizza with the following toppings:")
for topping in toppings:
print("- "+topping)