(三)3-3 Python的一般形式和参数

Python的函数
a、函数的一般形式
定义一个函数,需要满足以下规则
  函数代码块以def关键词开头,后接函数标识符名称和圆括号()
  任何传入参数和自变量必须放在圆括号中间,圆括号之间可以用于定义参数
  函数的第一行语句可以选择性地使用文档字符串,用于存放函数说明。
  函数内容以冒号起始,并且缩进。
  return [表达式] 结束函数,选择性地返回一个值给调用方,不带表达式的return相当于返回None
函数的简单例子

def sum(x,y):
    print('x = {0}'.format(x))
    print('y = {0}'.format(y))
    # print('x = %d' %x)
    # print('y = %d' %y)
    return x + y
a = 10 
b = 20
c = sum(a,b)
print(c)

运行结果:

x = 10
y = 20
30

注:
1、def 是函数的关键字,格式就是这样
2、def 后面跟的就是函数名,这个可以自定义
3、括号里面传递的是函数的参数,该参数在函数中都可以使用
4、sum(a,b)在执行的时候就把a和b传递给sum函数
5、return 是代表当我们调用函数的时候返回结果,调用函数返回两个数的和,c=a+b

b、函数的各种参数类型

经常会看到func(*args,**kwargs)的函数定义方式
例1:
1、给变量b设置一个默认值
  如果实参传入的时候,指定了b的值,那b没有值时,才会有默认值

def funcA(a,b=0):
    print("a = " + str(a))
    print("b = " + str(b))
funcA(1)

运行结果:

a = 1
b = 2

2、参数为元组(tuple)

def funcB(a,b,*c):
    print(a)
    print(b)
    print("length of c is :{0}".format(len(c)))
    print(c)
funcB(1,2,3,4,5,6)
#或者
#test = ("hello","world")
#funcB(1,2,*test)

运行结果:

1
2
length of c is :4
(3, 4, 5, 6)

3、参数为字典

def funcC(a,**b):
    print(a)
    print(b)
    for x in b :
        print(x + ":" + str(b[x]))
    print("*"*10)
    for k,v in b.iteritems():
        print(k + ":" + v)
funcC(100,x="hello",y="cnblogs")
print("*"*20)
args = {"1":"a","2":"b"}
funcC(a = 100,**args )

运行结果:

100
{'y': 'cnblogs', 'x': 'hello'}
y:cnblogs
x:hello
**********
y:cnblogs
x:hello
********************
100
{'1': 'a', '2': 'b'}
1:a
2:b
**********
1:a
2:b
原文地址:https://www.cnblogs.com/pythonlx/p/7767814.html