函数的定义:
完成一组特定功能的一组语句。这组语句可以作为一个单位使用,并取一个名字 为函数名,
。
可以在不同的地方通过这个函数名多次使用执行改函数,叫做函数调用。
建立一个函数
In [1]: def fun():
...: print "hello world"
...:
In [2]: fun()
hello world
创建一个判断数字的函数:输入数字判断是数字,输入字符串判断不是函数
[root@jie py]# cat a.py
#!/usr/bin/python
def fun():
sth=raw_input("Please input something: ")
try:
if type(int(sth)) ==type(1):
print ("%s is a number" %sth)
except ValueError:
print ("%s is not number" %sth)
fun()
运行该函数可以判断输入字符是否是数字
函数参数:
形式参数和实际参数
在定义函数的时候,函数名后面括号中的变量名称叫做形式参数,简称形参,
在调用函数的时候,函数名后面括号中的变量名称叫做实际参数,简称实参。
给函数传参数:
x,y为形参
In [13]: def fun(x,y):
....: print x+y
....:
调用该函数
2,3为实参
In [14]: fun(2,3)
5
判断字符是否是数字
#!/usr/bin/env python
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])
测试 ./test.py 111
111 is a number
(for 循环有个可选项else,循环正确结束会执行else模块)
sys.argv[1]可以从终端带进来参数相当于shell中的$1
打印linux系统下所有pid:
[root@jie py]# cat c.py
#!/usr/bin/env python
import os
def isNum(s):
for i in s:
if i.isdigit():
print (i),
isNum(os.listdir("/proc/"))
运行该脚本
[root@jie py]# python c.py
1 2 3 5 7 8 9 10 12 13 14 15 16 17 18 19 25 26 27 28 36 37 38 39 40 59 91 227 233 234 235 236 239 251 256 257 325 337 347 419 442 465 466 467 473 480 481 487 490 883 885 886 908 970 1129 1251 1488 2250 2809 2811 2832 2838 2915 2937 4001 17769 18775 23639 31048 31929
函数的默认参数:
设置默认参数,不给y传值的话,就用默认参数
In [17]: def fun(x,y=100):
....: print x+y
....:
In [18]: fun(2,5)
7
In [19]: fun(2)
102