zoukankan      html  css  js  c++  java
  • 《python tutorial》python 学习第一天

    摘要自《python tutorial》-中文版《python 指南》pyTutorial2.7-LX(刘鑫翻译)

    一 简介

    可以实现文本文件操作(类似shell),具有高级数据结构(编写GUI程序或者简单游戏),可扩展性强(可与c/c++等配合使用 )。解释型的高级语言。

    源文件 通过编码使用ASCII以外的字符集。???# -*- coding: encoding -*-

    如果你想要在当前目录中执行附加的启动文件,可以在全局启动文件中加入类似 以下的代码:

    if os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py') 。如果你想要在某个脚本中使用启动文
    件,必须要在脚本中写入这样的语句
    import os
    filename = os.environ.get('PYTHONSTARTUP')
    if filename and os.path.isfile(filename):
    execfile(filename)



    执行python文件的方法:

    安装python解释器

    1 python script.py

    2#!/usr/bin/env python 在脚本中添加解释器说明


    特别说明:

    python中使用缩进来表示对齐。使用table键即可。

    二 数据类型&表达式

    1 表达式

    类似shell或者haskell直接计算


    2字符串

    (1)\n\ 实现换行

    字符串文本有几种方法分行。

    (2)\ 续行

    可以使用反斜杠为行结尾的连续字符串,它表示下 一行在逻辑上是本行的后
    续内容
    hello = "This is a rather long string containing\n\
    several lines of text just as you would do in C.\n\
    Note that whitespace at the beginning of the line is\
    significant."

    (3)r不转义

    如果我们生成一个“原始”字符串, \n 序列不会被转义,而且行尾的反斜 杠,源码中的换行符,都成为
    字符串中的一部分数据,因此下例
    hello = r"This is a rather long string containing\n\
    several lines of text much as you would do in C."
    print hello
    would print:
    会打印:
    This is a rather long string containing\n\
    several lines of text much as you would do in C.

    (4)字符串连接

    ‘>>> word = 'Help' + 'A'
    >>> word
    'HelpA'
    >>> '<' + word*5 + '>'
    '<HelpAHelpAHelpAHelpAHelpA>'

    (5)截取(检索)。

    类似于 C ,字符串的第一个字符索引为 0 。没 有独立的字符类型,字符
    就是长度为 1 的字符串。类似 Icon ,可以用 切片标注 法截取字符串:由两个索引分割的复本。
    >>> word[4]
    'A'
    >>> word[0:2]
    'He'
    >>> word[2:4]
    'lp'

    >>> word[:2] + word[2:]
    'HelpA'
    >>> word[:3] + word[3:]
    'HelpA'

    >>> word[-2:]
    'pA'
    >>> word[:-2]
    'Hel'

    # The last two characters
    # Everything except the last two characters

    +---+---+---+---+---+
    | H | e | l | p | A |
    +---+---+---+---+---+
    0
    1
    2
    3
    4
    5
    -5 -4 -3 -2 -1

    >>> len(s)
    34

    (6)UNICODE对象

    >>> u'Hello World !'
    u'Hello World !'

    >>> u'Hello\u0020World !'   #\u0020表示空格
    u'Hello World !'

    特别的,和普通字符串一样, Unicode 字符串也有原始模式。可以在引号前加 “ur”,Python 会采用
    Raw-Unicode-Escape 编码(原始 Unicode 转义——译 者)。如果有前缀为 `u' 的数值,它也只会显示为
    \uXXXX 。
    >>> ur'Hello\u0020World !'
    u'Hello World !'
    >>> ur'Hello\\u0020World !'
    u'Hello\\\\u0020World !'           

    ?????????????????????????????????怎么多个\

    3  列表(类似haskell)

    a[:]是副本

    >>> a[:2] + ['bacon', 2*2]
    ['spam', 'eggs', 'bacon', 4]
    >>> 3*a[:3] + ['Boo!']
    ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boo!']

    >>> a[:]  #全部
    ['spam', 'eggs', 100, 1234]

    不像 不可变的 字符串,列表允许修改元素
    >>> a
    ['spam', 'eggs', 100, 1234]
    >>> a[2] = a[2] + 23
    >>> a
    ['spam', 'eggs', 123, 1234]


    range() 函数产生数值序列

    >>> range(10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >> range(5, 10)
    [5, 6, 7, 8, 9]
    >>> range(0, 10, 3)
    [0, 3, 6, 9]
    >>> range(-10, -100, -30)
    [-10, -40, -70]


    需要迭代链表索引的话,如下所示结合使 用range() 和 len()

    >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
    >>> for i in range(len(a)):
    ...
    print i, a[i]
    ...
    0 Mary
    1 had
    2 a
    3 little
    4 lamb



    三  流程控制

    1 if

    >>> x = int(raw_input("Please enter an integer: "))
    Please enter an integer: 42
    >>> if x < 0:
    ...
    x = 0
    ...
    print 'Negative changed to zero'
    ... elif x == 0:
    ...
    print 'Zero'
    ... elif x == 1:
    ...
    print 'Single'
    ... else:
    ...
    print 'More'
    ...
    More


    2 for

    >>> # Measure some strings:
    ... a = ['cat', 'window', 'defenestrate']
    >>> for x in a:
    ...
    print x, len(x)
    ...
    cat 3
    window 6
    defenestrate 12

    在迭代过程中修改迭代序列不安全(只有在使用链表这样的可变序列时才会有这 样的情况)。如果你想要
    修改你迭代的序列(例如,复制选择项),你可以迭代 它的复本。使用切割标识就可以很方便的做到这一

    >>> for x in a[:]: # make a slice copy of the entire list
    ...
    if len(x) > 6: a.insert(0, x)
    ...
    >>> a
    ['defenestrate', 'cat', 'window', 'defenestrate']

    3 break and continue不变

    4  else

    循环可以有一个 else 子句;它在循环迭代完整个列表(对于 for )或执行条件 为 false (对于 while
    )时执行,但循环被 break 中止的情况下不会执行。 以下搜索素数的示例程序演示了这个子句
    >>> for n in range(2, 10):
    ...
    for x in range(2, n):
    ...
    if n % x == 0:
    ...
    print n, 'equals', x, '*', n/x
    ...
    break
    ...
    else:
    ...
    # loop fell through without finding a factor
    ...
    print n, 'is a prime number'
    ...
    2 is a prime number
    3 is a prime number
    4 equals 2 * 2
    5 is a prime number
    6 equals 2 * 3
    7 is a prime number
    8 equals 2 * 4
    9 equals 3 * 3

    5 pass

    pass 语句什么也不做。
    >>> while True:
    ...         pass # Busy-wait for keyboard interrupt (Ctrl+C)

    这通常用于创建最小结构的类
    >>> class MyEmptyClass:
    ...              pass
    ...



    三  函数

    1 基本定义

    >>> def fib(n):
    # write Fibonacci series up to n
    ...
    """Print a Fibonacci series up to n."""
    ...
    a, b = 0, 1
    ...
    while a < n:
    ...
    print a,
    ...
    a, b = b, a+b
    ...
    >>> # Now call the function we just defined:
    ... fib(2000)
    0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597


    关键字 def 引入了一个函数 定义 。函数体语句从下一行开始,必须是缩进的。

    函数体的第一行可以是一个字符串值,这个字符串是该函数的文档字符串 ,或称 docstring 。有些工具使用文 档字符
    串在线的生成及打印文档,或者允许用户在代码中交互式的浏览;编写代 码进加入文档字符串是个好的风
    格,应该养成习惯。

    函数引用的实际参数在函数调用时引入局部符号表,因此,实参总是 传值调用 (这里的值总是一个对象
    引用 --自我感觉是传引用,
    而不是该对象的值)。 2 一个函数被另一个函 数调用时,一个新的局部符号表在调用过程中被创
    建。

    2 参数默认值

    def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
    while True:
    ok = raw_input(prompt)
    if ok in ('y', 'ye', 'yes'):
    return True
    if ok in ('n', 'no', 'nop', 'nope'):
    return False
    retries = retries - 1
    if retries < 0:
    raise IOError('refusenik user')
    print complaint


    ?????????????????????????????????????下面的两个例子似乎有问题

    第一个函数默认参数传的是值?第二个函数传的是“地址”

    i = 5
    def f(arg=i):
    print arg
    i = 6
    f()
    will print 5.

    def f(a, L=[]):
    L.append(a)
    return L
    print f(1)
    print f(2)
    print f(3)

    This will print :
    这样会打印出
    [1]
    [1, 2]
    [1, 2, 3]


    3 关键字参数--*NAME--多个参数,**NAME-关键字参数

    def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print "-- This parrot wouldn't", action,
    print "if you put", voltage, "volts through it."
    print "-- Lovely plumage, the", type
    print "-- It's", state, "!"
    could be called in any of the following ways:
    可以用以下的任一方法调用
    parrot(1000)
    parrot(action = 'VOOOOOM', voltage = 1000000)
    parrot('a thousand', state = 'pushing up the daisies')
    parrot('a million', 'bereft of life', 'jump')
    but the following calls would all be invalid:
    不过以下几种调用是无效的
    parrot()
    parrot(voltage=5.0, 'dead')
    parrot(110, voltage=220)
    parrot(actor='John Cleese')

    实际参数不能一次赋多个值——形式参数不能在同一次调用中同时使用位置和关键字绑定值。

    *NAME **NAME

    引入一个形如 **name 的参数时,它接收一个字典(参见 typesmapping ) ,该字典包含了所有未出现
    在形式参数列表中的关键字参数。这里可能还会组合使用一个形如 *name (下一小节詳細介绍) 的形 式
    参数,它接收一个元组(下一节中会详细介绍),包含了所有没有出现在形式 参数列表中的参数值。(
    *name 必须在 **name 之前出现) 例如,我们这样定 义一个函数

    ef cheeseshop(kind, *arguments, **keywords):
    print "-- Do you have any", kind, "?"
    print "-- I'm sorry, we're all out of", kind
    for arg in arguments: print arg
    print "-" * 40
    keys = keywords.keys()
    keys.sort()
    for kw in keys: print kw, ":", keywords[kw]
    It could be called like this:
    cheeseshop("Limburger", "It's very runny, sir.",
    "It's really very, VERY runny, sir.",
    shopkeeper='Michael Palin',
    client="John Cleese",
    sketch="Cheese Shop Sketch")
    and of course it would print:

    -- Do you have any Limburger ?
    -- I'm sorry, we're all out of Limburger
    It's very runny, sir.
    It's really very, VERY runny, sir.
    ----------------------------------------
    client : John Cleese
    shopkeeper : Michael Palin
    sketch : Cheese Shop Sketch


    4 可变参数列表

    最后,一个最不常用的选择是可以让函数调用可变个数的参数。这些参数被包装 进一个元组(参见 Tuples
    and Sequences 元组和序列 )。在这些可变个数的参数之前,可以有零到多个普通的参数
    def write_multiple_items(file, separator, *args):
    file.write(separator.join(args))

    5  参数列表的分拆-使用***

     当你要传递的参数已经是一个列表,但要调用的函数却接受 分开一个个的参数值.
    这时候你要把已有的列表拆开来. 例如内建函数 range() 需要要独立的 start, stop 参数. 你可以在调
    用函数时加一个 * 操作符来自动 把参数列表拆开
    >>> range(3, 6)
    [3, 4, 5]
    >>> args = [3, 6]
    >>> range(*args)
    [3, 4, 5]
    # normal call with separate arguments
    # call with arguments unpacked from a list


    以同样的方式,可以使用 ** 操作符分拆关键字参数为字典
    >>> def parrot(voltage, state='a stiff', action='voom'):
    ...
    print "-- This parrot wouldn't", action,
    ...
    print "if you put", voltage, "volts through it.",
    ...
    print "E's", state, "!"
    ...
    >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
    >>> parrot(**d)
    -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin'

    6  Lambda 形式--可以有匿名函数

    出于实际需要,有几种通常在函数式编程语言例如 Lisp 中出现的功能加入到了 Python 。通过 lambda
    关键字,可以创建短小的匿名函数。

    Lambda 形式可以用于任何需要的 函数对象。出于语法限制,它们只能有一个单独的表达式。语义上讲,它
    们只是 普通函数定义中的一个语法技巧。类似于嵌套函数定义,lambda 形式可以从外 部作用域引用变量

    def make_incrementor(n):
    return lambda x: x + n
    f = make_incrementor(42)
    f(0)

    42

    f(1)



    6  文档字符串

    第一行应该是关于对象用途的简介。

    如果文档字符串有多行,第二行应该空出来,与接下来的详细描述明确分隔。接 下来的文档应该有一或多
    段描述对象的调用约定、边界效应等。
    >>> def my_function():
    ...
    """Do nothing, but document it.
    ...
    ...
    No, really, it doesn't do anything.
    ...
    """
    ...
    pass
    ...












  • 相关阅读:
    poj 1417 True Liars(并查集+背包dp)
    CodeForces 760 C. Pavel and barbecue(dfs+思维)
    poj 2912 Rochambeau(枚举+带权并查集)
    lightoj 1245 Harmonic Number (II)(简单数论)
    thinkphp __PUBLIC__的定义 __ROOT__等常量的定义
    HTML5 画布参考
    HTML5 DTD
    HTML5 音频视频
    HTML5 事件
    HTML5 标准属性 NEW:HTML 5 中新的标准属性。 注释:HTML 4.01 不再支持 accesskey 属性:
  • 原文地址:https://www.cnblogs.com/catkins/p/5270674.html
Copyright © 2011-2022 走看看