Home >Backend Development >Python Tutorial >Python def函数的定义、使用及参数传递实现代码

Python def函数的定义、使用及参数传递实现代码

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-16 08:42:551882browse

Python编程中对于某些需要重复调用的程序,可以使用函数进行定义,基本形式为:

def 函数名(参数1, 参数2, ……, 参数N):

执行语句函数名为调用的表示名,参数则是传入的参数,可以更具需要定义,也可以没有。

# 例1:简单的函数使用
# coding=gb2312

# 定义函数
def hello():
  print 'hello python!'
  
# 调用函数    
hello()
  
>>> hello python!

函数可以带参数和返回值,参数将按从左到右的匹配,参数可设置默认值,当使用函数时没给相应的参数时,会按照默认值进行赋值。

# 例2:累加计算值
# coding=gb2312

# 定义函数
def myadd(a=1,b=100):
  result = 0
  i = a
  while i <= b:  # 默认值为1+2+3+……+100
    result += i  
    i += 1
  return result

# 打印1+2+……+10    
print myadd(1,10)
print myadd()    # 使用默认参数1,100
print myadd(50)   # a赋值50,b使用默认值
  
>>> 55
>>> 5050
>>> 3825

Python 函数的参数传递时,值得注意的是参数传入时若为变量会被当作临时赋值给参数变量,如果是对象则会被引用。

# 例3:
# coding=gb2312

def testpara(p1,p2):
  p1 = 10
  p2.append('hello')

l = []   # 定义一数组对像
a = 20   # 给变量a赋值
testpara(a,l) # 变量a与对象数组l作为参数传入
print a   # 打印运行参数后的值
for v in l: # 打印数组对象的成员
  print v
    
>>> 20    # 调用函数后a变量并未被复值
>>> hello  # 而对象l数组则增加成员hello
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Python异常处理总结Next article:Python-基础-入门 简介