zoukankan      html  css  js  c++  java
  • Python初学笔记

    <<Python初学笔记>>

         下面分三部分来从感性认识到理性命令代码測试来逐步掌握和熟悉Python脚本;重要的是第三部分,把第三部分中每一条命令,每个函数,都要亲自測试并显示正确结果。运用熟练就ok

    ==========================================================

    第一部分:当前python应用实例

      google web爬虫,搜索引擎

      yahoo, 管理讨论组

      youtobe, 分享服务

      豆瓣网的前台+后台+server都用的是python

    第二部分:Python概念总体介绍

      定位:解释性的。面向对象的带有动态语义的程序设计语言

      python特性

      脚本语言

      高阶动态编程语言

      简单易学

      解释性&编译性:不须要变异成二进制,可是须要解释器, 也能够进行编译,速度更快

      面向对象:及支持面向过程编程又支持面向对象的编程

      可扩展性挤可嵌入性。能够嵌入到c/c++程序。提供脚本功能。部分程序也能够用c编写

      可移植性:全部程序无需不论什么改动就可以运行在不论什么平台

      丰富的库:password系统。GUI, TK,文档生成,单元測试。线程。CGI。 电子邮件

                其他高质量库:wxPython, Twisted, Python图像库等等

      自己主动化的内存管理

      免费,开源

      和其他语言结合开发快。又叫胶水语言

      认识文件类型三种形式:

    1源码: 以.py为扩展名,有python程序解释,不须要编译

    2字节代码:编译后生成扩展名为.pyc的文件

              import py_compile

              py_compile.compile("hello.py")

    3优化代码:经过优化的源文件, 扩展名为.pyo

    以上三种均可直接运行

    第三部分:Python语言命令和代码的运行測试

    1.py

    print("hello, world")

    运行 python 1.py

    ==> hello, world

    2.py

    import py_compile

    py_compile.compile('1.py')

    生成文件__pycache__/1.cpython-33.pyc

    运行 python 1.cpython-33.pyc

    ==> hello, world

    生成优化代码:

    运行 python -O -m py_compile 1.py

    生成文件__pycache__/1.cpython-33.pyo

    运行 python 1.cpython-33.pyo

    ==> hello, world

    python变量

    ===========================================

    >>a1 = 123

    >>a2 = 123

    >>id(a1)

    505912912

    >>id(a2)

    505912912

    c语言不同,c语言给变量名开辟空间,存放数值。python则相反,数值是存在内存中的

    不同变量能够指向同一地址空间的数值

    python运算符&表达式

    =============================================

    赋值运算符

    -----------------------

    = += -= *= /= %=

    算数运算符

    -----------------------

    + - * / //(整数除法) %(求余) **(求幂)

    >> 4/3 

    1.33333333333333

    >> 4//3

    1

    关系运算符

    -----------------------

    < > <= >= != ==

    >> a = 1

    >> b = 1.0

    >> a == b

    true

    >> a = "hello"

    >> b = "hello"

    >> a == b

    true

    逻辑运算符

    ------------------------

    and or not

    优先级(低到高)

    ================================

    或 or

    与 and 

    非 not 

    成员:in, not in

    同一性:is ,is not

    < , <=, >, >=, !=, ==

    按位或 |

    按位异或 ^

    按位与 &

    移位 << , >>

    +, -

    *, /, %

    正负号 +x, -x

    按位翻转 ~x

    指数 **

    数据类型

    =======================

    数字类型

      2.x版本号中分为:整型,长整型,浮点型。复数型

      3.x版本号中氛围:整型,浮点型。复数型

      能够用type函数查看类型

    >> a = 111

    >> type(a)

    int

    >> a = 1.23

    >> type(a)

    float

    >> a = 12j

    >> type(a)

    complex

    字符串类型

    >> "let's go" #正确

    >> 'let's go' #错误

    转义

    >> a = "let's "go""

    >> print(a)

    let's "go"

    换行 

    不使用换行,使用三重引號 ''' xxxxxxx  '''

    >> str = 'abc'

    >> str[0]

    a

    >> str = "abc"

    >> str[0]

    a

    切片&索引 操作:

    >> a = "123456"

    >> a[1:4]

    1234

    >> a[2:]

    3456

    >> a[:4]

    1234

    >> a[-1]

    6

    >> a[::1] 间隔0个一取

    123456

    >> a[::2] 间隔1个一取

    135

    >> a[:]

    123456

    >> a[::]

    123456

    序列

     列表,元组,和字符串都是序列

     序列的两个主要特点:索引操作符和切片操作符

    序列的基本操作:

    len()

    >> len("abcdef")

    *

    >> 5*"a"

    +

    >> "abc" + "bcd"

    in

    >> "a" in "abc"

    max()

    >> max("adfe")

    f

    min()

    >> min("dfa")

    a

    cmp(tuple1, tuple2)

    tuple1> tuple2 ==> 1

    tuple1< tuple2 ==> -1 

    tuple1 = tuple2 ==> 0

    cmp("abc", "123") ?

    cmp 3.x版本号中不存在

    元组

    元组和列表十分类似,仅仅只是元组和字符串一样是不可变的,即不能改动

    通经常使用在使用语句或者用户定义的函数,能够安全的採用一组值的时候

    创建元组()

    空元组 a = ()

    含有单个元素的元组 a = ("a",)

    一般的元组 a = ("a", "b")

    >> a = ()

    >> b = (2,)

    >> c = (1,2)

    >> type(a) ==> tuple

    >> type(b) ==> tuple

    >> type(c) ==> tuple

    错误的写法

    >> d = (2)

    >> type(d) ==> int

    >> d = ("ss")

    >> type(d) ==> str

    元组的值不能改动

    >> a = (2,3)

    >> a[1] = 4 #报错TypeError: 'tuple' object does not support item assignment

    赋值

    >> name,age,sex = ("zhang", 20, "man")

    >> name ==> "zhang"

    >> age ==> 20

    >> sex ==> "man"

    #列表list[]

    列表元素可变

    >> a = [1]

    >> type(a) ==> list

    基本操作

    索引 list[index]

    切片 list[:]

    加入 list.append()

    查找 var in list

    删除 list.remove() #删除第一个出现的元素

    >> a = [1,2,3,2]

    >> a.remove(2) ==> [1,3,2]

    系统方法del

    >> del(a[0]) ==> [3,2]

    注意:列表又一次赋值后,地址空间不变

    >> list = [1, 3]

    >> id(list) => 85445

    >> list[0] = 2

    >> id(list) => 85445 

    条件表达式

    python使用缩进作为其语言的分组方法

    假设缩进不统一。程序报错

    if 1 > 2:

       print("ok")

       print("ok")

       print("xx")

    print("no")

    ==> no

    if 1 > 2:

       print("ok")

       print("ok")

      print("xx")

    print("no")

    ==> IndentationError: unindent does not match any outer indentation level

    x = 99

    if x > 90:

        print("A")

    elif x > 80:

        print("B")

    elif x > 70:

        print("C")

    else:

        print("D")

    取反,用not,不能用!

    if not 0

        print("OK")

    循环遍历:

    for i in range(10):

        print("hello ,world")

    for i in [1,3,4,5,5]:

        print(i)

    for i in range(1,10):

        print(i)

    ==> 1,2,3..10

    for i in range(1, 10, 2):

        print(i)

    ==> 1,3,5,7,9

    列表的遍历:

    d = {2:333, 4:444, 5:666}

    for k,v in d.items():

        print(k)

        print(v)

    else:

        print("ending")

    结果==>

    2

    333

    4

    444

    5

    666

    ending

    -------------------------------

    比較特殊的,pythonfor循环能够接else,当循环正常运行完成后

    运行else中的语句,假设循环中断。则不会运行else的语句

    d = {1:333, 2:444, 3:666, 4: 444, 5: 777}

    for k,v in d.items():

        if k == 2:

            break

        else:

            print(k)

            print(v)

    else:

        print("ending")

    结果==> 

    1

    333

    pass 代码桩,什么也不做

    continue 继续

    exit() 退出程序

    ---------------------------------------

    d = {1:333, 2:444, 3:666, 4: 444, 5: 777}

    for k,v in d.items():

        if k == 3:

            break

        if k == 2:

            pass

            continue

        if k == 5:

            exit()

        else:

            print(k)

            print(v)

    else:

        print("ending")

    while 循环:

    --------------------------------------------

    $ cat while.py

    while条件为false时,才会运行else中的语句

    x = ""

    while x != "q":

       print("hello")

       x = input("input something, q for quit: ")

       if not x :

           break

    else:

       print("ending")

    函数:

    ------------------------------

    a = 2

    b = 3

    def add():

        c=a+b

        print(c)

    add()

    ==> 5

    这个有点不安全吧,要是函数体中得变量不小心和函数外的变量重名,那不是麻烦了?

    def new_add(x, y):

        z = x + y

        print(z)

    add()

    new_add(3,4)

    传參

    ----------------------------------

    def add(x = 3, y = 4):

        c = x + y

        print(c)

    add()

    add(y = 5) #能够单独传參。可是假设x没有默认值就不行了

    全局变量

    -------------------------

    $ cat global.py

    x = "global var"

    def change():

        x = 100

    print(x)

    ==> "global var"

    ------------------------------

    $ cat global.py

    x = "global var"

     

    def change():

        global x

        x = 100

    change() #运行了change()方法以后。global x ,相当于给x又一次赋值了

    print(x)

    ==> 100

    元组作为參数

    -------------------------

    $ cat function1.py

    def add(x, y):

            print("%s : %s" % (x,y))

    add("hello", "world")

    a = ("hello", "world")

    b = ("hello", "pthon", "world")

    add(a)  #错误,a作为一个总体传给了x,报參数错误

    add(*a) #正确, 当元组元素的个数于函数參数的个数同样的时候。则x=a[0], y=a[1]

    add(*b) #错误。 当元组元素的个数不等于函数參数的个数时,报參数错误

    add(y="world", x="hello") #正确,能够指定參数传值,也就是说顺序没有关系

    字典作为參数

    -------------------------------------

    def add(x, y):

            print("%s : %s" % (x,y))

    d={"y":"world", "x":"hello"}

    d1={"y":"world", "x":"hello", "z": "python"}

    add(**d) #正确输出==> hello, world

    add(**d1) #错误。add() got an unexpected keyword argument 'z'

    接受多余參数 

    ------------------------------------------------------

    *args(剩余的參数作为元组), **args(剩余的參数作为字典)

    $ cat function2.py

     

    def p(x, *args):

            print(x)

            print(args)

    p(1)

    p(1,2,3)

    ==>1

    ==>()

    ==>1

    ==>(2, 3)

    p(x=1,y=3)

    ==> p() got an unexpected keyword argument 'y'

    y=3不能作为多余參数保存在args中。能够用**args来保存

    -----------------------------------------------------

    $ cat function2.py

     

    def p(x,**args):

            print(x)

            print(args)

    p(1)

    p(x=2,y=4)

    ==>1

    ==>{}

    ==>2

    ==>{'y': 4}

     

    p(1,x=3) #错误,第一个參数付给了x,那么相当于穿了x=1,x=3

    ==>p() got multiple values for argument 'x'

    同一时候接受*args, **args的情况

    ------------------------------------------------------

    def p(x,*args,**other_args):

            print(x)

            print(args)

            print(other_args)

    p(1)

    ==>1

    ==>()

    ==>{}

    p(3,3,z=5)

    ==>3

    ==>(3,)

    ==>{"z":5}

    參数的顺序不能变

    p(y=3,3,5) #错误。SyntaxError: non-keyword arg after keyword arg

    p(3,4,y=4,5) #错误,SyntaxError: non-keyword arg after keyword arg

    lambda表达式

    ----------------------------------

    lambda函数是一种高速定义单行的最小函数, 从lisp借用而来,能够用在不论什么

    须要函数的地方

     

    g = lambda x,y: x+y

    g(1,2) ==> 3

    lambda的优点:

    1.写一些运行脚本,省去函数的定义过程。让代码更简洁

    2.省去抽象函数命名的问题

    3.让代码更easy理解(sometime)

    swtich, python中没有swtich,能够使用字典来实现switch

    ------------------------------------------------------

    x=1

    y=4

    dd = {

      "+": x+y,

      "-": x-y

    }

    print(dd)

    print(dd.get("+"))

    print(dd.get("-"))

    内置函数

    ----------------------------------------------------

    查看文档:

    help(str.replace)

    str.capilize()

    str.split()

    str.replace()

    异常处理

    --------------------------------------------

    contents = {"tomato":4, "banana":3}

    try:

      if contents["apple"] > 3:

        print("i have apples")

    except (KeyError) as error:

      print("i have no %s" % error)

    ==> i have no 'apple'

查看全文
  • 相关阅读:
    网页加速的14条优化法则 网站开发与优化
    .NET在后置代码中输入JS提示语句(背景不会变白)
    C语言变量声明内存分配
    SQL Server Hosting Toolkit
    An established connection was aborted by the software in your host machine
    C语言程序设计 2009春季考试时间和地点
    C语言程序设计 函数递归调用示例
    让.Net 程序脱离.net framework框架运行
    C语言程序设计 答疑安排(2009春季 110周) 有变动
    软件测试技术,软件项目管理 实验时间安排 2009春季
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10571263.html
  • Copyright © 2011-2022 走看看