您的位置:首页 > 其它

关于函数的总结之一

2016-04-19 20:54 447 查看
1、前言

在每种语言中,总是会存在函数,那么为什么每种语言都有函数这个东西呢?

函数,简单的来说,是一种对程序在逻辑上进行结构化的一种编程方法,主要就是将需要解决的问题来进行抽象,来进行分解,从而达到代码复用的目的。

2、函数的基本概念

创建函数如下:

>>> def createFunction(x,y):
...     return x+y
函数对象或者函数引用如下:

>>> createFunction
<function createFunction at 0x7f8bfb925488>


函数调用:

>>> createFunction(3,2)
5
在函数的返回值方面有几个分类如下:

a、 当返回0个值也就是没有返回值的时候,返回的值为None

b、当返回值为1个的时候,返回值为object

c、当返回值大于1个的时候,返回值为一个tuple --当返回值为tuple的时候,可以进行解包,也就是unpack,如下:

>>> def returnaTuple(x):
...     return x,3,4
...
>>> x,y,z = returnaTuple(1)  #unpack操作,将返回值分别进行赋值
>>> x,y,z
(1, 3, 4)


函数的参数:
包括函数的形参:在函数中定义的参数,例如f(x)中的x表示为形参

在调用函数的实参:也就是在调用函数的时候传入的参数,例如multi(4,5)也就是实际参数

3、调用参数

在调用参数的时候,有几种特殊的参数需要注意,一个是元组,也就是非关键字参数;一个是字典,也就是关键字参数。

在进行调用的语法如下:

>>> def func(*tuple_nonkw_args,**dict_kw_args):
...     pass
...
a、 顺序问题:关键字参数必须位于非关键字后面否则会报错syntax error,如下所示:

>>> func(3,4,name='kel',4)
File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
b、 关键字参数,必须是变量等于的形式,如下:

>>> func(3,4,'name'='kel')
File "<stdin>", line 1
SyntaxError: keyword can't be an expression
c、 在字典做参数的时候:

在使用字典的时候,必须使用双星号,也就是**dict;可以使用关键字方法,例如name=‘kel’

>>> func(1,**dict)
"(1,) {'name': 'kel'} "
>>> func(1,name='kel')
"(1,) {'name': 'kel'} "
>>> <strong>func(1,dict) #在使用字典的时候,如果字典不用双星号进行标记,那么就会出现如下错误,将字典的值也传递给了tuple</strong>
"(1, {'name': 'kel'}) {} "
函数调用参数主要规则如下:

>>> def func(positional_args,keyword_args,*tuple_nonkw_args,**dict_kw_args):
...     pass
...
4、 在未声明不允许调用函数

在未进行声明的时候,不允许调用函数。

在声明的时候,顺序是可以改变的,只要在调用的时候,已经声明过了即可,如下:

>>> def foo():
...     print 'foo is called'
...     bar()
...
>>> def bar():
...     print 'bar is called'
...
>>> foo()
foo is called
bar is called
从上面例子可以看到,在定义函数foo的时候,并没有定义bar,但是函数定义成功

在调用函数foo的时候,bar函数已经声明了,从而可以正确执行

在python中,前向引用函数或者后向引用函数都是可以的,不会出现报错,但是在调用的时候,函数一定已经存在声明。

以下内容是从python核心编程中引出,如下:

#!/usr/bin/env python

from operator import add,sub
from random import choice,randint

MAXTRIES = 2   #用来定义最大尝试次数
op = {'+':add,'-':sub} #主要用字典来定义使用的计算

def doprobe():
'use to print the calculate math and the check result'
nums = [randint(1,10) for i in range(2)]
nums.sort(reverse=True)
opera = choice('+-')
oops = 0
pr = '%d %s %d ' %(nums[0],opera,nums[1]) #打印出来的计算式
answer = op[opera](*nums) #在此,直接使用字典来调用方法,并且直接将参数作为一个元组进行传入然后计算。
ans = '%d %s %d = %d' % (nums[0],opera,nums[1],answer) #计算结果
while True:
try:
print pr
userinput = int(raw_input('answer is : '))
if userinput == answer:
print 'correct'
break
elif oops == MAXTRIES:
print ans
else:
print 'incorrect ,try again'
oops += 1
except (KeyboardInterrupt,EOFError,ValueError):
print 'invalid input ...try again'

def main():
'this is to sure continue the math'
while True:
doprobe()
try:
userchoice = raw_input('continue ? [y]/
').lower()
if userchoice and userchoice[0] == 'n':
break
except:
print 'quit for math'
break

if __name__ == '__main__':
main()


执行结果如下:

[root@python 419]# python easyMath.py
10 + 1
answer is : 11
correct
continue ? [y]/

10 + 5
answer is : 12
incorrect ,try again
10 + 5
answer is : 13
incorrect ,try again
10 + 5
answer is : 1
10 + 5 = 15
10 + 5
answer is : 1
10 + 5 = 15
10 + 5
answer is : 15
correct
continue ? [y]/
n


在以上例子中:

主要使用两个方法来分割整个计算,在main中主要是用来做是否循环的询问,在doprobe函数中,主要是用来进行打印计算公式和计算结果。

在进行调用函数的时候,第一个是使用字典来实现case ,when的选择,第二个是在传递计算参数的时候,直接使用一个元组来调用参数。

在进行模块编写的时候,常量写在最上面,从而可以直接使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: