In [75]: def fun():
...: print "hello python!!"
...:
In [76]: fun()
hello python!!
例子1:
判断从键盘输入的是数字还是非数字:
def fun():
sth = raw_input("pls input a number :")
try:
if type(int(sth)) == type(1): ##判断是否为 int 类型
print "{} is a number.".format(sth)
except ValueError: ##如果执行有问题出现异常,就会执行这一句
print "{} is not a number.".format(sth)
fun() ##调用
涉及到的知识点:
以下为简单的try….except…else的语法:
try:
<语句> #运行别的代码
except <名字>:
<语句> #如果在try部份引发了'name'异常
except <名字>,<数据>:
<语句> #如果引发了'name'异常,获得附加的数据
else:
<语句> #如果没有异常发生
try的工作原理是,当开始一个try语句后,python就在当前程序的上下文中作标记,这样当异常出现时就可以回到这里,try子句先执行,接下来会发生什么依赖于执行时是否出现异常。
下面是简单的例子,它打开一个文件,在该文件中的内容写入内容,且并未发生异常:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print "Error: 没有找到文件或读取文件失败"
else:
print "内容写入文件成功"
fh.close()
以上程序输出结果:
$ python test.py
内容写入文件成功
$ cat testfile # 查看写入的内容
这是一个测试文件,用于测试异常!!
形式参数和实际参数
In [78]: def fun(x ,y): ## x,y 称为形式参数
...: print x + y
...:
In [79]: fun(3,5) ##传多个参数或传少都会报错
8
In [81]: fun('asd','12')
asd12
判断输入的实参大小:
In [82]: def aa(x,y):
...: if x > y:
...: print x
...: else:
...: print y
...:
In [83]: aa(3,5)
5
In [84]: aa(8,5)
8
列子2:
import sys
def isNum(n):
for i in n:
if i in '0123456789':
pass
else:
print "{} is not a number".format(n)
sys.exit()
else:
print "{} is a number.".format(n)
isNum(sys.argv[1])
扩充:
和shell一样的规则:
print sys.argv[0]: 表示脚本的本身
print sys.argv[1]: 表示脚本的第一个参数
print sys.argv[2]: 表示脚本的第二个参数
...
In [85]: import os
In [86]: os.listdir('/proc/') ## 遍历某个目录下的所有文件,并以列表的形式展现
Out[86]:
['fb',
'vmstat',
'cgroups',
'kpageflags',
'partitions',
'timer_list',
'execdomains',
'filesystems',
'sched_debug',
'timer_stats',
'vmallocinfo',
'pagetypeinfo',
'sysrq-trigger',
'self',
'1',
'2',
'3',
'5',
'7',
'8',
'9',
'10',
'12',
打印出来linux系统中的pid:
#!/usr/bin/python
import sys
import os
def aa(n):
for i in n:
if i in '0123456789':
pass
else:
break
else:
print "{}".format(n)
for i in os.listdir('/proc'):
aa(i)
扩充:
sys.exit() : 意思是:退出整个脚本。
In [88]: def aa(x, y): ##定义两个形参
...: print x + y
...:
In [89]: aa(3,6) ##接收两个实参
9
In [90]: def aa(x, y=12): ##定义两个形参,且赋值其中一个形参
...: print x + y
...:
In [91]: aa(3,6) ##自定义以后,会按照自定义的参数来
9
In [92]: aa(3) ##如果只定义一个参数,就会使用其中赋值的形参
15
In [93]: def aa(x=13, y): ##形参的赋值只能放在最后一位。
...: print x + y
...:
File "<ipython-input-93-75321c574f96>", line 1
def aa(x=13, y):
SyntaxError: non-default argument follows default argument
In [94]: def bb(x=7,y=8):
...: print x + y
...:
In [95]: bb()
15
In [96]: bb(22,33) ##自定义的参数优先
55