zoukankan      html  css  js  c++  java
  • Python入门(二,基础)

    一,基本语法

    Python标识符

    在python里,标识符有字母、数字、下划线组成。

    在python中,所有标识符可以包括英文、数字以及下划线(_),但不能以数字开头。

    python中的标识符是区分大小写的。

    以下划线开头的标识符是有特殊意义的。以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;

    以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。


    Python保留字符

    下面的列表显示了在Python中的保留字。这些保留字不能用作常数或变数,或任何其他标识符名称。

    所有Python的关键字只包含小写字母。

    and exec not
    assert finally or
    break for pass
    class from print
    continue global raise
    def if return
    del import try
    elif in while
    else is with
    except lambda yield

    行和缩进

    学习Python与其他语言最大的区别就是,Python的代码块不使用大括号({})来控制类,函数以及其他逻辑判断。python最具特色的就是用缩进来写模块。

    缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。

    多行语句

    Python语句中一般以新行作为为语句的结束符。

    但是我们可以使用斜杠( )将一行的语句分为多行显示,如下所示:

     total = item_one +  
            item_two + 
            item_three
       

    语句中包含[], {} 或 () 括号就不需要使用多行连接符。如下实例:

     days = ['Monday', 'Tuesday', 'Wednesday',
            'Thursday', 'Friday']
    

    Python 引号

    Python 接收单引号(' ),双引号(" ),三引号(''' """) 来表示字符串,引号的开始与结束必须的相同类型的。

    其中三引号可以由多行组成,编写多行文本的快捷语法,常用语文档字符串,在文件的特定地点,被当做注释。

    word = 'word'
    sentence = "This is a sentence."
    paragraph = """This is a paragraph. It is
    made up of multiple lines and sentences."""
    

    Python注释

    python中单行注释采用 # 开头。

    python没有块注释,所以现在推荐的多行注释也是采用的 #比如:

    #!/usr/bin/python
    
    # First comment
    print "Hello, Python!";  # second comment
    

    输出结果:

    Hello, Python!
    

    注释可以在语句或表达式行末:

    name = "Madisetti" # This is again comment
    

    多条评论:

    # This is a comment.
    # This is a comment, too.
    # This is a comment, too.
    # I said that already.
    

    Python空行

    函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

    空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

    记住:空行也是程序代码的一部分。


    等待用户输入

    下面的程序在按回车键后就会等待用户输入:

    #!/usr/bin/python
    
    raw_input("
    
    Press the enter key to exit.")
    

    以上代码中 ," "在结果输出前会输出两个新的空行。一旦用户按下键时,程序将退出。


    同一行显示多条语句

    Python可以在同一行中使用多条语句,语句之间使用分号(;)分割,以下是一个简单的实例:
    import sys; x = 'foo'; sys.stdout.write(x + '
    ')
    

    多个语句构成代码组

    缩进相同的一组语句构成一个代码块,我们称之代码组。

    像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。

    我们将首行及后面的代码组称为一个子句(clause)。

    如下实例:

    if expression : 
       suite 
    elif expression :  
       suite  
    else :  
       suite 
    

    命令行参数

    很多程序可以执行一些操作来查看一些基本信,Python可以使用-h参数查看各参数帮助信息:

    $ python -h 
    usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... 
    Options and arguments (and corresponding environment variables): 
    -c cmd : program passed in as string (terminates option list) 
    -d     : debug output from parser (also PYTHONDEBUG=x) 
    -E     : ignore environment variables (such as PYTHONPATH) 
    -h     : print this help message and exit 
     
    [ etc. ] 
    

    二,数据类型

    变量赋值

    Python中的变量不需要声明,变量的赋值操作既是变量声明和定义的过程。

    每个变量在内存中创建,都包括变量的标识,名称和数据这些信息。

    每个变量在使用前都必须赋值,变量赋值以后该变量才会被创建。

    等号(=)用来给变量赋值。

    等号(=)运算符左边是一个变量名,等号(=)运算符右边是存储在变量中的值。例如:

    #!/usr/bin/python

    counter = 100 # An integer assignment
    miles = 1000.0 # A floating point
    name = "John" # A string

    print counter
    print miles
    print name

    以上实例中,100,1000.0和"John"分别赋值给counter,miles,name变量。

    执行以上程序会输出如下结果:

    100
    1000.0
    John


    多个变量赋值

    Python允许你同时为多个变量赋值。例如:

    a = b = c = 1

    以上实例,创建一个整型对象,值为1,三个变量被分配到相同的内存空间上。

    您也可以为多个对象指定多个变量。例如:

    d, e, f = 2, 3, "john"

    以上实例,两个整型对象1和2的分配给变量a和b,字符串对象"john"分配给变量c。

    print a,b,c,d,e,f

    1 1 1 2 3 "john"



    标准数据类型

    在内存中存储的数据可以有多种类型。

    例如,person.s年龄作为一个数值存储和他或她的地址是字母数字字符存储。

    Python有一些标准类型用于定义操作上,他们和为他们每个人的存储方法可能。

    Python有五个标准的数据类型:

    • Numbers(数字)
    • String(字符串)
    • List(列表)
    • Tuple(元组)
    • Dictionary(字典)


    Python数字

    数字数据类型用于存储数值。

    他们是不可改变的数据类型,这意味着改变数字数据类型会分配一个新的对象。

    当你指定一个值时,Number对象就会被创建:

    var1 = 1
    var2 = 10

    您也可以使用del语句删除一些对象引用。

    del语句的语法是:

    del var1[,var2[,var3[....,varN]]]]

    您可以通过使用del语句删除单个或多个对象。例如:

    del var
    del var_a, var_b

    Python支持四种不同的数值类型:

    • int(有符号整型)
    • long(长整型[也可以代表八进制和十六进制])
    • float(浮点型)
    • complex(复数)
    实例

    一些数值类型的实例:

    int long float complex
    10 51924361L 0.0 3.14j
    100 -0x19323L 15.20 45.j
    -786 0122L -21.9 9.322e-36j
    080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
    -0490 535633629843L -90. -.6545+0J
    -0x260 -052318172735L -32.54e100 3e+26J
    0x69 -4721885298529L 70.2-E12 4.53e-7j
    • 长整型也可以使用小写"L",但是还是建议您使用大写"L",避免与数字"1"混淆。Python使用"L"来显示长整型。
    • Python还支持复数,复数由实数部分和虚数部分构成,可以用a + bj,或者complex(a,b)表示, 复数的实部a和虚部b都是浮点型


    Python字符串

    字符串或串(String)是由数字、字母、下划线组成的一串字符。

    一般记为 :

    s="a1a2···an"(n>=0)

    它是编程语言中表示文本的数据类型。

    python的字串列表有2种取值顺序:

    • 从左到右索引默认0开始的,最大范围是字符串长度少1
    • 从右到左索引默认-1开始的,最大范围是字符串开头

    如果你的实要取得一段子串的话,可以用到变量[头下标:尾下标],就可以截取相应的字符串,其中下标是从0开始算起,可以是正数或负数,下标可以为空表示取到头或尾。

    比如:

    s = 'ilovepython'

    s[1:5]的结果是love。

    当使用以冒号分隔的字符串,python返回一个新的对象,结果包含了以这对偏移标识的连续的内容,左边的开始是包含了下边界。

    上面的结果包含了s[1]的值l,而取到的最大范围不包括上边界,就是s[5]的值p。

    加号(+)是字符串连接运算符,星号(*)是重复操作。如下实例:

    #!/usr/bin/python

    str = 'Hello World!'

    print str # 输出完整字符串
    print str[0] # 输出字符串中的第一个字符
    print str[2:5] # 输出字符串中第三个至第五个之间的字符串
    print str[2:] # 输出从第三个字符开始的字符串
    print str * 2 # 输出字符串两次
    print str + "TEST" # 输出连接的字符串

    以上实例输出结果:

    Hello World!
    H
    llo
    llo World!
    Hello World!Hello World!
    Hello World!TEST


    Python列表

    List(列表) 是 Python 中使用最频繁的数据类型。

    列表可以完成大多数集合类的数据结构实现。它支持字符,数字,字符串甚至可以包含列表(所谓嵌套)。

    列表用[ ]标识。是python最通用的复合数据类型。看这段代码就明白。

    列表中的值得分割也可以用到变量[头下标:尾下标],就可以截取相应的列表,从左到右索引默认0开始的,从右到左索引默认-1开始,下标可以为空表示取到头或尾。

    加号(+)是列表连接运算符,星号(*)是重复操作。如下实例:

    #!/usr/bin/python

    list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
    tinylist = [123, 'john']

    print list # 输出完整列表
    print list[0] # 输出列表的第一个元素
    print list[1:3] # 输出第二个至第三个的元素
    print list[2:] # 输出从第三个开始至列表末尾的所有元素
    print tinylist * 2 # 输出列表两次
    print list + tinylist # 打印组合的列表

    以上实例输出结果:

    ['abcd', 786, 2.23, 'john', 70.200000000000003]
    abcd
    [786, 2.23]
    [2.23, 'john', 70.200000000000003]
    [123, 'john', 123, 'john']
    ['abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john']


    Python元组

    元组是另一个数据类型,类似于List(列表)。

    元组用"()"标识。内部元素用逗号隔开。但是元素不能二次赋值,相当于只读列表。

    #!/usr/bin/python

    tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
    tinytuple = (123, 'john')

    print list # 输出完整列表
    print list[0] # 输出列表的第一个元素
    print list[1:3] # 输出第二个至第三个的元素
    print list[2:] # 输出从第三个开始至列表末尾的所有元素
    print tinylist * 2 # 输出列表两次
    print list + tinylist # 打印组合的列表

    以上实例输出结果:

    ('abcd', 786, 2.23, 'john', 70.200000000000003)
    abcd
    (786, 2.23)
    (2.23, 'john', 70.200000000000003)
    (123, 'john', 123, 'john')
    ('abcd', 786, 2.23, 'john', 70.200000000000003, 123, 'john')

    以下是元组无效的,因为元组是不允许更新的。而列表是允许更新的:

    #!/usr/bin/python

    tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
    list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
    tuple[2] = 1000 # 元组中是非法应用
    list[2] = 1000 # 列表中是合法应用


    Python元字典

    字典(dictionary)是除列表意外python之中最灵活的内置数据结构类型。列表是有序的对象结合,字典是无序的对象集合。

    两者之间的区别在于:字典当中的元素是通过键来存取的,而不是通过偏移存取。

    字典用"{ }"标识。字典由索引(key)和它对应的值value组成。

    #!/usr/bin/python

    dict = {}
    dict['one'] = "This is one"
    dict[2] = "This is two"

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


    print dict['one'] # 输出键为'one' 的值
    print dict[2] # 输出键为 2 的值
    print tinydict # 输出完整的字典
    print tinydict.keys() # 输出所有键
    print tinydict.values() # 输出所有值

    输出结果为:

    This is one This is two {'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name'] ['sales', 6734, 'john']


    Python数据类型转换

    有时候,我们需要对数据内置的类型进行转换,数据类型的转换,你只需要将数据类型作为函数名即可。

    以下几个内置的函数可以执行数据类型之间的转换。这些函数返回一个新的对象,表示转换的值。

    函数 描述

    int(x [,base])

    将x转换为一个整数

    long(x [,base] )

    将x转换为一个长整数

    float(x)

    将x转换到一个浮点数

    complex(real [,imag])

    创建一个复数

    str(x)

    将对象 x 转换为字符串

    repr(x)

    将对象 x 转换为表达式字符串

    eval(str)

    用来计算在字符串中的有效Python表达式,并返回一个对象

    tuple(s)

    将序列 s 转换为一个元组

    list(s)

    将序列 s 转换为一个列表

    set(s)

    转换为可变集合

    dict(d)

    创建一个字典。d 必须是一个序列 (key,value)元组。

    frozenset(s)

    转换为不可变集合

    chr(x)

    将一个整数转换为一个字符

    unichr(x)

    将一个整数转换为Unicode字符

    ord(x)

    将一个字符转换为它的整数值

    hex(x)

    将一个整数转换为一个十六进制字符串

    oct(x)

    将一个整数转换为一个八进制字符串


    三,运算符

    Python算术运算符

    以下假设变量a为10,变量b为20:

    运算符 描述 实例
    + 加 - 两个对象相加 a + b 输出结果 30
    - 减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -10
    * 乘 - 两个数相乘或是返回一个被重复若干次的字符串 a * b 输出结果 200
    / 除 - x除以y b / a 输出结果 2
    % 取模 - 返回除法的余数 b % a 输出结果 0
    ** 幂 - 返回x的y次幂 a**b 输出结果 20
    // 取整除 - 返回商的整数部分 9//2 输出结果 4 , 9.0//2.0 输出结果 4.0

    以下实例演示了Python所有算术运算符的操作:

    #!/usr/bin/python
    
    a = 21
    b = 10
    c = 0
    
    c = a + b
    print "Line 1 - Value of c is ", c
    
    c = a - b
    print "Line 2 - Value of c is ", c 
    
    c = a * b
    print "Line 3 - Value of c is ", c 
    
    c = a / b
    print "Line 4 - Value of c is ", c 
    
    c = a % b
    print "Line 5 - Value of c is ", c
    
    a = 2
    b = 3
    c = a**b 
    print "Line 6 - Value of c is ", c
    
    a = 10
    b = 5
    c = a//b 
    print "Line 7 - Value of c is ", c
    

    以上实例输出结果:

    Line 1 - Value of c is 31
    Line 2 - Value of c is 11
    Line 3 - Value of c is 210
    Line 4 - Value of c is 2
    Line 5 - Value of c is 1
    Line 6 - Value of c is 8
    Line 7 - Value of c is 2
    

    Python比较运算符

    以下假设变量a为10,变量b为20:

    运算符 描述 实例
    == 等于 - 比较对象是否相等 (a == b) 返回 False。
    != 不等于 - 比较两个对象是否不相等 (a != b) 返回 true.
    <> 不等于 - 比较两个对象是否不相等 (a <> b) 返回 true。这个运算符类似 != 。
    > 大于 - 返回x是否大于y (a > b) 返回 False。
    < 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 (a < b) 返回 true。
    >= 大于等于 - 返回x是否大于等于y。 (a >= b) 返回 False。
    <= 小于等于 - 返回x是否小于等于y。 (a <= b) 返回 true。

    以下实例演示了Python所有比较运算符的操作:

    #!/usr/bin/python
    
    a = 21
    b = 10
    c = 0
    
    if ( a == b ):
       print "Line 1 - a is equal to b"
    else:
       print "Line 1 - a is not equal to b"
    
    if ( a != b ):
       print "Line 2 - a is not equal to b"
    else:
       print "Line 2 - a is equal to b"
    
    if ( a <> b ):
       print "Line 3 - a is not equal to b"
    else:
       print "Line 3 - a is equal to b"
    
    if ( a < b ):
       print "Line 4 - a is less than b" 
    else:
       print "Line 4 - a is not less than b"
    
    if ( a > b ):
       print "Line 5 - a is greater than b"
    else:
       print "Line 5 - a is not greater than b"
    
    a = 5;
    b = 20;
    if ( a <= b ):
       print "Line 6 - a is either less than or equal to  b"
    else:
       print "Line 6 - a is neither less than nor equal to  b"
    
    if ( b >= a ):
       print "Line 7 - b is either greater than  or equal to b"
    else:
       print "Line 7 - b is neither greater than  nor equal to b"
    

    以上实例输出结果:

    Line 1 - a is not equal to b
    Line 2 - a is not equal to b
    Line 3 - a is not equal to b
    Line 4 - a is not less than b
    Line 5 - a is greater than b
    Line 6 - a is either less than or equal to b
    Line 7 - b is either greater than or equal to b 
    

    Python赋值运算符

    以下假设变量a为10,变量b为20:

    运算符 描述 实例
    = 简单的赋值运算符 c = a + b 将 a + b 的运算结果赋值为 c
    += 加法赋值运算符 c += a 等效于 c = c + a
    -= 减法赋值运算符 c -= a 等效于 c = c - a
    *= 乘法赋值运算符 c *= a 等效于 c = c * a
    /= 除法赋值运算符 c /= a 等效于 c = c / a
    %= 取模赋值运算符 c %= a 等效于 c = c % a
    **= 幂赋值运算符 c **= a 等效于 c = c ** a
    //= 取整除赋值运算符 c //= a 等效于 c = c // a

    以下实例演示了Python所有赋值运算符的操作:

    #!/usr/bin/python
    
    a = 21
    b = 10
    c = 0
    
    c = a + b
    print "Line 1 - Value of c is ", c
    
    c += a
    print "Line 2 - Value of c is ", c 
    
    c *= a
    print "Line 3 - Value of c is ", c 
    
    c /= a 
    print "Line 4 - Value of c is ", c 
    
    c  = 2
    c %= a
    print "Line 5 - Value of c is ", c
    
    c **= a
    print "Line 6 - Value of c is ", c
    
    c //= a
    print "Line 7 - Value of c is ", c
    

    以上实例输出结果:

    Line 1 - Value of c is 31
    Line 2 - Value of c is 52
    Line 3 - Value of c is 1092
    Line 4 - Value of c is 52
    Line 5 - Value of c is 2
    Line 6 - Value of c is 2097152
    Line 7 - Value of c is 99864
    

    Python位运算符

    按位运算符是把数字看作二进制来进行计算的。Python中的按位运算法则如下:

    运算符 描述 实例
    & 按位与运算符 (a & b) 输出结果 12 ,二进制解释: 0000 1100
    | 按位或运算符 (a | b) 输出结果 61 ,二进制解释: 0011 1101
    ^ 按位异或运算符 (a ^ b) 输出结果 49 ,二进制解释: 0011 0001
    ~ 按位取反运算符 (~a ) 输出结果 -61 ,二进制解释: 1100 0011, 在一个有符号二进制数的补码形式。
    << 左移动运算符 a << 2 输出结果 240 ,二进制解释: 1111 0000
    >> 右移动运算符 a >> 2 输出结果 15 ,二进制解释: 0000 1111

    以下实例演示了Python所有位运算符的操作:

    #!/usr/bin/python
    
    a = 60            # 60 = 0011 1100 
    b = 13            # 13 = 0000 1101 
    c = 0
    
    c = a & b;        # 12 = 0000 1100
    print "Line 1 - Value of c is ", c
    
    c = a | b;        # 61 = 0011 1101 
    print "Line 2 - Value of c is ", c
    
    c = a ^ b;        # 49 = 0011 0001
    print "Line 3 - Value of c is ", c
    
    c = ~a;           # -61 = 1100 0011
    print "Line 4 - Value of c is ", c
    
    c = a << 2;       # 240 = 1111 0000
    print "Line 5 - Value of c is ", c
    
    c = a >> 2;       # 15 = 0000 1111
    print "Line 6 - Value of c is ", c
    

    以上实例输出结果:

    Line 1 - Value of c is 12
    Line 2 - Value of c is 61
    Line 3 - Value of c is 49
    Line 4 - Value of c is -61
    Line 5 - Value of c is 240
    Line 6 - Value of c is 15
    

    Python逻辑运算符

    Python语言支持逻辑运算符,以下假设变量a为10,变量b为20:

    运算符 描述 实例
    and 布尔"与" - 如果x为False,x and y返回False,否则它返回y的计算值。 (a and b) 返回 true。
    or 布尔"或" - 如果x是True,它返回True,否则它返回y的计算值。 (a or b) 返回 true。
    not 布尔"非" - 如果x为True,返回False。如果x为False,它返回True。 not(a and b) 返回 false。

    以下实例演示了Python所有逻辑运算符的操作:

    #!/usr/bin/python
    
    a = 10
    b = 20
    c = 0
    
    if ( a and b ):
       print "Line 1 - a and b are true"
    else:
       print "Line 1 - Either a is not true or b is not true"
    
    if ( a or b ):
       print "Line 2 - Either a is true or b is true or both are true"
    else:
       print "Line 2 - Neither a is true nor b is true"
    
    
    a = 0
    if ( a and b ):
       print "Line 3 - a and b are true"
    else:
       print "Line 3 - Either a is not true or b is not true"
    
    if ( a or b ):
       print "Line 4 - Either a is true or b is true or both are true"
    else:
       print "Line 4 - Neither a is true nor b is true"
    
    if not( a and b ):
       print "Line 5 - a and b are true"
    else:
       print "Line 5 - Either a is not true or b is not true"
    

    以上实例输出结果:

    Line 1 - a and b are true
    Line 2 - Either a is true or b is true or both are true
    Line 3 - Either a is not true or b is not true
    Line 4 - Either a is true or b is true or both are true
    Line 5 - a and b are true
    

    Python成员运算符

    除了以上的一些运算符之外,Python还支持成员运算符,测试实例中包含了一系列的成员,包括字符串,列表或元组。

    运算符 描述 实例
    in 如果在指定的序列中找到值返回True,否则返回False。 x 在 y序列中 , 如果x在y序列中返回True。
    not in 如果在指定的序列中没有找到值返回True,否则返回False。 x 不在 y序列中 , 如果x不在y序列中返回True。

    以下实例演示了Python所有成员运算符的操作:

    #!/usr/bin/python
    
    a = 10
    b = 20
    list = [1, 2, 3, 4, 5 ];
    
    if ( a in list ):
       print "Line 1 - a is available in the given list"
    else:
       print "Line 1 - a is not available in the given list"
    
    if ( b not in list ):
       print "Line 2 - b is not available in the given list"
    else:
       print "Line 2 - b is available in the given list"
    
    a = 2
    if ( a in list ):
       print "Line 3 - a is available in the given list"
    else:
       print "Line 3 - a is not available in the given list"
    

    以上实例输出结果:

    Line 1 - a is not available in the given list
    Line 2 - b is not available in the given list
    Line 3 - a is available in the given list
    

    Python身份运算符

    身份运算符用于比较两个对象的存储单元

    运算符 描述 实例
    is is是判断两个标识符是不是引用自一个对象 x is y, 如果 id(x) 等于 id(y) , is 返回结果 1
    is not is not是判断两个标识符是不是引用自不同对象 x is not y, 如果 id(x) 不等于 id(y). is not 返回结果 1

    以下实例演示了Python所有身份运算符的操作:

    #!/usr/bin/python
    
    a = 20
    b = 20
    
    if ( a is b ):
       print "Line 1 - a and b have same identity"
    else:
       print "Line 1 - a and b do not have same identity"
    
    if ( id(a) == id(b) ):
       print "Line 2 - a and b have same identity"
    else:
       print "Line 2 - a and b do not have same identity"
    
    b = 30
    if ( a is b ):
       print "Line 3 - a and b have same identity"
    else:
       print "Line 3 - a and b do not have same identity"
    
    if ( a is not b ):
       print "Line 4 - a and b do not have same identity"
    else:
       print "Line 4 - a and b have same identity"
    

    以上实例输出结果:

    Line 1 - a and b have same identity
    Line 2 - a and b have same identity
    Line 3 - a and b do not have same identity
    Line 4 - a and b do not have same identity 
    

    Python运算符优先级

    以下表格列出了从最高到最低优先级的所有运算符:

    运算符 描述
    ** 指数 (最高优先级)
    ~ + - 按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)
    * / % // 乘,除,取模和取整除
    + - 加法减法
    >> << 右移,左移运算符
    & 位 'AND'
    ^ | 位运算符
    <= < > >= 比较运算符
    <> == != 等于运算符
    = %= /= //= -= += *= **= 赋值运算符
    is is not 身份运算符
    in not in 成员运算符
    not or and 逻辑运算符

    以下实例演示了Python所有运算符优先级的操作:

    #!/usr/bin/python
    
    a = 20
    b = 10
    c = 15
    d = 5
    e = 0
    
    e = (a + b) * c / d       #( 30 * 15 ) / 5
    print "Value of (a + b) * c / d is ",  e
    
    e = ((a + b) * c) / d     # (30 * 15 ) / 5
    print "Value of ((a + b) * c) / d is ",  e
    
    e = (a + b) * (c / d);    # (30) * (15/5)
    print "Value of (a + b) * (c / d) is ",  e
    
    e = a + (b * c) / d;      #  20 + (150/5)
    print "Value of a + (b * c) / d is ",  e
    

    以上实例输出结果:

    Value of (a + b) * c / d is 90
    Value of ((a + b) * c) / d is 90
    Value of (a + b) * (c / d) is 90
    Value of a + (b * c) / d is 50
    

    四:条件语句

    Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。

    可以通过下图来简单了解条件语句的执行过程:

    decision_making

    Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。

    Python 编程中 if 语句用于控制程序的执行,基本形式为:

    if 判断条件:
        执行语句……
    else:
        执行语句……
    

    其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。

    else 为可选语句,当需要在条件不成立时执行内容则可以执行相关语句,具体例子如下:

    # coding=utf8
    # 例1:if 基本用法
    
    flag = False
    name = 'luren'
    if name == 'python':         # 判断变量否为'python'
        flag = True          # 条件成立时设置标志为真
        print 'welcome boss'    # 并输出欢迎信息
    else:
        print name              # 条件不成立时输出变量名称
    

    输出结果为:

    >>> luren			# 输出结果
    

    if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)来表示其关系。

    当判断条件为多个值是,可以使用以下形式:

    if 判断条件1:
        执行语句1……
    elif 判断条件2:
        执行语句2……
    elif 判断条件3:
        执行语句3……
    else:
        执行语句4……
    

    实例如下:

    # coding=utf8
    # 例2:elif用法
    
    num = 5     
    if num == 3:            # 判断num的值
        print 'boss'        
    elif num == 2:
        print 'user'
    elif num == 1:
        print 'worker'
    elif num < 0:           # 值小于零时输出
        print 'error'
    else:
        print 'roadman'     # 条件均不成立时输出
    

    输出结果为:

    >>> roadman		# 输出结果
    

    由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。

    # coding=utf8
    # 例3:if语句多个条件
    
    num = 9
    if num >= 0 and num <= 10:    # 判断值是否在0~10之间
        print 'hello'
    >>> hello		# 输出结果
    
    num = 10
    if num < 0 or num > 10:    # 判断值是否在小于0或大于10
        print 'hello'
    else:
    	print 'undefine'
    >>> undefine		# 输出结果
    
    num = 8
    # 判断值是否在0~5或者10~15之间
    if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    
        print 'hello'
    else:
        print 'undefine'
    >>> undefine		# 输出结果
    

    当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。

    简单的语句组

    你也可以在同一行的位置上使用if条件判断语句,如下实例:

    #!/usr/bin/python 
     
    var = 100 
     
    if ( var  == 100 ) : print "Value of expression is 100" 
     
    print "Good bye!" 
    

    以上代码执行输出结果如下:

    Value of expression is 100
    Good bye!
    

    五:循环语句

    Python 循环语句

    本章节将向大家介绍Python的循环语句,程序在一般情况下是按顺序执行的。

    编程语言提供了各种控制结构,允许更复杂的执行路径。

    循环语句允许我们执行一个语句或语句组多次,下面是在大多数编程语言中的循环语句的一般形式:

    loop_architecture

    Python提供了for循环和while循环(在Python中没有do..while循环):

    循环类型 描述
    while 循环 在给定的判断条件为 true 时执行循环体,否则退出循环体。
    for 循环 重复执行语句
    嵌套循环 你可以在while循环体中嵌套for循环


    循环控制语句

    循环控制语句可以更改语句执行的顺序。Python支持以下循环控制语句:

    控制语句 描述
    break 语句 在语句块执行过程中终止循环,并且跳出整个循环
    continue 语句 在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。
    pass 语句 pass是空语句,是为了保持程序结构的完整性。

    六:While循环语句



  • 相关阅读:
    增强MyEclipse提示功能
    Mysql安装配置,修改初试密码。
    在我的电脑里面创建图标
    popup non topmost
    多线程下载或上传数据限速
    SynchronizationContext
    linux运维笔记——常用命令详解diff
    linux运维笔记——curl
    linux下mysql的源码安装
    shell编程——变量的数值计算
  • 原文地址:https://www.cnblogs.com/bill-technology/p/4130833.html
Copyright © 2011-2022 走看看