python学习—Day35—函数

python函数:

社么是函数
•函数就是完成特定功能的一个语句组,这组语句可以作为一个单位使用,并且给它取一个名字。
•可以通过函数名在程序的不同地方多次执行(这通常叫函数调用)。
•预定义函数

   可以直接使用

•自定义函数

   用户自己编写


为什么使用函数
•降低编程难度

   - 通常将一个复杂的大问题分解成一系列的小问题,然后将小问题划分成更小的问题,当问题细化为足够简单时,我们就可以分而治之。各个小问题解决了,大问题就迎刃而解了。

•代码重用

   - 避免重复劳作,提供效率


函数的定义和调用

   - def 函数名([参数列表]):    //定义。注意冒号

   - 函数名([参数列表])     //调用


函数名命名规则:可以是数字字母下划线组成的,但是不能以数字开头。函数名由多个单词组成,则第一个单词之后的所有单词的首字母都要大写。也可以使用下划线连接
变量的定义都是小写。类的命名要所有单词首字母都要大写。

#@File :hanshu_demo.py

def fun():
    sth = raw_input("Please input number: ")  #判断输入是否为纯数字
    try:					\\捕获异常。没有异常执行下面的代码块
        if type(int(sth)) == type(1):
            print "%s is a number" %sth
    except:					\\出现异常时执行这里的代码。这里还可以指定确定的异常:except ValueError:
        print "%s is not number" %sth

fun()
Please input number: 13 45
13 45 is not number



函数的参数:

形式参数和实际参数

   - 在定义函数时,函数名后面括号中的变量名称叫做“形式参数”,或者称为“形参”

   - 在调用函数时,函数名后面括号中的变量名称叫做“实际参数”,或者称为“实参”


def fun(x, y):
    print x + y            #这里 + 加号,用于数字的相加,字符串的连接。
fun('a', 'b')

def fun1(x, y):             #这里的X,Y就是形参
    if x > y:
        print x
    else:
        print y
fun1(3, 4)                  #调用函数时,这里使用的是实参。

import sys
def isNum(s):
    for i in s:
        if i in '0123456789':
            pass
        else:
            print "%s is not a number" %s
            sys.exit()
    else:
        print "%s is a number" %s
isNum(sys.argv[1])
ab
4
bv is not a number


练习:

打印系统的所有PID
•要求从/proc读取。
•os.listdir() \\返回列表,每个列表元素为字符串。

import os
def isNum(s):
    for i in s:
        if i in '0123456789':
            pass
        else:
            # sys.exit()          #不是数字会直接退出脚本
            break                   #不满足条件退出当前循环
    else:
        print s
for i in os.listdir('/proc'):
    isNum(i)
返回所有的pid。


缺省参数(默认参数)

   def fun(x, y=100):

       print x,y

   fun(1,2)

   fun(1)


def defult(y, x=100):   #如果只赋值一个默认形参,一定要放在后面。否则报错。
    print x + y
defult(2)               #如果两个形参都有默认值,但是只指定一个参数,那么默认赋值给前面的形参。
defult(2, 10)
defult(y=20, x=22)
ab
4
102
12
42



函数的变量:

局部变量和全局变量

   - Python中的任何变量都有特定的作用域

   - 在函数中定义的变量一般只能在该函数内部使用,这些只能在程序的特定部分使用的变量我们称之为局部变量

   - 在一个文件顶部定义的变量可以供文件中的任何函数调用,这些可以为整个程序所使用的变量称为全局变量


#@File :hanshu_bianliang.py

x = 'global var'
y = 10
def fun():
    x = 100
    print x
    global y
    y += 1
    print y
    global z
    z = 'abc'
    print locals()        #函数里面的变量。以字典的形势显示。
print y
print '##########     fun     ##########'
fun()
print '##########     fun-end     ##########'
print x
print y
print z             #即使在函数中使用global使z成为全局变量,也需要前面对函数fun调用过才可以。没有调用过函数,一样无法打印zprint locals()      #脚本执行时的变量。
10
##########     fun     ##########
100
11
{'x': 100}
##########     fun-end     ##########
global var
11
abc
{'__builtins__': <module '__builtin__' (built-in)>, '__file__': 'C:/Users/xiaojingjing/PycharmProjects/untitled1/liziyan/hanshu_bianliang.py', '__package__': None, 'fun': <function fun at 0x03559930>, 'x': 'global var', 'y': 11, '__name__': '__main__', 'z': 'abc', '__doc__': None}


函数的返回值:

函数返回值

   - 函数被调用后会返回一个指定的值

   - 函数调用后默认返回None

   - return 返回值

   - 返回值可以是任意类型

   - return执行后,函数终止

   - return与print区别


#@File :hanshu_return.py

def fun():
    print 'hello world'
    return 1                #增加这里,当执行print fun()hi返回这个值
    print 'abc'             #这不打印,因为函数遇到return就是结束,直接退出了。
print fun()                 #多输出了一个None,这个其实就是函数的返回值。因为函数中没有需要返回的值
hello world
1



用来判断字符串中是否为纯数字。
import sys
def isNum(s):
    if s.isdigit():
        return True
    return False
for i in sys.argv[1]:           #这里在edit编辑中指定的123.如果修改为‘abc’(非数字),返回为空。
    if isNum(i):
        print i
1
2
3



多类型传值和冗余参数:

#@File :hanshu_chuancan.py

def fun(x, y):
    return x + y
def fun1(x, y, z):
    return x + y + z

print(fun(1, 2))
t = (3, 4)
print(fun(*t))             #多类型传值,将 t 这个元组中的两个值作为函数中的参数

s = (9, 8)
print fun1(1, *s)           #这里要注意 需要把调用的写在后面。否则报错。
dic = {'x':1, 'y':7, 'z':4}
print fun1(**dic)           #使用字典传参。定义的字典key要与形参一样的。字典定义的时候key需要加引号
3
7
18
12



冗余参数:

处理多余实参
def fun(x,y,*args,**kwargs)

def fun(x, *args, **kwargs):        #星号后面的字母可以任意定义。这里是与python源码保持一致。
    print x
    print args
    print kwargs
t = (9,10)
fun(1)
print '############        test2         ############'
fun(123, 2)
print '############        test3         ############'
fun(1, 2, y=9)              #默认参数形式的才存到字典里面。
print '############        test4         ############'
fun(1, 2, *t, **{'c':11})
1
()
{}
############        test2         ############
123
(2,)
{}
############        test3         ############
1
(2,)
{'y': 9}
############        test4         ############
1
(2, 9, 10)
{'c': 11}


python函数递归调用:

def factorial(n):
    sum = 1
    for i in range(1, n+1):
        sum *= i
    return sum

print(factorial(5))     #阶乘
120


递归的注意事项:

必须有最后的默认结果

       if n == 0

递归参数必须向默认结果收敛的:

       factorial(n-1)




#@File :hanshu_digui.py

def factorial(n):
    sum = 1
    for i in range(1, n+1):
        sum *= i
    return sum
print(factorial(5))     #阶乘
print'##########       阶乘       ############'
def factorial1(n):
    if n == 0:
        return 1
    else:
        return n * factorial1(n-1)
print factorial1(4)
120
##########       阶乘       ############
24



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值