• 简明python教程笔记


    自然字符串

    如果你想要指示某些不需要如转义符那样的特别处理的字符串,那么你需要指定一个自然字符串。自然字符串通过给字符串加上前缀r或R来指定。

    r"Newlines are indicated by 
    "

    在文件头加上linux下运行python的主程序模块和文件名

    #!/usr/bin/python
    #Filename:test.py

    打印DocString(文档字符串)是个好习惯

    #!/usr/bin/python
    #Filename:test.py
    
    def printMax(x, y):
        '''Prints the maximum of two numbers.
    
        The two values must be integers.'''
        x = int(x) # convert to integers, if possible
        y = int(y)
        if x > y:
            print x, 'is maximum'
        else:
            print y, 'is maximum'
    
    printMax(3, 5)
    print printMax.__doc__

    Result

     主模块入口Sample

    #!/usr/bin/python
    # Filename: using_name.py
    if __name__ == '__main__':
        print 'This program is being run by itself'
    else:
        print 'I am being imported from another module'

    构建自己的模块

    mymodule

    #!/usr/bin/python
    # Filename: mymodule.py
    def sayhi():
    print 'Hi, this is mymodule speaking.'
    version = '0.1'
    # End of mymodule.py

    import的主module

    #!/usr/bin/python
    # Filename: mymodule_demo.py
    import mymodule
    mymodule.sayhi()
    print 'Version', mymodule.version

    数据结构

    列表,即Javascript中的数组,可以对它进行增删改查的操作

    #!/usr/bin/python
    # Filename: using_list.py
    
    # This is my shopping list
    shoplist = ['apple', 'mango', 'carrot', 'banana']
    
    print 'I have', len(shoplist),'items to purchase.' #length
    
    print 'These items are:', # Notice the comma at end of the line
    for item in shoplist: #for-in circle
        print item,
    
    print '
    I also have to buy rice.'
    shoplist.append('rice') #append element
    print 'My shopping list is now', shoplist
    
    print 'I will sort my list now'
    shoplist.sort() #sort elements
    print 'Sorted shopping list is', shoplist
    
    print 'The first item I will buy is', shoplist[0] #get element by index
    olditem = shoplist[0]
    del shoplist[0] #delete element
    print 'I bought the', olditem
    print 'My shopping list is now', shoplist

    Result

    元组,和列表类似,但是不能修改,即为不能修改的列表,用()包裹。

    元组可以直接输出,定义中可以直接包含其他元组

    类似于C++中的多维数组

    #!/usr/bin/python
    # 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]

    Result

    元组一般用于打印

    #!/usr/bin/python
    # Filename: print_tuple.py
    
    age = 22
    name = 'Swaroop'
    print '%s is %d years old' % (name, age)
    print 'Why is %s playing with that python?' % name

    字典,类似于Javascript里的Object,key/value键值对,Hash表

    #!/usr/bin/python
    #Filename:test.py
    
    #ab is short for 'a'ddress 'b'ook
    
    ab={
        'Swaroop' : 'swaroopch@byteofpython.info',
        'Larry' : 'larry@wall.org',
        'Matsumoto' : 'matz@ruby-lang.org',
        'Spammer' : 'spammer@hotmail.com'
        }
    
    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 '
    There are %d contacts in the address-book
    ' % 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 "
    Guido's address is %s" %ab['Guido']

    Result

    列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。

    #!/usr/bin/python
    # Filename: seq.py
    
    shoplist = ['apple', 'mango', 'carrot', 'banana']
    
    # Indexing or 'Subscription' operation
    print 'Item 0 is', shoplist[0] #Item 0 is apple
    print 'Item 1 is', shoplist[1] #Item 1 is mango
    print 'Item 2 is', shoplist[2] #Item 2 is carrot
    print 'Item 3 is', shoplist[3] #Item 3 is banana
    print 'Item -1 is', shoplist[-1] #Item -1 is banana
    print 'Item -2 is', shoplist[-2] #Item -2 is carrot
    
    # Slicing on a list
    print 'Item 1 to 3 is', shoplist[1:3] #Item 1 to 3 is ['mango', 'carrot']
    print 'Item 2 to end is', shoplist[2:] #Item 2 to end is ['carrot', 'banana']
    print 'Item 1 to -1 is', shoplist[1:-1] #Item 1 to -1 is ['mango', 'carrot']
    print 'Item start to end is', shoplist[:] #Item start to end is ['apple', 'mango', 'carrot', 'banana']
    
    # Slicing on a string
    name = 'swaroop'
    print 'characters 1 to 3 is', name[1:3] #characters 1 to 3 is wa
    print 'characters 2 to end is', name[2:] #characters 2 to end is aroop
    print 'characters 1 to -1 is', name[1:-1] #characters 1 to -1 is waroo
    print 'characters start to end is', name[:] #characters start to end is swaroop

    Result

    引用,类似于C++的指针,如果我们把一个列表赋值给一个新变量,实际是新变量指向列表的内存地址,如果我们把一个序列复制给一个新变量,这只是Copy操作。

    #!/usr/bin/python
    # 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] # remove first item
    print 'shoplist is', shoplist
    print 'mylist is', mylist
    # notice that now the two lists are different

    Result

    常用的字符串方法

    #!/usr/bin/python
    # Filename: str_methods.py
    
    name = 'Swaroop' # This is a string object
    if name.startswith('Swa'):
    print 'Yes, the string starts with "Swa"'
    
    if 'a' in name:
    print 'Yes, it contains the string "a"'
    
    if name.find('war') != -1:
    print 'Yes, it contains the string "war"'
    
    delimiter = '_*_'
    mylist = ['Brazil', 'Russia', 'India', 'China']
    print delimiter.join(mylist)

    编写一个备份文件的Python脚本

    设计思路

    1. 需要备份的文件和目录由一个列表指定。

    2. 备份应该保存在主备份目录中。

    3. 文件备份成一个zip文件。

    4. zip存档的名称是当前的日期和时间。

    5. 我们使用标准的zip命令,它通常默认地随Linux/Unix发行版提供。Windows用户可以使用Info-Zip程序。注意你可以使用任何地存档命令,只要它有命令行界面就可以了,那样的话我们可以从我们的脚本中传递参数给它。

    Code

    #!/usr/bin/python
    # Filename: backup_ver1.py
    
    import os
    import time
    
    # 1. The files and directories to be backed up are specified in a list.
    source = ['/home/swaroop/byte', '/home/swaroop/bin']
    # If you are using Windows, use source = [r'C:Documents', r'D:Work'] or something like that
    
    # 2. The backup must be stored in a main backup directory
    target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using
    
    # 3. The files are backed up into a zip file.
    # 4. The name of the zip archive is the current date and time
    target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
    
    # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive
    zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
    
    # Run the backup
    if os.system(zip_command) == 0:
        print 'Successful backup to', target
    else:
        print 'Backup FAILED'

    面向对象

    类与对象的方法

    举个简单的例子就能看懂,书上的缩进写的一团糟,看起来有点类,手打一遍,发现Python真的很优雅!

    #!/usr/bin/python
    #Filename:test.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 strill %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()

    Result

    继承

    #!/usr/bin/python
    #Filename:test.py
    
    class SchoolMember:
        '''Represents any school member.'''
        def __init__(self,name,age):
            self.name = name
            self.age = age
            print '(Initialized SchoolMember: %s)' %self.name
    
        def tell(self):
            '''Tell my details.'''
            print 'Name:"%s" Age:"%s"' %(self.name,self.age)
    
    
    
    class Teacher(SchoolMember):
        '''Represents a teacher.'''
        def __init__(self,name,age,salary):
            SchoolMember.__init__(self,name,age)
            self.salary = salary
            print '(Initialized Teacher: %s)' %self.name
    
        def tell(self):
            SchoolMember.tell(self)
            print 'Salary:"%d"' %self.salary
    
    
    
    
    class Student(SchoolMember):
        '''Represents a student.'''
        def __init__(self,name,age,marks):
            SchoolMember.__init__(self,name,age)
            self.marks = marks
            print '(Initialized Student: %s)' %self.name
    
        def tell(self):
            SchoolMember.tell(self)
            print 'Marks:"%d"' %self.marks
    
    
    
    t = Teacher('Mrs.Shrividya',40,30000)
    s = Student('Swaroop',22,75)
    
    print #prints a blank line
    
    members = [t,s]
    for member in members:
        member.tell() #works for both Teachers and Students
            

    Result

    输入输出

    文件

    你可以通过创建一个file类的对象来打开一个文件,分别使用file类的read、readline或write方法来恰当地读写文件。对文件的读写能力依赖于你在打开文件时指定的模式。最后当你完成对文件的操作的时候,你调用close方法来告诉Python我们完成了对文件的使用。

    #!/usr/bin/python
    #Filename:test.py
    
    poem = '''
    Programming is fun
    When the work is done
    if you wanna make your work also fun:
    use Python!
    '''
    
    f = file('poem.txt','w') #open for 'w'rting
    f.write(poem) #write text to file
    f.close() #close the file
    
    f = file('poem.txt')
    #if no mode is specified,'r'ead mode is assumed by default
    while True:
        line = f.readline()
        if len(line) == 0:#Zero length indicates EOF
            break
        print line,
        #Notice comma to avoid automatic newline added by Python
    
    f.close() #close the file

    储存与取储存 dump()&load()

    Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为 持久地 储存对象。

    还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。

    #!/usr/bin/python
    #Filename:test.py
    
    import cPickle as p
    #import pickle as p
    
    shoplistfile = 'shoplist.data'
    # the name of the file where we will store the object
    
    shoplist = ['apple', 'mango', 'carrot']
    
    # Write to the file
    f = file(shoplistfile, 'w')
    p.dump(shoplist, f) # dump the object to a file
    f.close()
    
    del shoplist # remove the shoplist
    
    # Read back from the storage
    f = file(shoplistfile)
    storedlist = p.load(f)
    print storedlist
            

    异常

    try...except的用法

    #!/usr/bin/python
    #Filename:test.py
    
    import sys
    
    try:
        s = raw_input('Enter something --> ')
    except EOFError:
        print '
    Why did you do an EOF on me?'
        sys.exit() # exit the program
    except:
        print '
    Some error/exception occurred.'
        # here, we are not exiting the program
    
    print 'Done'

    http://pythonguidecn.readthedocs.org/zh/latest/

    http://old.sebug.net/paper/books/LearnPythonTheHardWay/

  • 相关阅读:
    Python中使用pip安装库时提示:远程主机强迫关闭了一个现有的连接
    一个真正有能力的人
    一个程序员的自白(延迟满足)
    小规模团队如何“微服务”管理
    一个程序员的自白(无知之者)
    小型系统如何“微服务”开发
    TCP协议学习总结(下)
    TCP协议学习总结(中)
    TCP协议学习总结(上)
    一个程序员的自白(三十而立)
  • 原文地址:https://www.cnblogs.com/zcynine/p/5159152.html
Copyright © 2020-2023  润新知