Python函数

函数是一段可以重复使用的代码,通过传递的参数返回不同的结果,函数能够提高应用的模块性和代码的重复利用率。

目录:

函数
1.无参函数
2.带参函数
变量的作用域
1.全局变量
2.局部变量
lambda函数
内建函数
1.dir()
2.abs()
3.bool()
4.float()
5.int()
6.范围函数range()
7.求和函数sum()
8.最大值函数max()和最小值函数min()
9.表达式函数eval()
10.长度函数len()

函数

   Python中的函数都是语句和表达式的集合。函数的用法并没有限制,使用方法就像Python中其他值一样,对于重复使用的代码,需要编写为自定义函数以便于重复使用。函数包括无参函数和带参函数。

1.无参函数

1)自定义无参函数,语法格式如下:

def 函数名称():
    代码块
    return 表达式

  以关键字def开始,后面跟函数名和小括号,以冒号开头并缩进,最后使用return退出函数,有表达式则传递返回值,没有则返回None。函数是以字母、数字和下划线组成的字符串,但是不能以数字开头

无参函数调用语法如下:

[变量 = ] 函数名称()

使用赋值运算符“=”可以获得函数的返回值,使用函数是必须先定义再调用,否则程序会出现错误

演示1:

def add():   //定义无参函数add()
    op1 =10
    op2 =20
    rt  = op1+op2
    print op1,'+',op2,'=',rt
    return
add()  //调用函数

把演示1修改以下,用return语句返回值,代码如下:

def add():
    op1 =10
    op2 =20
    rt  = op1+op2
    return rt
i = add()
print '结果是:',i  //函数返回值赋予给i

//执行
结果是: 30

九九乘法表

演示:

def qin():
     for i in range(1,10):
        for j in range(1,i+1):
            print i, "*", j, "=" ,i*j,
        print "\t"
qin()

//执行
1 * 1 = 1 	
2 * 1 = 2 2 * 2 = 4 	
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 	
4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 	
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 	
6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 	
7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 	
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 	
9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 	

2)使用函数时经常会犯的错误,总结如下:

  • 函数的定义要先于函数的调用,否则会出错。
  • 函数的代码是一个整体,注意缩进。
  • 定义函数时要使用冒号,但调用函数时不能使用冒号。

3)结合上面所学做一下综合,写一个用户登录页面的脚本。

kgc={}
def newuser():     //定义创建新用户的无参函数                                        
    prompt1 = '新的用户:'
    while True:
        name = raw_input(prompt1)
        if (kgc.has_key(name)):       //has_key:用于判断name键是否存在kgc字典中                      
            prompt1 = '--name taken,try another:'
            continue
        else:
            break
    pwd = raw_input('输入密码:')
    kgc[name]=pwd
def olduser():              //定义已有账号的无参函数                                  
    name = raw_input('用户:')
    pwd = raw_input('密码:')
    password = kgc.get(name)     //获取name在kgc字典中的值          
    if password == pwd:
        print "登入成功"
    else:
        print "请检查账号和密码"
def showmenu():            //定义列表菜单,调用上两个无参函数                             
    prompt='''
        (N)创建新用户
        (E)已有用户登录
        (Q)退出
    输入选择:'''
    while True:
        choice = raw_input(prompt).strip()[0].lower() 
                //strip()表示去除字符串钱的多余字符,()表示空格
                //[0]表示字符串的第一个字符
                //lower()将字符变成小写                         
                
        print '\n--您的选择是:[%s]' %choice
        if choice not in 'neq':
            print '--invalid option,try again--'
        else:
            if choice=='n':
                newuser()
            elif choice=='e':
                olduser()
            else:
                print '成功退出'
                break
if __name__=='__main__':     //定义程序入口                      
    showmenu()

执行脚本

        (N)创建新用户
        (E)已有用户登录
        (Q)退出
    输入选择:n

--您的选择是:[n]
新的用户:qzt
输入密码:111

        (N)创建新用户
        (E)已有用户登录
        (Q)退出
    输入选择:e

--您的选择是:[e]
用户:qzt
密码:111
登入成功

        (N)创建新用户
        (E)已有用户登录
        (Q)退出
    输入选择:q

--您的选择是:[q]
成功退出

2.带参函数

1)带参函数的语法格式如下:

def 函数名称(形式参数列表):
    代码块
    return [表达式]

   通过语法,可以看出带参函数与无参函数的区别就是在函数名称后的小括号中有形式参数列表,参数列表实际上只是占位符,用于体现参数的个数,每个参数都没有提供具体的数值。

带参函数调用语法如下:

[变量 = ] 函数名称( 参数列表)

调用时只需要在每个参数传递对应的实际数值,就可以完成函数的调用。

演示1:

def add(x,y):   //定义带参函数
	return x+y
print add(1,2)  //调用

//执行
3

定义了函数add(),它有两个形式参数x和y,在函数的语句块中可以使用x和y,和使用变量是类似的。通过函数名add()和实际的参数值1和2进行调用,所以返回值是3

2)上面定义的是普通参数,又称位置参数,当调用函数时,传递的实际参数值是根据位置来跟函数定义的参数表匹配的,如下:

def aa(x,y):
    print x,y
aa(10,6)
aa(6,10)

//执行

10 6
6 10
>>> 

在函数aa(x,y)中,输出x,y值,x在前,y在后。调用aa(1,2)时,x的值是1,y的值是2;当调用aa(10,20)时,x的值是10,y的值是20,所以在最后的输出结果是不同的。

3)当程序比较繁琐时,参数的顺序是很难记住的,可以使用关键字参数。关键字参数实在调用函数时,明确指定参数值付给那个形参

语法:函数名称(形参1=实参1,形参2=实参2…)

如下:

def aa (x,y):
    print x,y
aa(x=10,y=6)
aa(y=6,x=10)

//执行
10 6
10 6
>>>

调用函数aa(x,y)指定了参数的名称和对应值(x=10,y=6)(y=6,x=10),所以在调用函数时,就不会因为位置的原因,而错乱顺序。

4)调用普通参数函数时,传入的参数个数必须和声明的参数个数一致。但关键字参数有一个特殊的作用,可以在定义函数时设置关键字参数的默认值,此时传入函数的参数就可以和声明的参数个数不一致了。

def aa(x,y=6):
    print x,y
aa(10)
aa(x=10)
//执行
10 6
10 6
>>> 



def aa(x,y=6):
    print x,y
aa(10,5)
aa(x=10,y=5)
//执行
10 5
10 5
>>>

定义时参数y的默认值是6,调用时,可以不传递y的值,只传递x的值即可,直接传值或使用参数名并赋值都可以所以,aa(10)和aa(x=10)结果是相同的,如果定义了y的值,则y的默认值将不生效。

注意:定义关键字参数默认值时需要注意,位置参数必须出现在默认参数之前,如下的函数定义时错误的:

def aa(x=1,y):
    print x,y
aa()

5)综合案例-计算器程序

①首先编写用来运算的函数,代码如下:

def operator(op1,op2,opFU):
         if opFU not in '+-*/':   //位置1
                  return -1
         if opFU == '+':        //位置2
                  result = op1+op2
         elif opFU == '-':
                  result = op1-op2
         elif opFU == '*':
                  result = op1*op2
         elif opFU == '/':
                  if op2 == 0:     //位置3
                           print '错误,除数不能为0! /n'
                           result = None
                  else:
                           result = op1/op2
         return result

在上面代码中,位置1处定义了函数operator(op1,op2,opfu),参数op1表示运算符前面的数值,op2表示运算符后面的数值,opfu表示运算符,然后先判断opfu是不是“+-*/”中的其中一个,如果不是,返回值是-1,表示程序出错。在接下来就是判断是哪个运算符号,就进行哪种运算处理。但是在判断除法运算符时,需要加一个条件,就是除数不能是0,因为除数是0在数学上是没有意义的,最后只要把运算的结果返回即可。

②字符串转为数值型的操作代码如下:

def convert(op):
         flag = True  //位置1
         for ch in op:  //位置2
                  if ch not in '1234567890':
                           flag = False
                           break
         if flag == True:  //位置3
                  return int(op)
         else:              //位置4
                  return None

在上面的代码中,首先定义了一个布尔型变量flag,用于判断数值的有效性,在for循环语句中,op是传进来的字符串,使用for循环判断它的每一个字符是不是在“1234567890”中,如果有一个不再,说明这个字符串不能转换为数值,flag的值为False,退出循环,否则flag的值不变,还是True,说明字符串可以转换为数值型。然后接下来做了相应的判断,把字符串op转换为了整型,使用的是int()函数。最后是如果不能转换为整型,返回的是None。
③主体代码如下:

if __name__=='__main__':
//以下是定义三个字符串的提示文字
    str1 = '请输入第一个数:\n'
    strfu = '请输入一个算数运算符:\n'
    str2 = '请输入第二个数:\n'
//下面是主体代码的无限循环操作,可以用来进行多次计算
    while True:
        print '需要退出程序,请输入字母q'
//以下是判断当键盘输入q时,就退出程序
        opp1 = raw_input(str1)
        ch = opp1.strip()[0].lower()
        if ch == 'q':
            break
//对输入的第一个字符串进行数值转换操作,convert()返回是None,说明不能转换,使用continue进入到下一次循环重新输入。
        op1 = convert(opp1)
        if op1 ==None:
            print '输入错误,请输入整数!\n'
            continue
//等待输入运算符,如果是“+-*/”中的一个,使用break结束循环,否则执行continue,重新输入
        while True:
            opfu = raw_input(strfu)
            if opfu in '+-*/':
                break
            else:
                print '运算符输入错误'
                continue
//下面是输入第二个数值,同样需要做转换操作,如果不能转换就需要重新输入
        while True:
            op2 = convert(raw_input(str2))
            if op2 == None:
                print "输入错误,请输入整数!\n"
                continue
            else:
                break
//下面就是调用函数operator进行运算,result不等于None就说明运算是正常的,显示出运算结果
        result = operator(op1,op2,opfu)
        if result <> None:
            print "计算%d %s %d = %d \n" %(op1,opfu,op2,result)
print '程序退出了'

把上面三段代码连接起来,就完成操作了

最终代码效果如下:

def operator(op1,op2,opFU):
         if opFU not in '+-*/':
                  return -1
         if opFU == '+':
                  result = op1+op2
         elif opFU == '-':
                  result = op1-op2
         elif opFU == '*':
                  result = op1*op2
         elif opFU == '/':
                  if op2 == 0:
                           print '错误,除数不能为0! /n'
                           result = None
                  else:
                           result = op1/op2
         return result
def convert(op):
         flag = True
         for ch in op:
                  if ch not in '1234567890':
                           flag = False
                           break
         if flag == True:
                  return int(op)
         else:
                  return None

if __name__=='__main__':
         str1 = '请输入第一个数:\n'
         strFU = '请输入一个运算符:\n'
         str2 = '请输入第二个数:\n'
         while True:
                  print '需要退出程序,请输入字母q'
                  opp1 = raw_input(str1)
                  ch = opp1.strip()[0].lower()
                  if ch == 'q':
                           break
                  op1 = convert(opp1)
                  if op1 == None:
                           print '输入错误,请输入整数!/n'
                           continue
                  while True:
                           opFU = raw_input(strFU)
                           if opFU in '+-*/':
                                    break
                           else:
                                    print '运算符输入错误'
                                    continue
                  while True:
                           op2 = convert(raw_input(str2))
                           if op2 == None:
                                    print "输入错误,请输入整数!\n"
                                    continue
                           else:
                                    break
                  result = operator(op1,op2,opFU)
                  if result <> None:
                           print "计算%d %s %d = %d \n" %(op1,opFU,op2,result)
         print '程序退出了'

测试效果

需要退出程序,请输入字母q
请输入第一个数:
11
请输入一个运算符:
+
请输入第二个数:
11
计算11 + 11 = 22 

变量的作用域

作用域是指变量在程序中的应用范围,而变量声明的位置决定它的作用域,Python按作用域区分有局部变量和全局变量。

全局变量:最高级别变量,全局有效,存活到程序结束(除非被删除),所有函数都能访问全局变量。

局部变量:是在 函数内部定义的变量,只能在函数内部使用(有限制范围)

 1. 局部变量的作用域仅限于定义它的函数,全局变量的作用域在整个模块内部都是可见的。在同一个函数中,不允许有同名的局部变量在不同函数中,可以有同名的局部变量。在同一个程序中,全局变量和局部变量同名时,局部变量具有更高的优先级

演示:

def addage(age):
    age += 1
    print 'addage():_age=%d age=%d' %(_age,age)
    return age
_age = input('请输入年龄:\n')
rt = addage(_age)
print 'main():_age = %d'%_age
print 'main(): rt=%d' %rt

//执行
请输入年龄:
11
addage():_age=11 age=12
main():_age = 11
main(): rt=12

在上面的代码中,函数addage(age)中定义了局部变量age,在全局范围定义了全局变量_age。_age的值是由我们键盘输入的,它在全局都生效,所以在addage(age)函数中也可以对它进行引用。当键盘输入是10时,_age的值是10,调用“rt=addage(_age)”,就是把全局变量_age的值10传给了函数,此时addage(age)的局部变量age的值也是10,执行age += 1后,age值成为了11,而全局变量_age的值不发生变化,打印输出“_age=10 age=11”,函数的返回值age的值是11,由rt接收,所以打印“_age=10,rt=11”

通过上面的代码示例,可以看出Python采用的是值传递的方式,但实际上并不是这样。Python采用的是值传递和引用传递相结合的方式,当传递可变对象时(如字典或者列表),相当于传引用,而不可变对象(如数字、字符或元组)就是值传递。上面传递的是字符串,所以是值传递的方式。

在Python中尽量不使用全局变量,因为程序中可以自由的访问全局变量,其他人并不知道哪个变量是全局变量,非常容易出现引用错误,这种错误也很难发现和更正的。

2.局部变量在函数外引用不到

演示:

def addage(age):
         age += 1
         print 'addage():_age=%d age=%d' %(_age,age)
         return age
_age = input('输入年龄: \n')
rt = addage(_age)
print 'main():_age = %d' %_age
print 'main():age = %d' %age	\\本行执行会出现错误,因age为局部变量无法执行
print 'main():rt = %d' %rt

3.声明局部变量到全局

global的作用是声明变量为全局变量,即使变量定义在函数内部,加上global后,也可以在全局范围访问。

演示:

def addage(num):
         global age	\\发布局部变量到全局
         age = num + 1
         print 'addage():_age=%d age=%d' %(_age,age)
         return age
_age = input('输入年龄: \n')
rt = addage(_age)
print 'main():_age = %d' %_age
print 'main():rt = %d' %rt
print 'main():age = %d' %age

使用global语句声明的全局变量名不能与其中的局部变量重名,而且尽量要避免在函数中使用global定义全局变量,减少程序的不可预知性。

lambda函数

lambda函数的作用是创建匿名函数,是一种声明函数的特殊方式

语法:lambda params:expr

演示:

def sum1(x,y):
    return x+y

sum2 = lambda x,y : x+y
print sum1(3,4)
print sum2(3,4)

实现的是相同的功能,但lambda函数更加简洁,只用一条语句实现,所以lambda也称为lambda表达式,注意:使用lambda只能是表达式不能包含if、for等条件循环语句,对于不需要复用、简单的匿名函数,使用lambda能起到很好的效果。 

内建函数

1.dir()函数可以返回关于任何值的相关信息,可以用于任何对象,包括字符串、数字、函数、模块、对象和类。相当于帮助手册。

语法:dir([object])

object是可选参数无参数时,返回当前范围内的变量,带参时,返回的是参数的属性、方法列表

演示:

>>> dir()  //无参数时,返回当前范围内的变量
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'sum1', 'sum2']

>>> dir(sum1)  //带参时,返回的是参数的属性、方法列表
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

dir()函数还有一个功能非常有用,那就是查看内建函数,并查看个别内建函数的详细用法。

演示:

>>> dir(__builtins__)  // //查看内置函数
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

利用help查看内建函数详细用法

>>> help (sum)  //查看sum内建函数的详细用法
Help on built-in function sum in module __builtin__:

sum(...)
    sum(iterable[, start]) -> value
    
    Return the sum of an iterable or sequence of numbers (NOT strings)
    plus the value of 'start' (which defaults to 0).  When the sequence is
    empty, return start.

2.abs()函数能够返回一个数字的绝对值,即整数

演示:

>>> abs(10)
10
>>> abs(-10)
10
>>> o = -3
>>> abs(o)
3

3.bool()函数返回值是True或False,它是布尔值的简写,可以用来判断字符是否为空。

函数返回值为True或False;
        当参数为数字时:0返回False,非0返回True。
        当参数为字符串时,None或空字符串返回False,否则为True。
        当参数为空的列表、元组、字典时,返回False,否则为True。

演示:

>>> bool()
False
>>> bool(0)
False
>>> bool(5)
True
>>> bool(-5)
True
>>> bool(None)
False
>>> bool('zzz')
True
>>> bool('11,22')
True

4.float()函数用于转换数据为float(浮点)类型。

演示:

>>> float('25')
25.0
>>> float(3)
3.0
>>> float(111.222)
111.222
>>> float('111.222')
111.222

字符串和数字都可以转换为float类型,如果不能转换,就会报错。

5.int()函数可以将数据转换为整数。

演示:

>>> int(2002.05)  //浮点
2002
>>> int('28') //字符串
28

>>> int('2002.05')  //字符串,带浮点(报错)

Traceback (most recent call last):
  File "<pyshell#37>", line 1, in <module>
    int('2002.05')
ValueError: invalid literal for int() with base 10: '2002.05'

需要注意当参数为字符串,参数只能是整数,如果是浮点就会报错。

6.范围函数range()

>> range(0,10)  //表示范围0-9
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(0,150,50)  //第三位的数字代表步长,是可选参数
[0, 50, 100]
>>> range(100,0,-10)  //负数为倒着输出
[100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

>>> for i in range(0,5):  //配合for使用
	print i
	
0
1
2
3
4

7.求和函数sum()

演示:

>>> num = range(0,500,50)
>>> num
[0, 50, 100, 150, 200, 250, 300, 350, 400, 450]
>>> print (sum(num))  //对元组中的值进行累加求和操作
2250

8.最大值函数max()和最小值函数min()

演示:

>>> min (50,60,100)   //输出最小值
50
>>> min ('d','z','g','l')
'd'

>>> max(50,60,100)   //输出最大值
100
>>> max ('d','z','g','l')
'z'

9.表达式函数eval()

可以计算表达式的值

演示:

>>> eval ('100*9')
900
>>> eval (raw_input("请输入表达式"))
请输入表达式9*9+9
90

10.长度函数len()

>>> len ('qinlishzi')
9
>>> aa = ['python','linux','mysql','php']
>>> len(aa)
4
>>> zz={'zhangsan':123,'lisi':456,'wangwu':678}
>>> len(zz)
3

环境:使用python版本2

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章