python基础语法

    本文地址:http://www.tongxinmao.com/Article/Detail/id/245

    #!/usr/bin/python3
    
    # 第一个注释
    print ("Hello, Python!") 
    
    '''
    第三注释
    第四注释
    '''
    python最具特色的就是使用缩进来表示代码块,不需要使用大括号({})。
    缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数
    
    paragraph = """这是一个段落,
    可以由多行组成"""
    python允许处理unicode字符串,加前缀u或U, 如 u"this is an unicode string"。
    通过在字符串前加r或R。 如 r"this is a line with \n" 则\n会显示,并不是换行。
    
    Python可以在同一行中使用多条语句,语句之间使用分号(;)分割
    
    print 默认输出是换行的  print( x, end=" " ) # 不换行输出
    
    
    Python 中只有模块(module),类(class)以及函数(def、lambda)才会引入新的作用域,其它的代码块(如 if/elif/else/、try/except、for/while等)是不会引入新的作用域的,也就是说这这些语句内定义的变量,外部也可以访问
    
    当内部作用域想修改外部作用域的变量时,就要用到global和nonlocal(外层非全局作用域)关键字了。类似PHP
    
    import somemodule
    
    for i in sys.argv:
        print (i)
        
    while b < 10:
      print(b)
      
      
    list=[1,2,3,4]
    it = iter(list)    # 创建迭代器对象
    for x in it:
        print (x, end=" ")
         
    if condition_1:
        statement_block_1
    elif condition_2:
        statement_block_2
    else:
        statement_block_3
    
    
    def printinfo( name, age = 35 ): #默认参数
    def functionname([formal_args,] *var_args_tuple ): #不定长参数    
        
    匿名函数
    
    sum = lambda arg1, arg2: arg1 + arg2;
    print ("相加后的值为 : ", sum( 10, 20 ))
    
    def example(anything):
        '''形参为任意类型的对象,
           这个示例函数会将其原样返回。
        '''
        return anything
        
     不带参数值的return语句返回None
     
     
    sys.argv 是命令行参数列表。sys.argv[0] 表示脚本名
    len(sys.argv) 是命令行参数个数
    print ('参数列表:', str(sys.argv))
    
    
    
    def main(argv):
       inputfile = ''
       outputfile = ''
       try:
          opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
       except getopt.GetoptError:
          print ('test.py -i <inputfile> -o <outputfile>')
          sys.exit(2)
       for opt, arg in opts:
          if opt == '-h':
             print ('test.py -i <inputfile> -o <outputfile>')
             sys.exit()
          elif opt in ("-i", "--ifile"):
             inputfile = arg
          elif opt in ("-o", "--ofile"):
             outputfile = arg
       print ('输入的文件为:', inputfile)
       print ('输出的文件为:', outputfile)
    
    if __name__ == "__main__":
       main(sys.argv[1:])
       
     列表 vec = [2, 4, 6] 
     元组和序列basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
     集合a = set('abracadabra')
     
    
    理解字典的最佳方式是把它看做无序的键=>值对集合 tel = {'jack': 4098, 'sape': 4139}
    
       
    字符串:
    print ("var2[1:5]: ", var2[1:5])
    * 重复输出字符串
    []通过索引获取字符串中字符
     a[1:4]  截取字符串中的一部分
    in/not in 如果字符串中是否包含给定的字符 
     
    print ("我叫 %s 今年 %d 岁!" % ('小明', 10))
     str.format(),
     
     encode(encoding='UTF-8',errors='strict')
     
     Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。
     
     	
    find(str, beg=0 end=len(string))
    index(str, beg=0, end=len(string)) 	 rindex( str, beg=0, end=len(string))
    isalnum() 	isalpha() isdigit() islower() isnumeric()
    	
    split(str="", num=string.count(str)) 以 str 为分隔符截取字符串
    join(seq) 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符
    len(string)
    lower() 
    replace(old, new [, max])
    rstrip() 	strip([chars]) 删除字符串字符串末尾的空格
    startswith(str, beg=0,end=len(string))
    
    # Python 字典类型转换为 JSON 对象
    data = {
        'no' : 1,
        'name' : 'Runoob',
        'url' : 'http://www.runoob.com'
    }
    
    json_str = json.dumps(data)
    
    # 将 JSON 对象转换为 Python 字典
    data2 = json.loads(json_str)
    print ("data2['name']: ", data2['name'])
    
    
    
    # 写入 JSON 数据
    with open('data.json', 'w') as f:
        json.dump(data, f)
    
    # 读取数据
    with open('data.json', 'r') as f:
        data = json.load(f)
        
        
    import time;  # 引入time模块
    
    ticks = time.time()
    print ("当前时间戳为:", ticks) # 1459996086.7115328
    localtime = time.localtime(time.time())
    print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    
    
    
    
    os.chdir(path)
    	
    os.chmod(path, mode)
    	
    os.chroot(path)
    	
    os.listdir(path)
    	
    os.unlink(path)
    os.utime(path, times)
    
    
    
    
    os.system('cat /etc/passwdqc.conf')
    output = os.popen('cat /proc/cpuinfo')
    同时返回结果和运行状态,commands模块:
    
    input("\n\n按下 enter 键后退出。")
    
    Python 调用 C/C++ (base)。源码中加入封装函数编译成SO,PYTHON中IMPORT调用
    调用SO文件:from ctypes import *
    test = cdll.LoadLibrary(" ./certificate.so ")
    
    
    
    import random
    print(random.randint(0,9))
    
    sys.stderr.write('Warning, log file not found starting a new one\n')
    
    # 写文件
    with open("test.txt", "wt") as out_file:
        out_file.write("该文本会写入到文件中\n看到我了吧!")
     
    # Read a file
    with open("test.txt", "rt") as in_file:
        text = in_file.read()
     
    print(text)
    
    
    
    >>> help(max)  打印输出一个函数的文档字符串
    
    
    面向对象
    
    class MyClass(Base1, Base2, Base3):
        """一个简单的类实例"""
        i = 12345
         __secretCount = 0  # 私有变量
        #两个下划线开头,声明该属性为私有
        def f(self):
            return 'hello world'
     def __foo(self):          # 私有方法
            print('这是私有方法')
            
     def __init__(self):
        self.data = []
     def __del__ : 
     
        
    # 实例化类
    x = MyClass()
     
    self代表类的实例,而非类
    类方法必须包含参数 self, 且为第一个参数
    
    
    # 访问类的属性和方法
    print("MyClass 类的属性 i 为:", x.i)
    print("MyClass 类的方法 f 输出为:", x.f())
    
    
    
    import _thread
    import time
    
    # 为线程定义一个函数
    def print_time( threadName, delay):
       count = 0
       while count < 5:
          time.sleep(delay)
          count += 1
          print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
    
    # 创建两个线程
    try:
       _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
       _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
    except:
       print ("Error: 无法启动线程")
    
    while 1:
       pass
       
       
    class myThread (threading.Thread):
        def __init__(self, threadID, name, counter):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.name = name
            self.counter = counter
        def run(self):
            print ("开始线程:" + self.name)
            print_time(self.name, self.counter, 5)
            print ("退出线程:" + self.name)
    
    def print_time(threadName, delay, counter):
        while counter:
            if exitFlag:
                threadName.exit()
            time.sleep(delay)
            print ("%s: %s" % (threadName, time.ctime(time.time())))
            counter -= 1
    
    # 创建新线程
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)
    
    # 开启新线程
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print ("退出主线程")


    上一篇:FT2232H 双USB串口 描述符
    下一篇:树莓派 AndroidThings镜像下载