python中使用def关键字来定义参数,之后是函数名,函数名后面用小括号列出参数列表,使用冒号结束,参数可有可无.
def test():
global global_value #global可以在一个作用域内定义一个全局变量
global_value="abdsd"
temp="hello word"
print("aaa") #函数体也需要缩进
print(locals()) #以字典形式返回当前作用域的全部变量与值
print(globals()) #以字典形式返全部全局变量与值
test() #函数的调用
print(global_value)
定义匿名函数
使用lambda定义一个匿名函数
count=lambda x,y:x*y #def count(x,y): return x*y
show_value=count(3,5)
print(show_value)
count=lambda :1+12 #可不带参数
show_value=count()
print(show_value)
传参
默认参数,从右向左写默认参数,
def test(num1,num=6):
print(num1,num)
test(1)
test(1,7)
'''
1 6
1 7
’‘’
关键字传参,传参顺序可以由自己决定
def test(num1,num):
print("函数体内:%s,%s" %(num1,num))
a=6
b=7
test(a,b)
print(a)
print(b)
test(num=a,num1=b) #改变传参的顺序
print(a)
print(b)
'''
函数体内:6,7
6
7
函数体内:7,6
6
7
'''
在函数内部改变函数外部的值(使用可修改对象,如:字典,列表)
def test(list_test):
list_test[1]="aaaa"
print("函数体内:%s" %(list_test))
list_test=[1,2,3,4,5]
test(list_test)
print(list_test)
变参的传递
- 元组传参的形式,通常使用*args进行形参的设置 。
- 字典传参的形式,通常使用**kwargs进行形成的设置 。
- 可变参数可以传递多个。
- 元组参数一定要在字典参数前面。
#通过元组进行可变参数的传递
def dest_tuplel(*tuples_values):
print(tuples_values,type(tuples_values))
#传入的第一个参数会给arg,剩下的组合成元组传递给tuples_values
def dest_tuplel(arg,*tuples_values):
print(tuples_values,type(tuples_values))
通过字典进行可变参数的传递
def test_dict(**info):
print(info,type(info))
#函数的调用的时候,必须通过键值对的方式
test_dict(name='小明',age=18,height=180)
多类型参数传递
def multiple_types(arg,*args,**info):
print(arg,type(arg))
print(args,type(args))
print(info,type(info))
multiple_types(1,2,3,4,5,6,name='linhua',age='19',height='168')
'''
输出:
1 <class 'int'>
(2, 3, 4, 5, 6) <class 'tuple'>
{'name': 'linhua', 'age': '19', 'height': '168'} <class 'dict'>
'''
返回值
函数的返回值可以是一个或者多个,使用逗号分开。返回值可以指定,也可以不写(不写默认为None)
函数可以返回任意类型的值,包括列表和字典等
#返回一个字典
def test(list_test):
infor={'username':"linhua","sex":"girl","age":list_test}
return infor
list_test=str(input("请输入"))
result_value=test(list_test)
print(result_value["username"])
获取函数的返回值
def test(list_test):
num1=list_test**3 #5*5*5
num2=list_test+6
return num1,num2
list_test=int(input("请输入"))
value_1,value_2=test(list_test) #两个变量来获取返回值
print(value_1,value_2)
导入模块
#info.py
def info_test():
print("lalala")
#index.py
#使用info.test()
1.导入整个模块
#index.py
import info #import + 文件名
info.info_test()
2.导入特定函数
#index.py
from info import info_test #from 文件名 import 函数名
info_test()
指定别名(导入的模块中有可能和现有或其他导入文件重名,所以用as来解决这个问题)
#模块指定别名
import info as info_old
info_old.info_test()
#函数指定别名
from info import info_test as infotest
infotest()