首页 > 编程语言 > 详细

《转》python

时间:2019-10-31 17:54:44      阅读:102      评论:0      收藏:0      [点我收藏+]

转自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、列表解析

技术分享图片

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 

《转》python

原文:https://www.cnblogs.com/cmybky/p/11772186.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!