现在的位置: 首页 > 综合 > 正文

Python入门笔记(4):基础快餐版

2012年09月21日 ⁄ 综合 ⁄ 共 2583字 ⁄ 字号 评论关闭

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

	
0 B
1 e
2 g
3 i
4 n
5 M
6 a
7 n
>>> 

 4、列表解析

5、文件操作

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

filename=raw_input('Enter file name:')
#filename:对应文件完整路径,这里创建一个py.txt与.py文件同级
fobj=open(filename,'r') #获得文件对象的句柄 fobj
for eachLine in fobj:
    print eachLine
fobj.close()    #一次读入文件的所有行然后关闭文件,再迭代每一行的输出

 

抱歉!评论已关闭.