您的位置:首页 > 其它

Chapter05 条件、循环和其他语句

2013-12-06 00:01 323 查看
输出:

    >>> print 'Age:', 52

    Age: 52

    >>> 1,2,3

    (1, 2, 3)

    >>> print 1,2,3

    1 2 3

    >>> print (1,2,3)

    (1, 2, 3)

    >>>

    >>> name = 'Merisc'

    >>> salutation = 'Mr.'

    >>> greeting = 'Hello, '

    >>> print greeting, salutation, name

    Hello,  Mr. Merisc

    >>> print greeting + ',', salutation, name

    Hello, , Mr. Merisc

    >>>  

导入:

    >>> import math

    >>> from math import sqrt

    >>> from math import sqrt, log

    >>> from math import*

    >>>

    两个来自不同模板的open

    module1.open()

    module2.open()

    import ... as ... 改变不喜欢的函数名为自己喜欢的

    >>> import math as foobar

    >>> foobar.sqrt(4)

    2.0

    >>> from math import sqrt as foobar

    >>> foobar(4)

    2.0

    两个来自不同模板的open  也可以

    >>>from module1 import open as open1

    >>>from module2 import open as open2

    >>>

赋值:

    序列解包

    >>> x,y,z = 1,2,3

    >>> print x,y,z

    1 2 3

    

    跟换值操作,变简单

    >>> x,y = y,x

    >>> print x,y,z

    2 1 3

    >>>

    

    >>> values = 1,2,3

    >>> values

    (1, 2, 3)

    >>> x,y,z = values

    >>> y

    2

    >>>

    

    >>> scoundrel = {'name':'Robin', 'girlfriend':'Marion'}

    >>> key, value = scoundrel.popitem()

    >>> key

    'girlfriend'

    >>> value

    'Marion'

    >>>

    

链式赋值(chained assignment)

    >>> x = y = 1

    >>> x

    1

    >>> y

    1

    >>>

增量赋值(augmented assignment):

    >>> f = 'foo'

    >>> f += 'bar'

    >>> f *= 2

    >>> f

    'foobarfoobar'

    >>>

    

布尔变量

    下面的值作为布尔表达式的时候,是false

    False None 0 "" () [] {}

    >>>

    >>> bool(())

    False

    >>> true    # 注意这里要大写开头

    Traceback (most recent call last):

      File "<pyshell#50>", line 1, in <module>

        true

    NameError: name 'true' is not defined

    >>> True

    True

    >>> bool(3)

    True

    >>> bool(0)

    False

    >>>

条件和条件语句   if/elif/else

    num = input('Enter a number: ')

    if num > 0:

        print 'Positive'

    elif num < 0:

        print 'Negative'

    else:

            print 'Zero'

    若改为

    num = raw_input('Enter a number: ')

    一直Positive,以为是raw!

    age = input('age: ')

    if 18 <= age <= 50 :

        print 'You are allowed to get in'

    elif 50 < age <=65:

        print 'You are not suggested to get in'

    elif 65 < age:

        print 'You are too old to get in'

    else:

        print 'You are too young to get in'

    >>>

    

    >>> name = raw_input('Enter your name: ') or '<unknown>'

    Enter your name:

    >>> name

    '<unknown>'

    >>> name = raw_input('Enter your name: ') or '<unknown>'

    Enter your name: mrsj

    >>> name

    'mrsj'

    >>>

    

    

    >>> 3 if 1 else -3

    3

    >>> -3 if 1 else 3

    -3

    >>>

    

比较操作符

    >>> x = y = [1,2,3]

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

    >>> x == y

    True

    >>> x == z

    True

    >>> x is y             #is是比较同一性(同一个对象)而不是相等性

    True

    >>> x is z

    False

    >>>

    >>> 'alpha' < 'beta'

    True

    >>> "alpha" < "beta"

    True

    >>> 'F' < 'f'

    True

    >>> 'F' > 'f'

    False

    >>> 'Fon' < 'fon'

    True

    >>> [1,2] < [2,1]

    True

    >>> [2,[1,4]] < [2,[1,5]]

    True

    >>>

    

断言

    if 的近亲

    工作方式:

        if not condition:

            crash program

    >>> age = 10

    >>> assert 0 < age < 100

    >>> age = -1

    >>> assert 0 < age < 100

    Traceback (most recent call last):

      File "<pyshell#79>", line 1, in <module>

        assert 0 < age < 100

    AssertionError

    

    条件后可以添加字符串,用来解释断言

    >>> assert 0 < age < 100, 'The age must be realistic'

    Traceback (most recent call last):

      File "<pyshell#80>", line 1, in <module>

        assert 0 < age < 100, 'The age must be realistic'

    AssertionError: The age must be realistic

    >>>

while循环

    >>> x = 1

    >>> while x <= 10:

        print x

        x += 1

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

for循环

    >>> words = ['this', 'is', 'an', 'ex', 'parrot']

    >>> for word in words:

        print word

        

    this

    is

    an

    ex

    parrot

    >>>

    >>> numbers = [0,1,2,3,4,5]

    >>> for num in numbers:

        print num

        

    0

    1

    2

    3

    4

    5

    >>>

    内建的范围函数

    >>> range(0,3)

    [0, 1, 2]

    >>> for number in range(1,4):

        print number

        

    1

    2

    3

    >>>

    如果能使用for就尽量不要用while

    >>> d = {'x':1, 'y':2, 'z':3}

    >>> for key in d:

        print key, 'corresponds to', d[key]

        

    y corresponds to 2

    x corresponds to 1

    z corresponds to 3

    >>>

    >>> for key, value in d.items():

        print key, 'corresponds to', value

    y corresponds to 2

    x corresponds to 1

    z corresponds to 3

    >>>

    for循环的好处就是可以循环中使用序列解包

并行迭代

    程序可以同时迭代两个序列。

    >>> names = ['anne', 'beh', 'getor', 'damon']

    >>> ages = [12,34,32,102]

    >>> for i in range(len(names))            忘记加: 导致错误

    SyntaxError: invalid syntax

    >>> for i in range(len(names)):

        print names[i], 'is', ages[i], 'years old'

    anne is 12 years old

    beh is 34 years old

    getor is 32 years old

    damon is 102 years old

    内建的zip函数也可以用来进行并行迭代,可以吧两个序列“压缩“在一起,然后返回一个元组的列表:

    >>> zip(names, ages)

    [('anne', 12), ('beh', 34), ('getor', 32), ('damon', 102)]

    在循环中解包元组:

    >>> for name, age in zip(names, ages):

        print name, 'is', age, 'years old'

    anne is 12 years old

    beh is 34 years old

    getor is 32 years old

    damon is 102 years old

    zip函数也可以作用域任意多的序列。

    >>> zip(range(5), xrange(100000000))

    [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

编号迭代

    想要迭代序列中的对象,同时还想要获取当前对象的索引

    在一个字符串列表中替换所有包含‘xxx'的子字符串。

    >>> strings = ["mrsj", "Merisc", "risc"]

    >>> for strs in strings:

            if 'risc' in strs:

                index = strings.index(strs)

                strings[index] = '[censored]'

    Traceback (most recent call last):

      File "<pyshell#38>", line 3, in <module>

        index = strings.index(strs)

    AttributeError: 'set' object has no attribute 'index'

    

    较好的版本:

    >>> index = 0

    >>> for string in strings:

        if 'risc' in string:

            strings[index] = '[censored]'

        index += 1

    >>> for string in strings:

        print string

    mrsj

    [censored]

    [censored]

    

    有点笨。另一种方法是使用内建的enumerate函数:

    >>> strings = ["mrsj", "Merisc", "risc"]

    >>> for index, string in enumerate(strings):

            if 'risc' in string:

                strings[index] = '[censored]'

    >>> for str in strings:

            print str

    mrsj

    [censored]

    [censored]

    

翻转和排序迭代:

    >>> sorted([4,3,6,8,3])

    [3, 3, 4, 6, 8]

    >>> sorted('Hello World!')

    [' ', '!', 'H', 'W', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r']

    >>> list(reversed('Hello World!'))

    ['!', 'd', 'l', 'r', 'o', 'W', ' ', 'o', 'l', 'l', 'e', 'H']

    >>> ''.join(reversed('Hello World!'))

    '!dlroW olleH'

    

    >>> nums = [4,3,6,8,3]

    >>> nums

    [4, 3, 6, 8, 3]

    >>> sorted(nums)

    [3, 3, 4, 6, 8]

    >>> nums

    [4, 3, 6, 8, 3]

    >>> str = 'Hello World!'

    >>> str

    'Hello World!'

    >>> reversed(str)

    <reversed object at 0x00000000030B5320>

    >>> list(reversed(str))

    ['!', 'd', 'l', 'r', 'o', 'W', ' ', 'o', 'l', 'l', 'e', 'H']

    >>> str

    'Hello World!'

    

跳出循环

    1.break

    寻找100以内最大的平方数

    >>> for n in range(99, 0, -1):

            root = sqrt(n)

            if root == int(root):

                print n

                break

    81

    

    2.continue

    输出100以内能被14除尽的数

    >>> x = range(0, 100)

    >>> for i in x:

            if (i % 14 == 0):

                print i

                continue    

    0

    14

    28

    42

    56

    70

    84

    98

    >>>

    

    3. while True/break 习语

    若不用这个结构

    进入循环之前需要给 循环值 一个哑值((dummy value)未使用的值)。

    >>> word = 'Merisc'

>>> while word:

        word = raw_input('Please enter a word: ')

        print 'The word was ' + word

    Please enter a word: mrsj

    The word was mrsj

    Please enter a word: Merisc

    The word was Merisc

    Please enter a word:

    The word was

    >>>

    

    >>> while True:

            word = raw_input('Please enter a word: ')

            if not word:

                break

            print 'The word was: ' + word

    Please enter a word: Merisc

    The word was: Merisc

    Please enter a word: yoo

    The word was: yoo

    Please enter a word:

    >>>

    

循环中的else子句

    else对齐的地方不同,会有不同的结果:

    from math import sqrt

    for n in range(99, 81, -1):

        root = sqrt(n)

        if root == int(root):

            print n

            break

        else:

            print "Didn't find it!"

out:

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

    Didn't find it!

            

            

    from math import sqrt

    for n in range(99, 81, -1):

        root = sqrt(n)

        if root == int(root):

            print n

            break

    else:

        print "Didn't find it!"

out:

    Didn't find it!

    

    

列表推导式--轻量级循环

    列表推导式(list comprehension)是利用其它列表创建新的列表的一种方法。

    >>> [x*x for x in range(10) if x % 3 == 0]

    [0, 9, 36, 81]

    >>> [(x,y) for x in range(3) for y in range(3)]

    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

    >>> result = []

    >>> for x in range(3):

            for y in range(3):

                result.append((x,y))

    >>> result

    [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

    >>>

    

    可以和if子句联合使用,找到首字母相同的男孩和女孩

    >>> girls = ['Alice', 'Bernie', 'CLar']

    >>> boys = ['Chris', 'Anod', 'Bob']

    >>> [b + '+' + g for b in boys for g in girls if b[0] == g[0]]

    ['Chris+CLar', 'Anod+Alice', 'Bob+Bernie']

    

    优化:

    girls = ['Alice', 'Bernie', 'CLar']

    boys = ['Chris', 'Anod', 'Bob']

    letterGirls = {}

    for girl in girls:

        letterGirls.setdefault(girl[0], []).append(girl)

    print [b+'+'+g for b in boys for g in letterGirls[b[0]]]

    ['Chris+CLar', 'Anod+Alice', 'Bob+Bernie']

    

三人行:pass、del、exec

    1.什么都没发生 pass

    name = raw_input('Enter you name: ')

    if name == 'Merisc':

        print 'Welcom!!!!'

    elif name == 'Bob':

        # not finish...

        pass

    elif name == 'Bill Gates':

        print 'Access Denied!'

    else:

        pass

测试:

    Merisc

    welcome

    Bob

    

    Bill Gates

    Access Denied!

    

    注释和pass语句联合的替代方案是插入字符串。

    对于那些没有完成的函数和类来说这个方法尤其有用,因为它们会扮演文档字符串的角色。

    

    2.使用del删除

    python会删除那些不再使用的对象

    >>> Merisc = {'age':22, 'first name':'Merisc', 'last name':'Ma'}

    >>> mrsj = Merisc

    >>> Merisc

    {'last name': 'Ma', 'first name': 'Merisc', 'age': 22}

    >>> mrsj

    {'last name': 'Ma', 'first name': 'Merisc', 'age': 22}

    >>> Merisc = None

    >>> Merisc

    >>> mrsj

    {'last name': 'Ma', 'first name': 'Merisc', 'age': 22}

    >>> mrsj = None

    >>> mrsj

    >>>

    这时,字典就"漂”在内存中了,没有任何名字绑定到它上面。

    没有办法获取和使用它,所以python解释器直接删除了那个字典(垃圾收集)。

    法2:del

    >>> x = 1

    >>> x

    1

    >>> del x

    >>> x

    Traceback (most recent call last):

      File "<pyshell#220>", line 1, in <module>

        x

    NameError: name 'x' is not defined

    >>>

    

    >>> x = ["hello", "world"]

    >>> y = x

    >>> y[1]

    'world'

    >>> y[1] = "python"

    >>> x

    ['hello', 'python']

    >>> del x

    >>> x

    Traceback (most recent call last):

      File "<pyshell#229>", line 1, in <module>

        x

    NameError: name 'x' is not defined

    >>> y

    ['hello', 'python']

    >>>

    y还存在,因为删除的是名称,而不是列表本身(值)。

    python是没有办法删除值的。

    

    3.使用exec和eval执行和求值字符串

    exec

    >>> exec "print 'Hello, World!'"

    Hello, World!

    简单形式绝不是好事。

    很多情况下可以给它提供命名空间--可以放变量的地方。

    >>> from math import sqrt

    >>> exec "sqrt = 1"

    >>> sqrt(4)

    Traceback (most recent call last):

      File "<pyshell#237>", line 1, in <module>

        sqrt(4)

    TypeError: 'int' object is not callable

    >>> sqrt

    1

    >>>

    这里看上去好像sqrt被替换为1了。

    

    >>> from math import sqrt

    >>> scope = {}

    >>> exec 'sqrt = 1' in scope

    >>> sqrt(4)

    2.0

    >>> scope['sqrt']

    1

    >>>     可以看到,潜在的破坏性代码并不会覆盖sqrt函数,原来的函数能正常工作,而通过exec赋值的变量sqrt只在它的作用域内有效。

    >>> len(scope)

    2

    >>> scope.keys()

    ['__builtins__', 'sqrt']

    内建的_builtins_字典自动包含所有的内建函数和值。

    

    eval

    用于“求值”。    exec语句会执行一系列python语句,而eval会计算python表达式(以字符串形式书写),并且返回结果值,(exec语句并不返回任何对象,因为它本身就是语句)。

    >>> eval(raw_input("Enter an arithmetic expression: "))

    Enter an arithmetic expression: 6+18*2

    42

    >>>

    注意:eval(raw_input(...))事实上等同于input().

    在python3.0中,raw_input被命名为input。

    

    跟exec一样可以使用命名空间

    >>> scope = {}

    >>> scope['x'] = 2

    >>> scope['y'] = 3

    >>> eval('x*y', scope)

    6

    

    >>> scope = {}

    >>> exec 'x = 2' in scope

    >>> eval('x*x', scope)

    4

    

    

    

小结:

    1.打印。

        print,’,‘隔开多个值。

        如果’,‘结尾,后面的print在同一行继续打印。

    2.导入。

        import

        import ... as ...

    3.赋值。

        序列解包和链式赋值功能。

    4.块。

        通过缩排使语句成组的方法。

    5.条件。

        if/elif/else

    6.断言。

        肯定某事为真,也可在后面跟上这么认为的原因。

        若果表达式为假,让程序崩溃(产生异常)

    7.循环。

        尽量for代替while。

        break   continue

    8.列表推导式。

        旧列表产生新列表

    9.pass、del、exec、eval。

   
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: