函数定义
-
函数:完成特定功能的一个语句组
-
通过函数名在程序不同地方多次执行,称为函数的调用
-
函数分为:预定义函数和自定义函数
-
为何使用函数?
- 降低编程难度
- 代码重用
- 使用def 关键字来定义函数
def 函数名([参数列表])
- 变量:全小写
- 函数名:从第二个单词开始首字母大写
- 类名:每个单词首字母大写
In [1]: def fun ():
...: print "hello"
...:
In [2]: fun()
hello
#!/usr/bin/python
# -*- coding:utf-8 -*-
def fun():
sth = raw_input("Please input something: ")
try:
if type(int(sth)) == type(1):
print "%s is number" %sth
except:
print "%s is not number" %sth
fun() #调用
函数的参数
- 形参,定义函数时
- 实参,调用函数时
In [1]: def cmp(x, y):
...: if x >= y:
...: print x
...: else:
...: print y
...:
In [2]: cmp()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-2000d34a547a> in <module>()
----> 1 cmp()
TypeError: cmp() takes exactly 2 arguments (0 given)
In [3]: cmp(2, 4)
4
In [4]: cmp(4)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-07287826b1cb> in <module>()
----> 1 cmp(4)
TypeError: cmp() takes exactly 2 arguments (1 given)
#!/usr/bin/python
# -*- coding:utf-8 -*-
import sys
# print sys.argv # 输出一个包含脚本名和所有参数的列表
# print sys.argv[1] # 脚本的第一个参数
## 判断函数的第一个参数是否为纯数字
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])
[root@KARL ~]# python y8.py 123
123 is a number
[root@KARL ~]# python y8.py asd123
asd123 is not a number
#!/usr/bin/python
# -*- coding:utf-8 -*-
## 打印/proc目录下的所有pid
import sys
import os
# print sys.argv # 输出一个包含脚本名和所有参数的列表
# print sys.argv[1] # 脚本的第一个参数
def isNum(s):
for i in s:
if i in '0123456789':
pass
else:
# print "%s is not a number" %s
break
else:
print "%s is a number" %s
isNum(sys.argv[1])
for i in os.listdir('/proc'):
isNum(i)
函数的默认参数
In [8]: def sum(x , y=100)
File "<ipython-input-8-1144897e8d1a>", line 1
def sum(x , y=100)
^
SyntaxError: invalid syntax
In [9]: def sum(x , y=100):
...: print x + y
...:
In [10]: sum(2, 5)
7
In [11]: sum(30)
130
网友评论