《转》python学习(3)

时间:2022-07-13 18:21:14

转自http://www.cnblogs.com/BeginMan/archive/2013/06/03/3114974.html

1、print语句调用str()函数显示,交互式解释器调用repr()函数来显示对象

>>> s='python'
>>> s
'python' #repr(),显示结果呈现单引号
>>> print s #str().没有单引号
python
>>> repr(s)
"'python'"
>>> str(s)
'python'

str()主要显示给人看,repr()显示个机器和畜生看。
print语句会默认给每一行加上换行符,只要在print语句的最后添加一个逗号(,)就可让结果排列在一行。

2、raw_input():

读取标准输入,并把结果给指定变量,如:name=raw_input('your name:')

3、一些语句

(1)、if、if .. else ..、if ..elif..else..

elif即‘else if ’,注意在Django中不存在 elif 模板标签

(2)、while循环
循环控制,最好依赖 ..True..Flase,如下:(《DjangoBook第八章例子》)

#coding=utf-8
'''
Created on 2013-4-17
@author: BeginMan
'''
db={}
def newuser():
prompt='login desired:'
while True:
name=raw_input(prompt)
if db.has_key(name):
prompt='name taken,try another'
continue
else:
break
pwd=raw_input('password:')
db[name]=pwd def olduser():
name=raw_input('name:')
pwd=raw_input('password:')
if pwd==db.get(name):
print 'welecom back ',name
else:
print 'login error' def showmenu():
prompt="""
-----------------
(N) new user login
(E) existing user login
(Q) quit
-----------------
Enter choice:
"""
done=False
while not done:
chosen=False
while not chosen:
try:
choice=raw_input(prompt).strip()[0].lower()
except(EOFError,KeyboardInterrupt):
choice='q'
print '\n you picked:[%s]' %choice
if choice not in 'neq':
print 'invalid option,try again'
else:
chosen=True
if choice=='q':done=True
if choice=='n':newuser()
if choice=='e':olduser() if __name__=='__main__':
showmenu()

(3)、for循环

不同C#、java、C、等编程语言,如js中:for(var i=0;i<s.length;i++){....};python中它更像C#中的foreach():

>>> dic={'name':'BeginMan','job':'pythoner','age':22}
>>> for obj in dic.items():
print obj ('age', 22)
('job', 'pythoner')
('name', 'BeginMan')

(4)、range()/len()使用

这两个方法用的很多,如:

>>> for obj in range(5):
print obj, 0 1 2 3 4
>>> for obj in [0,1,2,3,4]:
print obj, 0 1 2 3 4
 

首先了解下range()。它很像JavaScript里面随机函数,在python里也这样称呼。

>>> help(range)
Help on built-in function range in module __builtin__: range(...)
range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.
When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.
 

当然,我们也可以这样:

 
>>> for obj in range(5,10):
>>> print obj, 5 6 7 8 9

range()经常和len()函数一起使用用于字符串索引,如:

>>> name='BeginMan'
>>> for obj in range(len(name)):
print '(%d)' %obj,name[obj] (0) B
(1) e
(2) g
(3) i
(4) n
(5) M
(6) a
(7) n

enumerate()的强势围攻,
上面的例子循环有些约束,Python2.3推出了enumerate()函数来解决这一问题,enumerate:枚举 的意思:

>>> for i,j in enumerate(name):
>>> print i,j B
e
g
i
n
M
a
n

 4、列表解析

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgsAAABhCAIAAADXzXWMAAAI40lEQVR4nO2dy5arKhBA/eszzSf09Hytd5A+3kSgeAgUVey9MjA2IhK7tjzU4+/fvycAAEDAgSEAACAKhgBo5wXj0f6Rt8akIY7XsfLnu6wHHz+fAOLXaKhhXawaQrsISSKGAB9gCA2oYV0wRGcwhFswhAbUsC4YojMYwi0YQgNqWBdLhjguREO8k2Szerj+Kst9vWyIP8fvZzxP6iHJlJIP5XbIxwdCsveqMLd7/ErVz8TfvZa+50ntGZX6P7r4rOFsYuhO3BB/Er9B7fq+XGdGtg3RcA4d38jrbwm+8hEMMT1A8L8UIv126T+9V4W5FV3hDv3de2Te6zx559Omk9RWYQ1zVs8k2Yb4cxzRuF+7PrnjRORNReozYYhUWD8TVxypzG+7KFwf/iluiOsSMryWFFaeFdeefeshQrQkt3Lm+Dl+fo6fa+G9/Pmn6MrPhTD97a/RfD6PuvlrxhBC/UR/4ihCfWZPnjJVjD5PmsM3hliTTC/ToMZE5l8xt9UVhZMKif0DyGU4P/5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I8bAFyAITyiaAjcAOAIDOGRW4y+Re3ooHEqspeHe9wA4A4M4ZGbD7IL0a/CyjANbgDwCIbwyGRDAIBTMIRHMAQA9ABDeKRhHCLcSlgJAHuAITzSPEW1V1YA4AIM4ZHa+ay1t9EBwB4kDdH2ouKG9PLeC/f4PB9XLPXUDQAwS9wQJUOYqa3KE3eZgi9stW9wwxAA0INuhkhNkCncqmpfJVltHdkwBAD0YEVD1HYNpSbmbNrFdH4f/PMPAOxKH0M0RxW5DfFENs35AADAm57jEF0SYwgAgEWwbQghMYYAAHjIkNmuVbNUw/RV+5XnRNGRDgDQDHfMAQBAHAwBAABx/gNly7mA5abnjwAAAABJRU5ErkJggg==" alt="" />

5、文件操作

打开文件:handle=open(file_name,access_mode='r')
如果打开成功,一个文件对象的句柄将会被返回,就可以通过它的句柄进行一系列的操作。

>>> dic={'name':'BeginMan','job':'pythoner','age':22}
>>> for obj in dic.items():
print obj ('age', 22)
('job', 'pythoner')
('name', 'BeginMan')

附:遍历数组的两种方式

第一种,最常用的,通过for in遍历数组

>>> name='BeginMan'
>>> for obj in range(len(name)):
print '(%d)' %obj,name[obj] (0) B
(1) e
(2) g
(3) i
(4) n
(5) M
(6) a
(7) n

第二种,先获得数组的长度,然后根据索引号遍历数组,同时输出索引号

colours = ["red","green","blue"]  

for i in range(0, len(colours)):
print i, colour[i] # 0 red
# 1 green
# 2 blue