Python学习笔记之疑问 1:def 是什么意思

1.def (define的前三个字母)是一个关键字,用来声明函数。

2.def 声明函数的格式为:

def 函数名(参数1,参数2,...,参数n):

     函数体

例如:

def fib(n):                   
    print 'n =', n            
    if n > 1:                 
        return n * fib(n - 1)
    else:                     
        print 'end of the line'
        return 1

3.函数返回值类型不固定,声明函数时不需要指定其返回值的数据类型。
4.函数甚至可以没有返回值,如果没有返回值,系统回默认返回空值 None。
5.可选参数:可以指定参数的默认值,如果调用时没有指定参数,将取默认值。
例如:
def approximate_size(size, a_kilobyte_is_1024_bytes=True):
    print(approximate_size(1000000000000,False))  
    print(approximate_size(1000000000000))        

6.命名参数:通过使用命名参数还可以按照任何顺序指定参数。只要你有一个命名参数,它右边的所有参数也都需要是命名参数。
例如:
>>>from humansize import approximate_size>>>approximate_size(4000, a_kilobyte_is_1024_bytes=False)
'4.0 KB'>>>approximate_size(size=4000, a_kilobyte_is_1024_bytes=False)
'4.0 KB'>>>approximate_size(a_kilobyte_is_1024_bytes=False, size=4000)
'4.0 KB'>>>approximate_size(a_kilobyte_is_1024_bytes=False,4000)
File "<stdin>", line 1 SyntaxError: non-keyword arg after keyword arg>>>approximate_size(size=4000,False)
File "<stdin>", line 1 SyntaxError: non-keyword arg after keyword arg

原文地址:https://www.cnblogs.com/littleebeer/p/3352380.html