复习贴-函数

来源:互联网 发布:淘宝上的面膜是正品吗 编辑:程序博客网 时间:2024/06/03 05:54

1.函数

函数就是完成特定功能的一个语句组,这组语句可以作为一个单位使用,并且给他去一个名字。

可以通过函数名在程序不同的地方多次执行。

怎么去定义函数

函数如果有2个单词组成的,建议第二个单词首字母大写。叫驼峰式命名法,还有可以下划线命名法。

#! /usr/bin/python


def fun(): //定义一个函数
sth = raw_input('Please input something: ') //将键入的值存在sth里

try: //捕获异常
if type(int(sth)) == type(1): // 当键入的值是个数字的时候,输出
print '%s is a number' %sth
except: //处理异常
print '%s is not number' %sth

fun()

函数的参数

#! /usr/bin/pythonimport sysdef 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' %sisNum(sys.argv[1])    



打印系统的PID

import os os.listdir() 查看目录里的所有文件,返回的是个列表。#! /usr/bin/pythonimport os ,sysdef isNum(s):    for i in s:        if i in '0123456789':            print '%s is a number'%s        else:            #print '%s is not a number'%s            breakfor i in os.listdir('/proc'):    isNum(i)


函数的变量


x = 100def fun():    global x    x += 1    print xfun()print x

函数的变量分为全局变量局部变量,在函数内部定义的变量是局部变量,如想要内部变量在函数外部被使用,要使用 global 声明。

多类型传值跟冗余参数

--def fun(x ,y):
-- return x + y
--
--print fun(2,3)
5

t = (4,7)
---fun(*t) #多类型传值,如果是元组直接加一个*
--- 11




最少要有一个参数

多余的参数都存在元组里。默认参数会存在字典里。比如a=3.


递归:

先使用for循环递归


使用递归计算阶层

原创粉丝点击