Python 编程入门/Python 编程 - 函数
外观
Python 中的函数是一组代码,执行单个实用程序,可能或可能不返回结果。函数提供了将复杂代码分解为可重用代码块的方法,这些代码块可以用作不同程序的构建块。Python 已经提供了许多内置函数,例如 print、input 等。您可以编写自己的 Python 函数,称为用户定义函数。
如前所述,可以编写一组代码来执行某些实用程序。以下规则提供了编写自己的函数的指南。当用户定义的函数名称调用函数时,函数将被执行。
函数块以关键字“def”开头,后跟用户提供的函数名称和括号 ()。用户提供给函数的输入放在括号内,进一步扩展括号可用于定义要在用户定义函数内使用的新的参数。Python 提供文档,可用于描述函数、作者、创建日期和用户定义函数的目的等。可以使用用户定义函数名称后的 __doc__ 关键字访问用户定义函数的文档。关键字 return 用于退出函数,可选地将表达式传递给函数的调用者。
def functionname(parameters): ‘’’function docstring’’’
代码块
Return(expression)
例子
>>> def squareofnum(n):
This function returns the square of the number passed as the parameter
return n*n
>>> print squareofnum(3)
9
>>> print squareofnum.__doc__
This function returns the square of the number passed as the parameter
>>>
>>> def myappendlist(mylist,a):
this function appends a list to the already existing list
mylist.append(a)
return
>>> a=[1,2,3,4]
>>> b=[6]
>>>
>>> a
[1, 2, 3, 4]
>>> b
[6]
>>> print myappendlist(a,b)
None
>>> a
[1, 2, 3, 4, [6]]
>>>
可以通过按正确的顺序传递参数、提及关键字参数、默认参数、可变长度参数来调用函数。
#function is defined here
>>> def newfunction(n):
print "inside function"
answer= n*n*n
return answer
>>> print newfunction(2)
inside function
8
>>> print newfunction()
Traceback (most recent call last):
File "<pyshell#203>", line 1, in <module>
print newfunction()
TypeError: newfunction() takes exactly 1 argument (0 given)
>>>
>>> def vistingcard(name, age="22"):
print "the name is %s" %name
print "the age is %d" %age
return
>>> vistingcard("new", 33)
the name is new
the age is 33
>>> vistingcard(age=34, name="no name")
the name is no name
the age is 34
>>> vistingcard(36, "newname")
the name is 36
Traceback (most recent call last):
File "<pyshell#221>", line 1, in <module>
vistingcard(36, "newname")
File "<pyshell#218>", line 3, in vistingcard
print "the age is %d" %age
TypeError: %d format: a number is required, not str
>>>
可以使用 * 将可变长度参数传递给函数。以下提供了示例。
>>> def variableargfunc(*argu):
print "inside function"
for a in argu:
print a
return
>>> variableargfunc(10)
inside function
10
>>>
>>> variableargfunc(10,20)
inside function
10
20
>>>
>>> variableargfunc([1,2,3,4,5])
inside function
[1, 2, 3, 4, 5]
在使用它们的函数的作用域内定义了两种类型的变量。函数内的变量对函数是局部的,被称为函数的局部变量,全局变量是在变量作用域之外定义的。
>>> globalvariable=0
>>> def scopefunc(n,m):
globalvariable=n+m
print "the local variable is %d " %globalvariable
return globalvariable
>>>
>>> print "outside the function scope %d " %globalvariable
outside the function scope 0
>>> scopefunc(5,6)
the local variable is 11
11
>>> print "outside the function scope %d " %globalvariable
outside the function scope 0
>>>