abs(-1) --绝对值
1
>>> print 'with %s say %s' % (a,(b+' ')*3)
with king say hi hi hi
vim test.py
x=raw_input('Enter x: ')
if x>0:
print '"x" must be 0!'
输入x的值来返回结果其中if语句是不需要() 的 raw_input()是一个内建函数,她是 最容易从用户那里获取到值得方式
x=raw_input('Enter x: ')
if x>0:
print 'double x: %d' % (int(x)*2) 两倍值 也可以elif
while 循环
s=0
while s<3:
print 'while %d' % (s)
s+=1
for循环
a=['a','b','c','d']
for s in a:
print 'Have this options: %s' % (s)
a='funny'
for s in a:
print s
循环索引 循环元素
a='funny'
for s,c in enumerate(a): for s in range(len(a)):
print c ,'(%d)' % s print a[s],'(%d)' % s
列表解析 从for里传值到列表中
squared=[x**2 for x in range(4)]
for i in squared:
print i
文件打开读写 open(a,b) a=filename b= 'r'只读'w'写‘+’读写'b'二进制访问 -在print使用,抑制文本中生成的换行不然会有空白行
filename=raw_input('Enter you file name: ')
handle=open(filename,'r')
for i in handle:
print i,
handle.close()
try except
try 管理代码 except出现错误后的执行代码
def ff(a):
return (a+a)
print ff(1)
python里面的类的定义与调用: 其中object不能大写 不然就无定义 __init__是特殊方法有开始和结束有 两个下划无论是否调用都回执行,默认是什么也不
做 self是this标识符 是类自身的引用
#!/usr/local/bin/python
class TestClass(object):
version=0.1
def __init__(self,nm='Sunny'):
self.name=nm
print 'create a instance for ', nm
def showname(self):
print 'your name: ', self.name
print 'My name is',self.__class__.__name__
def showver(self):
print self.version
def addME2ME(self,x):
return x+x
fool=TestClass()
test=fool.showname()
test2=fool.showver()
test3=fool.addME2ME(2)
print test3
----------------------------------
[root@puppet pyy]# python file.py
create a instance for Sunny
your name: Sunny
My name is TestClass
0.1
4
dir显示属性 不加参数显示全部 标签名字
>>> dir(1)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
>>> dir('a')
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'a', 'aa', 'ad', 'ap', 'b', 'foo', 'py', 'rr', 'squared', 'sys', 'th', 'user', 'x']
type返回对象类型
>>> type (a)
练习:
自身输出是存在单引号 print是 字符输出
>>> a="aa"
>>> a
'aa'
>>> print a
aa
>>> a='aa'
>>> a
'aa'
>>> print a
aa
用while或者for 做循环 从0-10 要使用range内建函数
a=0
while a<11:
print a
a+=1
b=[0,1,2,3,4,5,6,7,8,9,10]
for i in range(len(b)):
print b[i]
输入数值 判断正负零
a=raw_input('Enter a number:')
if int(a)==0:
print "zero"
elif int(a)<0:
print "fushu"
else :
print "zhenshu"
满足5就返回 否则就一直让客户输入
b=True
while b:
a=raw_input('Enter 1-100 number: ')
if int(a)==5:
b=False
else:
b=True
1为和 2 为平均 3 退出
print "Please Enter option"
print "1 will output sum"
print "2 will output avr"
print "3 exit "
b=raw_input('Enter a option:')
a=[1,1,1,1,1]
c=0
d=True
while d:
if int(b)==1:
for i in range(len(a)):
c=a[i]+c
print c
d=False
elif int(b)==2:
for i in range(len(a)):
c=a[i]+c
v=float(c/5)
print v
d=False
elif int(b)==3:
d=False
3 章
#!/usr/local/bin/python
"this is module"
import sys
import os
debug = True
class Fooclass(object):
"Foo class"
pass
def test():
"function"
foo = Fooclass()
if debug:
print 'ran test'
if __name__ == '__main__':
test()
没弄懂什么 叫做一个模块的而不是运行 * 指你只想运行一个代码文件里面的一个模块 可是它的主程序部分无论你是导入它的模块还是运行它的代码文件,它一定会运行的,所以为了解决这个问题就有了__name__
模块被导入时 __name__的值为名字
模块被运行时__name__的值为“__main__”
写代码要分块写 可以多次利用 是和别人合作来的 不是通篇一个独立的文件
所以在主程序里写测试代码 这样在直接运行的时候才运行 导入不运行
import os
类 #!/usr/local/bin/python
'makeTextFile.py -- create test file '
import os
ls=os.linesep
#get filename
fname = raw_input('Enter you file name:')
while True:
if os.path.exists(fname): 检测代码的函数
print "ERROR:'%s' already exists" % fname
break
else:
#get file conenett lines
all=[]
print "\nEnter lines ('.' by itself to quit .)\n"
##loop until user terminates input
while True:
entry = raw_input('>')
if entry == '.':
break
else:
all.append(entry)
#write line to file with proper line-ending
fobj = open(fname,'w')
fobj.writelines(['%s%s' % (x,ls)for x in all])
fobj.close()
print 'DONE!'
似于os.linesep要解释器做两次查询 查询一次模块 查询一次变量
所以设置本地变量能够 提高查询速度 以上是 新建一个文件 然后直接输入字符
append 用法: 行终止 类似于\n \r
writelines 用法: 传递的 可以是字符列表
以下是打开文件每行输出
#!/usr/local/bin/python
'readTextFile.py -- read and display text file'
#get filename
fname = raw_input('Enter filename:')
#attempt to open file for reding
try:
bj = open(fname, 'r')
except IOError,e:
print "***file open error:",e
else:
#dispaly contents to the screen
for eachLine in bj :
print eachLine,
bj.close()
其实还不是很懂except的用法
try 检测错误代码except报错之后处理方式else无错误执行方案 后面那个print的都好是为了解决每行的行结束符
os.path.exists()和异常处理,一般是用前者 前者返回两个值是or不是
os.linesep 当前平台使用的行终止符
3 练习
为什么python不需要声明变量 不用定义函数返回值类型
例如c 实现开辟一个空间然后把数据拿去到空间内
而python则是以数据为中心 先把数据存贮到内存中然后再去引用
避免使用双下划线
特殊方法
一行可以书写多个语句 , 一行也可以分为多个语句来写 ''' / ( 等
x=1 y=1 z=1
字符串对象strip()方法
合并文件选择创建还是显示
添加新功能 允许用户编辑一个存在的文件 GUI 工具包或者基于屏幕编辑模块 curses模块 允许用户保存他的修改 或者取消他的修 改 保证文件安全性要关闭
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/30629069/viewspace-2129466/
,如需转载,请注明出处,否则将追究法律责任。