函数
函数是完成特定功能的一个语句组,这组语句可以作为一个单位使用,并且给它去一个名字
可以通过函数名在程序的不同地方多次执行
- 函数的定义和调用
- def函数名([参数列表]): //定义
- 函数名([参数列表]) //调用
In [1]: def fun():
...: print(1)
...:
In [2]: fun()
1
- 编写一个简单的函数,判断输入的是不是数字
#!/bin/python
def fun():
sth=input("please input something:")
try:
if type(int(sth)) == type(1):
print("%s is a number"%(sth))
except:
print("%s is not number"%(sth))
fun()
[root@localhost studypy]# python3 fun.py
please input something:1
1 is a number
[root@localhost studypy]# python3 fun.py
please input something:kk
kk is not number
函数的参数
形式参数和实际参数
-
在定义函数时,函数名后面括号中的变量名称叫做“形式参数”,或者称为“形参”
-
在调用函数时,函数名后面括号中的变量名称叫做“实际参数”,或者称为“实参”
-
函数的例子
相加的函数
In [1]: def fun(x,y):
...: print(x+y)
...:
In [2]: fun(1,2)
3
判断两个数大小的函数
In [3]: def fun(x,y):
...: if x>y:
...: print(x)
...: else:
...: print(y)
...:
In [4]: fun(1,2)
2
In [5]: fun(2,4)
4
- 判断传入的是不是数字
#!/bin/python
import sys
def isNum(s):
for i in s:
if i in '0123456789':
pass
else:
print("%s is not number"%(s))
sys.exit()
else:
print("%s is a numbuer"%(s))
isNum(sys.argv[1])
[root@localhost studypy]# python3 fun1.py 3
3 is a numbuer
[root@localhost studypy]# python3 fun1.py abc
abc is not number
默认参数
- 默认参数,如果没有没有参数赋值会使用默认值
In [1]: def fun(x,y=100):
...: print(x+y)
...:
In [2]: fun(2,3)
5
In [3]: fun(2)
102
- 打印服务器进程的pid程序
import sys
import os
def isNum(s):
for i in s:
if i in '0123456789':
pass
# print("%s is not number"%(s))
else:
break
else:
print("%s is a numbuer"%(s))
for j in os.listdir('/proc'):
isNum(j)
类似这样的输出
2133 is a numbuer
2525 is a numbuer
2529 is a numbuer
3134 is a numbuer
3137 is a numbuer
3148 is a numbuer
3153 is a numbuer
3154 is a numbuer