@wenshizhang
2016-08-10T09:36:58.000000Z
字数 1639
阅读 406
suse实习 python
print,用来输出一串字符,可以采用下面两种方式
#输出姓名和年龄print 'My name is ', name ', my age is ', ageprint 'My name is %s, my age is %d' %(name,age)
第一种是采用的连接输出的方式,第二种是占位符(和C语言类似)。%符号是用来格式化字符串的,占位符会被后面的数据替换,顺序要对应好。常见的占位符有:
| 格式 | 类型 |
|---|---|
| %d | 整数 |
| %s | 字符串 |
| %f | 浮点数 |
| %x | 十六进制 |
* 文件
程序总会有和文件交互的需求,python和文件相关的常用操作有读写、打开和关闭。打开文件的模式常见的有三种:a、r和w(append, read和write)。其他的方法可以通过help(file)查看。
下面给出一个读写文件的例子,先写文件后读文件:
test = 'this is a test message'f = file("test.txt",'w')f.write(test)f.close()f = file("test.txt") #缺省mode是readinfo = f.readline()print infof.close()
import cPickle as pinfo = { name : shiwen age : 24 sex : female}#数据写入存储f = file("store.txt",'w')p.dump(info,f)f.close()#从存储中取数据f = file("store.txt",'w)store_info = p.load(f)print store_info
import systry:s = raw_input('Enter something...')except EOFError:print 'catch user press ctrl+d ,program will exit'sys.exit()except:print 'Another error'
try可以捕捉到的异常不仅仅是系统定义的异常,也可以是自己定义的异常。如果是自己定义的异常,需要自己判断此异常是不是产生了,然后自己引发一个此异常方便try语句捕获。例如:
import sysclass shortexcept(Exception) #每一个自定义异常类都需要继承exception基本类 def __init__(self,length,atleast): Exception.__init__(self) self.length = length self.atleast = atleasttry: s = raw_input('Enter something ...')if len(s)<3: raise shortexcept(len(s),3) #引发一个异常except EOFError:print 'catch user press ctrl+d, program will exit'except shortexcept,xprint 'ShortInputException: The input was of length %d, \was expecting at least %d' % (x.length, x.atleast)else:print 'No exception was raised.'
except也可以嵌套else语句。
没明白具体是做什么的。。。