本文讲述:函数、实参和形参,返回值,传递列表
1.定义函数
def 函数名():
def greet():
'''显示问候语'''#简单说明函数的用处,文档字符串
print('hello')
greet()#调用函数
结果:hello
传递参数:
def greet(username):
print('hello, '+username)
greet('Amy')
结果:
hello, Amy
2.实参和形参
形参:函数定义时为了表示所需的一项信息,例如上述例子中的username
实参:调用函数时传递给函数的信息,例如上述例子中的Amy
2.1位置实参
实参和形参位置相同,可以实现多次调用
def greet(username,age):
print('hello, '+username+' is '+age)
greet('Amy','16')
greet('Emma','26')
结果:
hello, Amy is 16
hello, Emma is 26
2.1关键字实参
直接在实参中将名字和值关联,向函数传递实参时不会混淆
def greet(username,age):
print('hello, '+username+' is '+age)
greet(username='Amy',age='16')
greet(username='Emma',age='26')
结果
hello, Amy is 16
hello, Emma is 26
2.3形参指定默认值、
def greet(username='Lily',age='18'):
print('hello, '+username+' is '+age)
greet(username='Amy',age='16')
greet()
结果:
hello, Amy is 16
hello, Lily is 18
3.返回值
3.1函数处理数据后返回一个或者一组值
例子:
def greet(username='Lily',age='18'):
return username.upper()
name=greet()
print(name)
结果:LILY
3.2让实参变得可选
默认值为’ ’
def greet(username='Lily',pet='',age='18'):
if pet:
info=username+' '+pet+' '+age
else: info=username+' '+age
return info
info=greet(username='Amy',pet='',age='18')
print(info)
结果:
Amy 18
3.3返回字典
def greet(username='Lily',pet='dog',age='18'):
info={'name':username,'pet':pet,'age':age}
return info
info=greet(username='Amy',pet='cat',age='18')
print(info)
结果:
{'name': 'Amy', 'pet': 'cat', 'age': '18'}
4.传递列表
4.1传递列表
def greet(names):
for name in names:
print('hello '+name)
names=['Amy','Julia','Stacy']
greet(names)
结果:
hello Amy
hello Julia
hello Stacy
4.2 函数中修改列表
def printing(unprinted,completed):
while unprinted:
current=unprinted.pop()
print("printing "+current)
completed.append(current)
def show(completed):
for completed in completed:
print(completed)
unprinted=['dog','cat','bear']
completed=[]
printing(unprinted,completed)
show(completed)
结果:
printing bear
printing cat
printing dog
bear
cat
dog
4.3 禁止函数修改列表
方法:只传递副本
切片表示法创建列表的副本
print(unprinted[:],completed)
5.传递任意数量的关键字实参
**info
def dictionary(name,**info):
list1={}
list1['name']=name
for key,value in info.items():
list1[key]=value
return list1
list1_1=dictionary('Amy',location='China',age='18')
print(list1_1)
结果:
{'name': 'Amy', 'location': 'China', 'age': '18'}
5.导入函数
创建.py文件作为模块,包含要导入到程序的代码
import 模块名
导入特定的函数:
from 模块名 import 函数名1,函数名2
as 起别名:
from xxx import xxx as xxx
import 语句要放入到文件开头