zoukankan      html  css  js  c++  java
  • python基础知识

    这篇文章适合有语音基础的人学习,这里我主要列出python语法中需要注意的地方,方便快速入门python语言

    1.中文编码:编码添加# -*- coding: UTF-8 -*-

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    print "你好,世界";

    2.行与缩进

     用缩进代替{}代码块,下面的例子是因为没有缩进相同行所有会报错

    if True:
        print "True"
    else:
      print "False"

    3.变量,字符串,list,元组,字典(字符串,list通过[]效果相同截取特定位置子集)

      定义的变量可通过del删除

      list可以更新,元组不能更新

    list:['runoob', 786, 2.23, 'john', 70.2];

    tuple = ( 'runoob', 786 , 2.23, 'john', 70.2 );

    tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    str = 'Hello World!'
     
    print str           # 输出完整字符串
    print str[0]        # 输出字符串中的第一个字符
    print str[2:5]      # 输出字符串中第三个至第五个之间的字符串
    print str[2:]       # 输出从第三个字符开始的字符串
    print str * 2       # 输出字符串两次
    print str + "TEST"  # 输出连接的字符串

     4.运算符

      **:幂 - 返回x的y次幂:a**b 为10的20次方, 输出结果 100000000000000000000

      //:取整除 - 返回商的整数部分(向下取整):9//2 输出结果 4 , 9.0//2.0 输出结果 4.0

    运算符描述实例
    & 按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 (a & b) 输出结果 12 ,二进制解释: 0000 1100
    | 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。 (a | b) 输出结果 61 ,二进制解释: 0011 1101
    ^ 按位异或运算符:当两对应的二进位相异时,结果为1 (a ^ b) 输出结果 49 ,二进制解释: 0011 0001
    ~ 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。~x类似于 -x-1 (~a ) 输出结果 -61 ,二进制解释: 1100 0011,在一个有符号二进制数的补码形式。
    << 左移动运算符:运算数的各二进位全部左移若干位,由 << 右边的数字指定了移动的位数,高位丢弃,低位补0。 a << 2 输出结果 240 ,二进制解释: 1111 0000
    >> 右移动运算符:把">>"左边的运算数的各二进位全部右移若干位,>> 右边的数字指定了移动的位数 a >> 2 输出结果 15 ,二进制解释: 0000 1111

    逻辑运算符,以下假设变量 a 为 10, b为 20:

    运算符逻辑表达式描述实例
    and x and y 布尔"与" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。 (a and b) 返回 20。
    or x or y 布尔"或" - 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。 (a or b) 返回 10。
    not not x 布尔"非" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 not(a and b) 返回 False

     

    in 如果在指定的序列中找到值返回 True,否则返回 False。 x 在 y 序列中 , 如果 x 在 y 序列中返回 True。
    not in 如果在指定的序列中没有找到值返回 True,否则返回 False。 x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。
    运算符描述实例
    is is 是判断两个标识符是不是引用自一个对象 x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False
    is not is not 是判断两个标识符是不是引用自不同对象 x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。

    pass是空语句,是为了保持程序结构的完整性

    5.函数

      1)定义函数

    def functionname( parameters ):
       "函数_文档字符串"
       function_suite
       return [expression]

      2)参数:关键字参数,默认参数,不定长参数

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    #可写函数说明
    def printinfo( name, age ):
       "打印任何传入的字符串"
       print "Name: ", name;
       print "Age ", age;
       return;
     
    #调用printinfo函数,关键字参数
    printinfo( age=50, name="miki" );
    ----------------------------------
    #!/usr/bin/python # -*- coding: UTF-8 -*-
    # 可写函数说明 def printinfo( arg1, *vartuple ):
        "打印任何传入的参数"
        print "输出: "
         print arg1
        for var in vartuple:
          print var return;

    # 调用printinfo 函数 printinfo( 10 );
    printinfo( 70, 60, 50 );

      3)匿名函数:lamda函数

      lambda [arg1 [,arg2,.....argn]]:expression

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    # 可写函数说明
    sum = lambda arg1, arg2: arg1 + arg2;
     
    # 调用sum函数
    print "相加后的值为 : ", sum( 10, 20 )
    print "相加后的值为 : ", sum( 20, 20 )

    6.模块

      模块让你能够有逻辑地组织你的 Python 代码段。把相关的代码分配到一个模块里能让你的代码更好用,更易懂。模块能定义函数,类和变量,模块里也能包含可执行的代码

      1)定义模块

    模块:support.py
    def print_func( par ): print
    "Hello : ", par return

      2)引入模块

    引入模块:import module1[, module2[,... moduleN]
    调用模块内函数
    # 导入模块
    import support
     
    # 现在可以调用模块里包含的函数了
    support.print_func("Runoob")
    from modname import name1[, name2[, ... nameN]]:from 语句让你从模块中导入一个指定的部分到当前命名空间中
    from modname import *:把一个模块的所有内容全都导入到当前的命名空间
    
    

    7.文件I/O

      raw_input([prompt])从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符):

    str = raw_input("请输入:")
    print "你输入的内容是: ", str

      input([prompt]) 函数和 raw_input([prompt]) 函数基本类似,但是 input 可以接收一个Python表达式作为输入,并将运算结果返回

    str = input("请输入:")
    print "你输入的内容是: ", str

      open函数:打开一个文件,创建一个file对象,之后相关的方法才能调用进行读写

        file object = open(file_name [, access_mode][, buffering])# 打开一个文件

    fo = open("foo.txt", "r+")
    str = fo.read(10)
    print "读取的字符串是 : ", str
    # 关闭打开的文件
    fo.close()
    # 打开一个文件
    fo = open("foo.txt", "r+"str = fo.read(10)print "读取的字符串是 : ", str
     
    # 查找当前位置
    position = fo.tell()
    print "当前文件位置 : ", position
     
    # 把指针再次重新定位到文件开头
    position = fo.seek(0, 0)
    str = fo.read(10)
    print "重新读取字符串 : ", str
    # 关闭打开的文件
    fo.close()

    import os
    # 重命名

    os.rename(current_file_name, new_file_name)
    #删除文件
    os.remove(file_name)
    #当前目录下创建新的目录
    os.mkdir("newdir")
    #改变当前目录
    os.chdir("newdir")
    #获得当前目录
    os.getcwd()
    #删除当前目录
    os.rmdir('dirname')

    8.异常 

    try:
    <语句>        #运行别的代码
    except <名字><语句>        #如果在try部份引发了'name'异常
    except <名字>,<数据>:
    <语句>        #如果引发了'name'异常,获得附加的数据
    else:
    <语句>        #如果没有异常发生

    try:
        fh = open("testfile", "w")
        fh.write("这是一个测试文件,用于测试异常!!")
    except IOError:
        print "Error: 没有找到文件或读取文件失败"
    else:
        print "内容写入文件成功"
        fh.close()

    8.内置函数

    http://www.runoob.com/python/python-built-in-functions.html

    9.面向对象

      self是类的实例

      类的继承

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    class Parent:        # 定义父类
       parentAttr = 100
       def __init__(self):
          print "调用父类构造函数"
     
       def parentMethod(self):
          print '调用父类方法'
     
       def setAttr(self, attr):
          Parent.parentAttr = attr
     
       def getAttr(self):
          print "父类属性 :", Parent.parentAttr
     
    class Child(Parent): # 定义子类
       def __init__(self):
          print "调用子类构造方法"
     
       def childMethod(self):
          print '调用子类方法'
     
    c = Child()          # 实例化子类
    c.childMethod()      # 调用子类的方法
    c.parentMethod()     # 调用父类方法
    c.setAttr(200)       # 再次调用父类的方法 - 设置属性值
    c.getAttr()          # 再次调用父类的方法 - 获取属性值
    View Code

      类方法重写

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    class Parent:        # 定义父类
       def myMethod(self):
          print '调用父类方法'
     
    class Child(Parent): # 定义子类
       def myMethod(self):
          print '调用子类方法'
     
    c = Child()          # 子类实例
    c.myMethod()         # 子类调用重写方法
    View Code

      注意:

      单下划线,双下划线,头尾双下划线说明:

    • __foo__: 定义的是特殊方法,一般是系统定义名字 ,类似 __init__() 之类的。

    • _foo: 以单下划线开头的表示的是 protected 类型的变量,即保护类型只能允许其本身与子类进行访问,不能用于 from module import *

    • __foo: 双下划线的表示的是私有类型(private)的变量, 只能是允许这个类本身进行访问了。

    10.CGI编程(Common Gateway Interface):通用网关服务,可以做BS服务端代码编写

      CGI程序可以是Python脚本,PERL脚本,SHELL脚本,C或者C++程序

      http://www.runoob.com/python/python-cgi.html:现在都被php,servlet等取代了

    11.操作数据库参考(http://www.runoob.com/python/python-mysql.html)

      1)安装mysqldb:http://sourceforge.net/projects/mysql-python 

      2)使用列子

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    import MySQLdb
    
    # 打开数据库连接
    db = MySQLdb.connect("localhost", "testuser", "test123", "TESTDB", charset='utf8' )
    
    # 使用cursor()方法获取操作游标 
    cursor = db.cursor()
    
    # 使用execute方法执行SQL语句
    cursor.execute("SELECT VERSION()")
    
    # 使用 fetchone() 方法获取一条数据
    data = cursor.fetchone()
    
    print "Database version : %s " % data
    
    # 关闭数据库连接
    db.close()
    View Code

    12.python网络编程

    例子

      1)服务端

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    # 文件名:server.py
    
    import socket               # 导入 socket 模块
    
    s = socket.socket()         # 创建 socket 对象
    host = socket.gethostname() # 获取本地主机名
    port = 12345                # 设置端口
    s.bind((host, port))        # 绑定端口
    
    s.listen(5)                 # 等待客户端连接
    while True:
        c, addr = s.accept()     # 建立客户端连接。
        print '连接地址:', addr
        c.send('欢迎访问菜鸟教程!')
        c.close()                # 关闭连接
    View Code

      2)客户端

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    # 文件名:client.py
    
    import socket               # 导入 socket 模块
    
    s = socket.socket()         # 创建 socket 对象
    host = socket.gethostname() # 获取本地主机名
    port = 12345                # 设置端口好
    
    s.connect((host, port))
    print s.recv(1024)
    s.close()  
    View Code

      3)操作步骤:先执行 server.py 文件,再执行 client.py 文件:

      4)网络编程中一些重要模块

    协议功能用处端口号Python 模块
    HTTP 网页访问 80 httplib, urllib, xmlrpclib
    NNTP 阅读和张贴新闻文章,俗称为"帖子" 119 nntplib
    FTP 文件传输 20 ftplib, urllib
    SMTP 发送邮件 25 smtplib
    POP3 接收邮件 110 poplib
    IMAP4 获取邮件 143 imaplib
    Telnet 命令行 23 telnetlib
    Gopher 信息查找 70 gopherlib, urllib

    13.SMTP邮件

      看看例子就好了

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    import smtplib
    from email.mime.text import MIMEText
    from email.header import Header
     
    sender = 'from@runoob.com'
    receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱
     
    # 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
    message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
    message['From'] = Header("菜鸟教程", 'utf-8')   # 发送者
    message['To'] =  Header("测试", 'utf-8')        # 接收者
     
    subject = 'Python SMTP 邮件测试'
    message['Subject'] = Header(subject, 'utf-8')
     
     
    try:
        smtpObj = smtplib.SMTP('localhost')
        smtpObj.sendmail(sender, receivers, message.as_string())
        print "邮件发送成功"
    except smtplib.SMTPException:
        print "Error: 无法发送邮件"
    View Code

    14.多线程

      1)线程Thread

    • run(): 用以表示线程活动的方法。
    • start():启动线程活动 
    • join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
    • isAlive(): 返回线程是否活动的。
    • getName(): 返回线程名。
    • setName(): 设置线程名。

      调用thread模块中的start_new_thread()函数来产生新线程

      例子:thread.start_new_thread ( function, args[, kwargs] )

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    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: unable to start thread"
     
    while 1:
       pass
    View Code

      2)线程模块Threading:

      Python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁。

    • threading.currentThread(): 返回当前的线程变量。
    • threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
    • threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    import threading
    import time
     
    exitFlag = 0
     
    class myThread (threading.Thread):   #继承父类threading.Thread
        def __init__(self, threadID, name, counter):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.name = name
            self.counter = counter
        def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 
            print "Starting " + self.name
            print_time(self.name, self.counter, 5)
            print "Exiting " + self.name
     
    def print_time(threadName, delay, counter):
        while counter:
            if exitFlag:
                (threading.Thread).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()
     
    print "Exiting Main Thread"
    View Code

      3)线程同步,锁

      线程同步:代码放在acquire和release方法之间就能达到线程同步

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    import threading
    import time
     
    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 "Starting " + self.name
           # 获得锁,成功获得锁定后返回True
           # 可选的timeout参数不填时将一直阻塞直到获得锁定
           # 否则超时后将返回False
            threadLock.acquire()
            print_time(self.name, self.counter, 3)
            # 释放锁
            threadLock.release()
     
    def print_time(threadName, delay, counter):
        while counter:
            time.sleep(delay)
            print "%s: %s" % (threadName, time.ctime(time.time()))
            counter -= 1
     
    threadLock = threading.Lock()
    threads = []
     
    # 创建新线程
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)
     
    # 开启新线程
    thread1.start()
    thread2.start()
     
    # 添加线程到线程列表
    threads.append(thread1)
    threads.append(thread2)
     
    # 等待所有线程完成
    for t in threads:
        t.join()
    print "Exiting Main Thread"
    View Code

      4)线程优先级队列:queue

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    import Queue
    import threading
    import time
     
    exitFlag = 0
     
    class myThread (threading.Thread):
        def __init__(self, threadID, name, q):
            threading.Thread.__init__(self)
            self.threadID = threadID
            self.name = name
            self.q = q
        def run(self):
            print "Starting " + self.name
            process_data(self.name, self.q)
            print "Exiting " + self.name
     
    def process_data(threadName, q):
        while not exitFlag:
            queueLock.acquire()
            if not workQueue.empty():
                data = q.get()
                queueLock.release()
                print "%s processing %s" % (threadName, data)
            else:
                queueLock.release()
            time.sleep(1)
     
    threadList = ["Thread-1", "Thread-2", "Thread-3"]
    nameList = ["One", "Two", "Three", "Four", "Five"]
    queueLock = threading.Lock()
    workQueue = Queue.Queue(10)
    threads = []
    threadID = 1
     
    # 创建新线程
    for tName in threadList:
        thread = myThread(threadID, tName, workQueue)
        thread.start()
        threads.append(thread)
        threadID += 1
     
    # 填充队列
    queueLock.acquire()
    for word in nameList:
        workQueue.put(word)
    queueLock.release()
     
    # 等待队列清空
    while not workQueue.empty():
        pass
     
    # 通知线程是时候退出
    exitFlag = 1
     
    # 等待所有线程完成
    for t in threads:
        t.join()
    print "Exiting Main Thread"
    View Code

    15.GUI编程

    http://www.runoob.com/python/python-gui-tkinter.html

    16.注意

      1)在 python 中,strings, tuples, 和 numbers 是不可更改的对象,而 list,dict 等则是可以修改的对象

      2)变量 a 是没有类型,她仅仅是一个对象的引用(一个指针)

      3)根据调用地方的不同,globals() 和 locals() 函数可被用来返回全局和局部命名空间里的名字
    reload函数:当一个模块被导入到一个脚本,模块顶层部分的代码只会被执行一次因此,如果你想重新执行模块里顶层部分的代码,可以用 reload() 函数。该函数会重新导入之前导入过的模块
      4)包:简单来说,包就是文件夹,但该文件夹下必须存在 __init__.py 文件, 该文件的内容可以为空。在同级目录中创建py文件调用其他py文件中函数可通过
    "from package_runoob.runoob1 import runoob1"这种方式来获得
  • 相关阅读:
    job owner的权限和sql agent start account权限在job调用和job执行的各个阶段起什么作用?
    【转帖】SharePoint 2010中的沙盒解决方案(Sandboxed Solution)
    [ZT]使用IIS作为宿主的WCF服务出现HTTP Error 404.3 Not Found错误的解决办法
    [zt]SharePoint Calculate date column 日期计算列(20100916 23:04:14)
    PortalSiteMapProvider was unable to fetch children for node
    [ZT]SharePoint列表导入/导出命令 SharePoint列表导入/导出命令
    [ZT]一个女IT民工的梦
    “System.Collections.Generic.IEnumerable<TestDAL.HistoryData>”不包含“ToList”的定义
    C#生成随机序列
    利用C#线程窗口调试多线程程序
  • 原文地址:https://www.cnblogs.com/xiaoping1993/p/9365553.html
Copyright © 2011-2022 走看看