[python]函数

1. 简介

Python是通过引用调用的,因此函数内对参数的改变会影响到原始对象。

实际上,只有可变对象会受此影响;对不可变对象来说,不会被影响,类似于按值调用。

2. 语法格式

def function_name([arguments]):
    "optional documentation string"
    function_suite

函数语法包括:

  • def关键字
  • 函数名加上参数
  • 函数作用说明(可选)
  • 函数体

3. 示例

def addMe2Me(x):
    'apply + operation to argument'
    x = x + x
    return (x)
 
print addMe2Me(2)
print addMe2Me('Hello')

运行结果:

4
HelloHello

函数的参数也可以有默认值,在函数定义中,参数以赋值语句的形式提供。

  • 在函数调用时,如果没有提供参数的值,则使用默认值。
  • 在函数调用时,如果提供参数的值,则使用提供的值,而非默认值。

示例:

def foo(debug = True):
    'Determine if in debug mode, whether the default value is used'
    if debug:
        print 'Now in debug mode'
    print 'Done'
    
foo()

print 

foo(False)

运行结果:

Now in debug mode
Done

Done

 可以看到:

  • 第一个foo()函数,没有提供参数,因此使用默认值。
  • 第二个foo(False)函数,提供参数,因此使用提供的参数,而非默认值。
原文地址:https://www.cnblogs.com/sophia194910/p/5016326.html