• 《简明Python教程》学习笔记


    简明python教程网址:http://sebug.net/paper/python

     1 help(sys)
     2 help(int)
     3 help(list)
     4 help(dict)
     5 help(str)
     6 help(file)
     7 sys模块
     8 print sys.__doc__
     9 help(sys.exit)
    10 help(sys.stdin)
    11 help(sys.stdout)
    12 help(sys.stderr)

    1.
    运算符通常由左向右结合,即具有相同优先级的运算符按照从左向右的顺序计算。例如,2 + 3 + 4被计算成(2 + 3) + 4。一些如赋值运算符那样的运算符是由右向左结合的,即a = b = c被处理为a = (b = c)。
    2.

    -25.5%2.25=1.5

    3.
    **是幂运算,布尔(not、or、and)逻辑(&,|,^,~)
    4.
    输出变量

    1 area = 5
    2 print 'Area is', area
    3 Area is 5[自动输出1个空格]

    5.

    1 if condintion1:
    2  func1
    3 elif condition2:
    4  func2
    5 else :
    6  func3

    注意:if语句在结尾处包含一个冒号——我们通过它告诉Python下面跟着一个语句块。
    6.

    1 guess = int(raw_input('Enter an integer:'))

    我们为内建的raw_input函数提供一个字符串,这个字符串被打印在屏幕上,然后等待用户的输入。一旦我们输入一些东西,然后按回车键之后,函数返回输入。对于raw_input函数来说是一个字符串。我们通过int把这个字符串转换为整数,并把它存储在变量guess中。
    7.
    True、False、None首字母不能小写。
    8.

    #while
    while condtion1:
        func1
    else:
        func2
    #for
    for i in range(1,5):
        func1
    else:
        func2

    注意:
    else从句可有可无
    注释用#
    9.
    range(begin,end,step)
    range 以step为步长,延伸到end,但它不包含end。
    10.
    【Python的for循环更加简单、明白、不易出错。】
    在C/C++中,如果你想要写for (int i = 0; i < 5; i++),那么用Python,你写成for i in range(0,5)。
    11.
    def sayHello():
     print 'Hello world!'
    sayHello()
    12.
    global x,y,z
    13.
    print 'zhanghe'*5
    14.
    如果你的某个函数有许多参数,而你只想指定其中的一部分,那么你可以通过命名来为这些参数赋值——这被称作 关键参数 ——我们使用名字(关键字)而不是位置(我们前面所一直使用的方法)来给函数指定实参。
    func(50,c=100)
    先按照关键参数、在按照顺序
    15.
    除非你提供你自己的return语句,每个函数都在结尾暗含有return None语句。
    16.
    pass语句在Python中表示一个空的语句块。
    17.
    文档字符串的惯例是一个多行字符串,它的首行以大写字母开始,句号结尾。第二行是空行,从第三行开始是详细的描述。 强烈建议 你在你的函数中使用文档字符串时遵循这个惯例。
    18.
    每个Python模块都有它的__name__,如果它是'__main__',这说明这个模块被用户单独运行,我们可以进行相应的恰当操作。
    19.
    使用内建的dir函数来列出模块定义的标识符。标识符有函数、类和变量。

    1 >>> import sys
    2 >>> dir(sys) # get list of attributes for sys module
    3 >>> dir() # get list of attributes for current module
    4 >>> a = 5 # create a new variable 'a'
    5 >>> dir()
    6 >>> del a # delete/remove a name
    7 >>> dir()

    20.
    列表
    21.
    我们在print语句的结尾使用了一个 逗号 来消除每个print语句自动打印的换行符。
    22.
    元组
    元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。
    #Filename:using_tuple.py
    zoo = ('wolf','elephant','penguin')
    print 'Number of animals in the zoo is',len(zoo)

    new_zoo = ('monkey','dolphin',zoo)
    print 'Number of animals in the new zoo is',len(new_zoo)
    print 'All animals in new zoo are',new_zoo
    print 'Animals brought from old zoo are',new_zoo[2]
    print 'Last animal brought from old zoo is',new_zoo[2][2]

    output:
    Number of animals in the zoo is 3
    Number of animals in the new zoo is 3
    All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))
    Animals brought from old zoo are ('wolf', 'elephant', 'penguin')
    Last animal brought from old zoo is penguin
    如果你想要的是一个包含项目2的元组的时候,你必须在第一个(唯一一个)项目后跟一个逗号,你应该指明singleton = (2 , )。
    23.
    元组最通常的用法是用在打印语句中
    age = 22
    name = 'Swaroop'

    print '%s is %d years old' % (name, age)
    print 'Why is %s playing with that python?' % name
    24.
    字典
    字典是dict类的实例/对象
    键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
    记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。
    #Filename:using_dict.py

    #'ab' is short for 'a'ddress 'b'ook

    ab={    'Swaroop'   :   'swaroopch@byteofpython.info',
            'Larry'     :   'larry@eall.org',
            'Matsumoto' :   'matz@ruby-lang.org',
            'Spammer'   :   'spammer@hotmail.com'   #The last para has no ','
        }

    print "Swaroop's address is %s" % ab['Swaroop']

    #Adding a key/value pair
    ab['Guido'] = 'guido@python.org'

    #Deleting a key/value pair
    del ab['Spammer']

    print '\nThere are %d contacts in the address-book\n'%len(ab)
    for name,address in ab.items():
        print 'Contact %s at %s'%(name,address)

    if 'Guido' in ab:#OR ab.has_key('Guido')
        print "\nGuido's address is %s"%ab['Guido']
    25.
    序列
    列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。
    序列的神奇之处在于你可以用相同的方法访问元组、列表和字符串。

    # Filename: seq.py

    shoplist = ['apple', 'mango', 'carrot', 'banana']

    # Indexing or 'Subscription' operation
    print 'Item 0 is', shoplist[0]
    print 'Item 1 is', shoplist[1]
    print 'Item 2 is', shoplist[2]
    print 'Item 3 is', shoplist[3]
    print 'Item -1 is', shoplist[-1]
    print 'Item -2 is', shoplist[-2]

    # Slicing on a list
    print 'Item 1 to 3 is', shoplist[1:3]
    print 'Item 2 to end is', shoplist[2:]
    print 'Item 1 to -1 is', shoplist[1:-1]【notice that】
    print 'Item start to end is', shoplist[:]【notice that】

    # Slicing on a string
    name = 'swaroop'
    print 'characters 1 to 3 is', name[1:3]
    print 'characters 2 to end is', name[2:]
    print 'characters 1 to -1 is', name[1:-1]
    print 'characters start to end is', name[:]

    output:
    Item 0 is apple
    Item 1 is mango
    Item 2 is carrot
    Item 3 is banana
    Item -1 is banana
    Item -2 is carrot
    Item 1 to 3 is ['mango', 'carrot']
    Item 2 to end is ['carrot', 'banana']
    Item 1 to -1 is ['mango', 'carrot']【notice that】
    Item start to end is ['apple', 'mango', 'carrot', 'banana']【notice that】
    characters 1 to 3 is wa
    characters 2 to end is aroop
    characters 1 to -1 is waroo
    characters start to end is swaroop
    26.
    参考
    当你创建一个对象并给它赋一个变量的时候,这个变量仅仅 参考 那个对象,而不是表示这个对象本身!也就是说,变量名指向你计算机中存储那个对象的内存。这被称作名称到对象的绑定。
    #Filename:reference.py
    print 'Simple Assignment'
    shoplist = ['apple','mango','carrot','banana']
    mylist = shoplist #mylist is just another name pointing to the same object

    del shoplist[0]

    print 'shoplist is',shoplist
    print 'mylist is',mylist
    # notice that both shoplist and mylist both print the same list without
    # the 'apple' confirming that they point to the same object

    print 'Copy by making a full slice'
    mylist = shoplist[:]# make a copy by doing a full slice
    del mylist[0]

    print 'shoplist is',shoplist
    print 'mylist is',mylist
    # notice that now the two lists are different
    27.
    字符串str类
    #!/usr/bin/python
    #Filename:str_methods.py

    name = 'Swaroop' #This is a string object

    if name.startswith('Swa'):
        print 'This string starts with "Swa"'

    if 'a' in name:
        print 'This string contains the string "a"'

    if name.find('war') != -1:
        print 'This string contains the string "war"'

    delimiter = '_*_'
    mylist = ['Brazil', 'Russia', 'India', 'China']
    print delimiter.join(mylist)
    28.
    类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称,但是在调用这个方法的时候你不为这个参数赋值,Python会提供这个值。这个特别的变量指对象本身,按照惯例它的名称是self。
    29
    __init__
    __init__方法在类的一个对象被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的 初始化 。注意,这个名称的开始和结尾都是双下划线。
    30.
    类与对象的变量
    有两种类型的 域 ——类的变量和对象的变量,它们根据是类还是对象 拥有 这个变量而区分。
    类的变量 由一个类的所有对象(实例)共享使用。只有一个类变量的拷贝,所以当某个对象对类的变量做了改动的时候,这个改动会反映到所有其他的实例上。
    对象的变量 由类的每个对象/实例拥有。因此每个对象有自己对这个域的一份拷贝,即它们不是共享的,在同一个类的不同实例中,虽然对象的变量有相同的名称,但是是互不相关的。

    #Filename:objvar.py

    class Person:
        '''Represents a person.'''
        population = 0

        def __init__(self, name):
            '''Initializes the person's data.'''
            self.name = name
            print '(Initializing %s)'%self.name

            #When this person is created, he/she
            #adds to the population
            Person.population += 1

        def __del__(self):
            '''I am dying'''
            print '%s says bye.'%self.name

            Person.population -= 1

            if Person.population == 0:
                print 'I am the last one'
            else :
                print 'There are still %d people left.'%Person.population

        def sayHi(self):
            '''Greeting by the person.

            Really,that's all it does.'''
            print 'hi,my name is %s.'%self.name

        def howMany(self):
            '''Prints the current population.'''
            if Person.population == 1:
                print 'I am the only person here.'
            else:
                print 'We have %d persons here.'%Person.population

    swaroop = Person('Swaroop')
    swaroop.sayHi()
    swaroop.howMany()

    kalam = Person('Abdul Kalam')
    kalam.sayHi()
    kalam.howMany()

    swaroop.sayHi()
    swaroop.howMany()

    kalam.__del__()
    swaroop.__del__()

    31.
    Python要求:
    Python中所有的类成员(包括数据成员)都是 公共的 ,所有的方法都是 有效的 。
    只有一个例外:如果你使用的数据成员名称以 双下划线前缀 比如__privatevar,Python的名称管理体系会有效地把它作为私有变量。
    公共惯例:
    如果某个变量只想在类或对象中使用,就应该以单下划线前缀。而其他的名称都将作为公共的,可以被其他类/对象使用。记住这只是一个惯例,并不是Python所要求的(与双下划线前缀不同)。

    32.
    一个子类型在任何需要父类型的场合可以被替换成父类型,即对象可以被视作是父类的实例,这种现象被称为多态现象。

    33.
    Python不会自动调用基本类的constructor,你得亲自专门调用它。
    我们调用了子类型的tell方法,而不是SchoolMember类的tell方法。可以这样来理解,Python总是首先查找对应类型的方法,在这个例子中就是如此。如果它不能在导出类中找到对应的方法,它才开始到基本类中逐个查找。

    34.
    Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
    还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。
    dump()储存
    load()取储存
    35.
    处理异常
    我们可以使用try..except语句来处理异常。我们把通常的语句放在try-块中,而把我们的错误处理语句放在except-块中。
    对于每个try从句,至少都有一个相关联的except从句。
    你还可以让try..catch块关联上一个else从句。当没有异常发生的时候,else从句将被执行。
    36.
    引发异常
    你可以使用raise语句 引发 异常。你还得指明错误/异常的名称和伴随异常 触发的 异常对象。你可以引发的错误或异常应该分别是一个Error或Exception类的直接或间接导出类。
    37.
    try..finally
    假如你在读一个文件的时候,希望在无论异常发生与否的情况下都关闭文件,该怎么做呢?这可以使用finally块来完成。注意,在一个try块下,你可以同时使用except从句和finally块。如果你要同时使用它们的话,需要把一个嵌入另外一个。
    import time
    time.sleep(2)
    38.
    在程序运行的时候,按Ctrl-c中断/取消程序。
    39.
    sys模块
    40.
    os模块
    这个模块包含普遍的操作系统功能。如果你希望你的程序能够与平台无关的话,这个模块是尤为重要的。即它允许一个程序在编写后不需要任何改动,也不会发生任何问题,就可以在Linux和Windows下运行。一个例子就是使用os.sep可以取代操作系统特定的路径分割符。
    >>> import os
    >>> str = 'Path'
    >>> print os.getenv(str)
    C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;E:\Java\jdk1.6.0_21\bin;C:\Python27;

    下面列出了一些在os模块中比较有用的部分。它们中的大多数都简单明了。
    os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'。
    os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径。
    os.getenv()和os.putenv()函数分别用来读取和设置环境变量。
    os.listdir()返回指定目录下的所有文件和目录名。
    os.remove()函数用来删除一个文件。
    os.system()函数用来运行shell命令。
    os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
    os.path.split()函数返回一个路径的目录名和文件名。
    os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.path.existe()函数用来检验给出的路径是否真地存在。

    41.
    特殊方法:
    __init__(self,...) 这个方法在新建对象恰好要被返回使用之前被调用。
    __del__(self) 恰好在对象要被删除之前调用。
    __str__(self) 在我们对对象使用print语句或是使用str()的时候调用。
    __lt__(self,other) 当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。
    __getitem__(self,key) 使用x[key]索引操作符的时候调用。
    __len__(self) 对序列对象使用内建的len()函数的时候调用。

    42.
    单语句块:[butuijianshiyong
    if True: print 'Yes'

    43.
    列表综合
    通过列表综合,可以从一个已有的列表导出一个新的列表。例如,你有一个数的列表,而你想要得到一个对应的列表,使其中所有大于2的数都是原来的2倍。对于这种应用,列表综合是最理想的方法。

    44.
    在函数中接收元组和列表
    当要使函数接收元组或字典形式的参数的时候,有一种特殊的方法,它分别使用*和**前缀。这种方法在函数需要获取可变数量的参数的时候特别有用。
    变量前有*前缀,所有多余的函数参数都会作为一个元组
    变量前有**前缀,所有多余的函数参数都会作为一个字典的键/值对。

    45.
    lambda形式
    lambda语句被用来创建新的函数对象,并且在运行时返回它们。
    lambda需要一个参数,后面仅跟【单个表达式】作为函数体,而表达式的值被这个新建的函数返回。

    46.
    exec语句
    exec语句用来执行储存在字符串或文件中的Python语句。
    exec 'print "Hello World"'

    eval语句
    eval语句用来计算存储在字符串中的有效Python表达式。
    eval('2*3')

    assert语句
    assert语句用来声明某个条件是真的。例如,如果你非常确信某个你使用的列表中至少有一个元素,而你想要检验这一点,并且在它非真的时候引发一个错误,那么assert语句是应用在这种情形下的理想语句。

    repr函数
    repr函数用来取得对象的规范字符串表示。反引号(也称转换符)可以完成相同的功能。
    repr函数和反引号用来获取对象的可打印的表示形式。你可以通过定义类的__repr__方法来控制你的对象在被repr函数调用的时候返回的内容。

    >>> i = []
    >>> i.append('item')
    >>> `i`
    "['item']"
    >>> repr(i)
    "['item']"

    字节跳动内推

    找我内推: 字节跳动各种岗位
    作者: ZH奶酪(张贺)
    邮箱: cheesezh@qq.com
    出处: http://www.cnblogs.com/CheeseZH/
    * 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    CSS hack:针对IE6,IE7,firefox显示不同效果
    让IE6支持png24透明/半透明的方法
    IE8的css hack
    jQuery Mobile笔记三
    jQuery Mobile笔记二
    js常见面试题
    CSS3-transform3D
    CSS3-transform-style
    CSS3-媒体类型
    CSS3-盒模型-resize属性
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/2752267.html
Copyright © 2020-2023  润新知