zoukankan      html  css  js  c++  java
  • 《转》python

    转自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 '
     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 
  • 相关阅读:
    cf1100 F. Ivan and Burgers
    cf 1033 D. Divisors
    LeetCode 17. 电话号码的字母组合
    LeetCode 491. 递增的子序列
    LeetCode 459.重复的子字符串
    LeetCode 504. 七进制数
    LeetCode 3.无重复字符的最长子串
    LeetCode 16.06. 最小差
    LeetCode 77. 组合
    LeetCode 611. 有效三角形个数
  • 原文地址:https://www.cnblogs.com/cmybky/p/11772186.html
Copyright © 2011-2022 走看看