• The first glance at Python


    这是当年初学Python时写下的笔记,本来是放在SolidMCP@Baidu的。但技术Blog搬家到了cnblog,每次在久不用之后需要参考Python的某些语法时,总得到Baidu空间去晃一圈,很是麻烦。

    最近准备学习JavaScript,干脆把The first glance at PythonThe first glance at Scala也搬过来,一次看个够。

    >> Python Basic

    Python_Basic.py
    # ''' is docstring which is used for documenting.
    
    moduleName = 'The first glance at Python: Python_Basic'

    print 'multiple',\
            'lines'
    # ------------------------------------------------------------- # How to use if-elif-else # ------------------------------------------------------------- def TryIF(a, b): ''' ----Function : How to use if-elif-else----''' if a > b : print a, 'is bigger' elif a == b: print a, 'equals', b else: print b, ' is bigger' #print TryIF.__doc__ #TryIF(3, 'a') #TryIF(3, 3) #TryIF(5, 3) # ------------------------------------------------------------- # How to use while # Please notice that we can add a else case for while.. # ------------------------------------------------------------- def TryWhile(): ''' ---Function : How to use while----''' number = 100 running = True while running: guessValue = int(raw_input('Enter a integer:')) if guessValue == number: running = False elif guessValue == 1234: print 'Quit' break elif guessValue == 555: print '555 is input, let\'s continue' continue else: print 'continue' else: print 'Right! Jump out of while scope' #TryWhile()
    # ------------------------------------------------------------- # How to use for # for in Python is more like foreach # Also, we need to notice that we can add a else case for it.
    # -------------------------------------------------------------
    def TryFor(): ''' ----Function : How to use for----''' kickNum = 36 step = 2 number = 100 for i in range(0, step * 10): number = i * step print '\tcurrent number is', number, '\n' if number == kickNum: print 'Quit if number = ', kickNum break for i in range(0, 10): print 'for loop:', i else: print 'Out of range:', i #TryFor() # ------------------------------------------------------------- # How to use global variable # ------------------------------------------------------------- def TryGlobalVariable(changedValue = 6789): ''' --- Function : How to use Global Value ---''' global gValue print 'Current Value = ', gValue gValue = changedValue print 'gValue is changed to', gValue return gValue #gValue = 32 #print 'Global Value Test \n', TryGlobalVariable() == 6789 # ------------------------------------------------------------- # Show Document help for above functions # ------------------------------------------------------------- #help(TryIF) #help(TryWhile) #help(TryFor) #help(TryGlobalVariable) # ------------------------------------------------------------- # Show all methods in a python lib: math # -------------------------------------------------------------
    import math #help(math)

    sys module and Import our module

    # -------------------------------------------------------------
    # How to use SYS module and my own module
    # -------------------------------------------------------------
    import sys
    #help(sys)
    print 'The command line arguments are :'
    for i in sys.argv:
        print i
    print '\n The System Path is : ' , sys.path
    print 'File System Encoding = ', sys.getfilesystemencoding()
    print 'Windows OS version = ', sys.getwindowsversion()
    print 'Major Version = ', sys.version
    
    #using Python_Basic.py
    import Python_Basic
    print 'Imported Module Name :', Python_Basic.moduleName
    print '\nFunctions, Classes, Variables in sys module: \n', dir(sys)
    print '\nFunctions, Classes, Variables in Python_Basic module: \n', dir(Python_Basic)

    >> Python Data Structures

    # -------------------------------------------------------------
    # Data Structure in Python
    # -------------------------------------------------------------
    
    # Before all, we need to know that even int is a class in python.
    #help(int)
    
    # list class
    print '\n\nBegin to study list class'
    #help(list)
    teamMember = ['Bike', 'Bush', 'Xiao']
    print 'Index of \'Bush\' is:', teamMember.count('Bush') #index of list starts from 0
    teamMember.append(8888)
    print 'New object ', teamMember[3],'is added. Now, memeber count is', len(teamMember)
    del teamMember[2]
    print 'The 3th Object is:', teamMember[2]
    print 'Pre-Sorted Members:'
    for i in range(0, 3):
        print teamMember[i]
    teamMember.sort()
    print 'Sorted Members:'
    for i in range(0, 3):
        print teamMember[i]
    print 'using sliceing to list some members', teamMember[0:3]
    
    # tuple class
    print '\n\nBegin to study tuple'
    #help(tuple)
    subTuple = ('Mike', 'Monkey', 'Carl')
    parentTuple = ('Tuple1', 'Tuple2', subTuple)
    print 'Both methods should return Carl, sure?'
    print subTuple[2]
    print parentTuple[2][2]
    print parentTuple[2]
    print 'using sliceing to list some members', parentTuple[0:3] #we need to use 3 here, why?
    
    # String class
    print '\n\nBegin to study string'
    #help(str)
    myString = 'Piaoger is a good man..'
    print 'To Upper: ', myString[0:10].upper()
    
    # dictionary(dict) class
    print '\n\nBegin to study dictionary'
    #help(dict)
    directory = { 'Piaoger' : '139',
                  'Mike'    : '123',
                  'Bush'    : 'dsfsfd'
                }
    
    print 'list all members in the directory\n'
    for name, address in directory.items():
        print 'Name: %s\tValue: %s' % (name, address)
       
    directory['Piaoger'] = '12345'
    print 'Value of Piaoger is changed to ',directory['Piaoger']
    
    if 'Sophia' not in directory:
        directory['Sophia'] = '888'
        print 'Failing to find Sophia in the directory'
    if directory.has_key('Sophia'):
        print 'Sophia is in the directory now..'
        print 'Value of Sophia is ',directory['Sophia']
    
    
    # reference V.s. copy for sequence classes: tuple, list, string...
    # This Example tells us not to use reference for copy values in list..
    origin=['Mike', 'Monkey', 'Carl']
    originRef = origin
    originCopy= origin[:]
    del origin[2]
    print 'After change:'
    print '\'originRef == origin\' = ', originRef == origin, '\t\'originCopy == origin\' = ',originCopy== origin

    >> Python in OO paradigm
    Python_OO.py

    # My first class with multiple inheritance: Markup
    class Markup:
        '''This class is used to process markups.'''
        def __init__(self, fileName):
            '''Constructor'''
            self.fileName = fileName
        def __del__(self):
            '''Destructor'''
            print 'Byebye, Markup'
    
        def GetType(self):
            return 'Unknown'
           
        def Load(self):
            '''Method to load Markups'''
            print '%s file %s is loading' % (self.GetType() , self.fileName)
    
    
        def Save(self, bSaveCopyAs = False):
            '''Save Markups'''
            if bSaveCopyAs == True:
                print 'Dialog will be presented..'
            else:
                print 'Document is saved'
        def Action(self, strActionName, strActionContent):
            '''Process all action items.'''
            print 'Action Name = %s Content = %s' % (strActionName, strActionContent)
    
    class Language:
        def GetLanguage(self):
            print 'Language ID is Chinese'
           
    class PDFMarkup(Markup, Language):
        def GetType(self):
            '''Overloaded GetType for PDF Markup'''
            return 'PDF Markup'
           
    help(Markup)
    
    print 'Load a general markup file..'
    markup = Markup("c:\\temp\\my.txt")
    markup.Load()
    markup.Action('My Action', 'To many action items....')
    markup.Save()
    del markup #it's better to do that by our own.
    
    help(PDFMarkup)
    print '\nLoad a PDF markup file..'
    pdfMarkup = PDFMarkup("c:\\temp\\myfile.pdf")
    pdfMarkup.GetLanguage()
    pdfMarkup.Load()
    pdfMarkup.Action('Look into PDF file', '[It\'s so complicated]')
    pdfMarkup.Save(True)
    del pdfMarkup

    >> Other

    Python_Other.py
     

    #help(file)
    print 'Begin to study File IO'
    strContent = 'd'
    myFile = file('C:\\temp\\users\\NAME1', 'r')
    strContent = myFile.read()
    print strContent
    myFile.close()
    myFile = file('C:\\temp\\users\\NAME1', 'a')
    myFile.write('sssssssssssssssssssssssssss')
    myFile.close()
    
    
    # os Module
    print 'Begin to study os module'
    import os
    help(os)
    print 'os.name = ', os.name
    print 'os.getcwd() = ', os.getcwd()
    print 'path = ', os.getenv('path')
    os.putenv('MyEnv', 'No')
    print 'MyEnv =',os.getenv('MyEnv')
    paths = os.listdir('c:\\windows\\Fonts') #list all font files
    print 'dir count = ',len(paths)
    #for i in range(0, len(paths)):
    #    print '%s'% paths[i]
       
    filePath = os.path.split('C:\\temp\\users\\NAME1')
    print 'File Name = ', filePath[1]
    
    #shell scripting
    #
    import os
    #os.system('notepad C:\\temp\\users\\NAME1') #using os.system
    
    # we need to download win32all from http://sourceforge.net/projects/pywin32/
    import win32api
    #help(win32api)
    #using ShellExecute(hwnd, op , file , params , dir , bShow )
    #win32api.ShellExecute(0, 'open', 'notepad.exe', 'C:\\temp\\users\\NAME1','',1)
    #win32api.ShellExecute(0, 'open', 'http://www.google.com', '','',1)
    
    
    # Registry Operation
    # Environmnt Variables
    #
    #HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
    #
    import win32api
    import win32con
    key = win32api.RegOpenKey( win32con.HKEY_LOCAL_MACHINE,"SYSTEM\CurrentControlSet\Control\Session Manager\Environment",0,win32con.KEY_ALL_ACCESS)
    print 'path = \n',str(win32api.RegQueryValueEx(key, "Path")[0])
    win32api.RegSetValueEx(key, "\nPythonStudy", 0, win32con.REG_SZ, "GoodLanguage")
    print 'Key = PythonStudy, value = ', str(win32api.RegQueryValueEx(key, "PythonStudy")[0])
    win32api.RegCloseKey(key)

    >> More Materials

    Python简明教程

    http://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python

  • 相关阅读:
    Rsync命令参数详解
    mysql 主从同步如何 把从数据的版本升级到指定的版本
    MySQL同步故障:" Slave_SQL_Running:No" 两种解决办法 (转)
    Linux VPS/服务器 网站及数据库自动本地备份并FTP上传备份脚本
    在kloxo中把不带www的域名做301到带www的域名
    mysql sorce 导入数据乱码问题解决
    linux后台运行和关闭SSH运行,查看后台任务
    centos下MySQL主从同步配置
    ecshop 无法上传产品图片 服务环境少了GD库
    EOJ2902 Contest
  • 原文地址:https://www.cnblogs.com/piaoger/p/2485606.html
Copyright © 2020-2023  润新知