Python函数

2020-09-25  本文已影响0人  子鱼_谋

函数定义

Python 定义函数使用 def 关键字,一般格式如下:

def 函数名(参数列表):
    函数体

#空函数
def func():
    pass

#函数调用
func()

参数传递

def show(a, b):
    print("a, b".format(a, b))

show(1, 2)

在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象

# 可写函数说明
def changeme( mylist ):
   "修改传入的列表"
   mylist.append([1,2,3,4])
   print ("函数内取值: ", mylist)
   return
 
# 调用changeme函数
mylist = [10,20,30]
changeme( mylist )
print ("函数外取值: ", mylist)

输出:
函数内取值:  [10, 20, 30, [1, 2, 3, 4]]
函数外取值:  [10, 20, 30, [1, 2, 3, 4]]

参数

调用函数时可使用的正式参数类型:必需参数,关键字参数,默认参数,不定长参数

  1. 必需参数
def printme( str ):
   print (str)
   return
 
# 调用 printme 函数,不加参数会报错
printme()
  1. 关键字参数
    函数调用使用关键字参数来确定传入的参数值
def printme( str ):
   print (str)
   return
 
#调用printme函数
printme( str = "python")

函数参数的使用不需要使用指定顺序

#可写函数说明
def printinfo( name, age ):
   print ("名字: ", name)
   print ("年龄: ", age)
   return
 
#调用printinfo函数
printinfo( age=50, name="runoob" )
  1. 默认参数
    调用函数时,如果没有传递参数,则会使用默认参数
def printinfo( name, age = 35 ):
   print ("名字: ", name)
   print ("年龄: ", age)
   return
 
#调用printinfo函数
printinfo( age=50, name="runoob" )
print ("------------------------")
printinfo( name="runoob" )

输出:
名字:  runoob
年龄:  50
------------------------
名字:  runoob
年龄:  35
  1. 不定长参数
    加了星号 * 的参数会以元组(tuple)的形式导入,存放所有未命名的变量参数。
def printinfo( arg1, *vartuple ):
   print ("输出: ")
   print (arg1)
   print (vartuple)
 
# 调用printinfo 函数
printinfo( 70, 60, 50 )

输出: 
70
(60, 50)

加了两个星号 ** 的参数会以字典的形式导入。

def printinfo( arg1, **vardict ):
   print ("输出: ")
   print (arg1)
   print (vardict)
 
# 调用printinfo 函数
printinfo(1, a = 2, b = 3)

输出: 
1
{'a': 2, 'b': 3}

注意,可变参数一定是最后一个参数

返回值

python 不需要在函数定义的时候声明返回值,直接在函数里面return相应数据,默认返回null

def show():
    pass
result = show()
#result = null

#多个返回值
def retun_nums():
    return 1, 2, 3, 4
re = return_nums()
或者
r1, r2, r3, r4 = return_nums()

print(re)
print(r1,r2,r3,r4)

输出:
(1, 2, 3, 4)
1 2 3 4

局部变量

可以通过 global 关键字引用全局变量

x=50
def test():
    global x
    x=2
    print("1 x is {}".format(x))

test()
print("2 x is {}".format(x))

结果:
1 x is 2
2 x is 2

lambda

定义用户自定义函数名

def test(n):
    return n + 1
print(test(10))

test1 = lambda n : n + 1
print(test1(10))

结果
11
11
上一篇下一篇

猜你喜欢

热点阅读