设为首页 收藏本站
查看: 848|回复: 0

[经验分享] python学习(第五章)

[复制链接]

尚未签到

发表于 2017-4-28 10:18:56 | 显示全部楼层 |阅读模式

条件、循环和其他语句



print和import的更多信息



使用逗号输出



  •   打印多个表达式,只要将它们用逗号隔开:


    >>>print 'Age:', 42
    Age: 42
  •   可以看到每个参数之间都插入了一个空格符




把某事件作为另一事件导入



  •   从模块导入函数的时候,可以使用:


    import somemodule
    or
    from somemodule import somefunction
    or
    from somemodule import somefunction, anotherfunction, yetanotherfunction
    or
    from somemodule import *
  •   如果两个模块有相同的函数,需按如下方式使用函数:


    modulename.functionname
  •   可以在语句末尾增加一个as子句,在该子句后给出名字,或为整个模块提供别名:


    >>>import math as foobar
    >>>foobar.sqrt(4)
    2.0
    >>>from math import sqrt as foobar
    >>>foobar(4)
    2.0


赋值



序列解包



  •   多个赋值操作可以同时进行:


    >>>x, y, z = 1, 2, 3
    >>>print x, y, z
    1, 2, 3
  •   用它交换两个(或更多个)变量也没有问题:


    >>> x, y = 1, 2
    >>> x, y = y, x
    >>> print x, y
    2 1
  •   这里所做的事情叫序列解包或可选代解包--将多个值的序列解开,然后放到变量的序列中。


    >>>values = 1, 2, 3
    >>>values
    (1, 2, 3)
    >>>x, y , z = values
    >>>x
    1
  •   允许函数返回一个以上的值并打包成元组,然后通过一个赋值语句很容易进行访问。所解包的序列中的元素数量必须和放置在赋值符号=左边的变量数量完全一致,否则python会在赋值时,引发异常。




链式赋值



  •   链式赋值是将同一个值赋给多个变量的捷径。


    >>>x = y = z


增量赋值


+=, -=, *=, /=, %=


语句块: 缩排的乐趣



  • 语句块是条件为真时执行或执行多次的一组语句。在代码前放置空格来缩进语句即可创建语句块。
  • 在python中,冒号(:)用来标识语句块的开始,块中的每一个语句都是缩进的(缩进量相同)。当回退到和已经闭合的块一样的缩进量时,就表示前块已经结束了。


条件和条件语句



这就是布尔变量的作用



  •   下面的在作为布尔表达式的时候,会被解释器看作假(false):


    False None 0 "" () [] {}

      其他的一切都被解释为真,包括特殊值True。


  •   在python中,"标准"的布尔值为False和True


  •   bool函数可以用来转换其他值


    >>>bool('I think, therefore I am')
    True
    >>>bool(42)
    True
    >>>bool(0)
    False
  •   因为所有值都可以用作布尔值,所以几乎不需要对它们进行显示转换




条件执行和if语句


name = raw_input('What is your name? ')
if name.endswith('Gumby'):
print 'Hello, Mr. Gumby'


else子句


name = raw_input('What is your name? ')
if name.endswith('Gumby'):
print 'Hello, Mr. Gumby'
else:
print 'Hello, stranger'


elif语句



  •   elif是"else if"的缩写,也是if和else语句的联合使用--也就是具有条件的else子句

      num = input('Enter a number: ')if num > 0:print 'The number is positive'elif num < 0:print 'The number is negtive'else:print 'The number is zero'


嵌套代码块



更复杂的条件



  •   比较运算符


    x == y & x等于y \\
    x < y & x小于y \\
    x > y & x大于y \\
    x >= y & x大于等于y \\
    x <= y & x小于等于y \\
    x != y & x不等于y \\
    x is y & x和y是同一个对象 \\
    x is not y & x和y是不同对象 \\
    x in y & x是y容器的成员 \\
    x not in y & x不是y容器的成员 \\
  •   在python中比较运算和复制运算一样是可以连接的--几个运算符可以连接在一起使用,比如: 0 < age < 100


  •   is运算符是判断同一性而不是相等性的


  •   字符串可以按照字母顺序排列进行比较


  •   布尔运算符(通常被称为逻辑运算符): and, or, not



断言



  •   如果需要确保程序中的某一条件一定为真才让程序正常工作的话,assert语句就有用了,它可以在程序中置入检查点


    >>> age = -1
    >>> assert 0 < age and age < 100
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AssertionError


循环



while循环


x = 1
while x <= 100:
print x
x += 1
name = ''
while not name or name.isspace():
name = raw_input('Please enter your name: ')
print 'Hello, %s!' % name


for循环



  •   range函数一次创建整个序列


    >>>range(10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>>range(0, 10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>>range(1, 10)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]


循环遍历字典元素



  •   一个简单的for语句就能循环字典的所有键,就像处理序列一样:

      d = {'x': 1, 'y': 2, 'z': 3}for key in d:print key, 'corresponds to', d[key]

  •   d.items方法会将键-值对作为元组返回,for循环的一大好处就是可以在循环中使用序列解包:

      d = {'x': 1, 'y': 2, 'z': 3}for key, value in d.items():print key, 'corresponds to', value

  •   [注: 字典元素的顺序是没有定义的。换句话说,迭代的时候,字典中的键和值都能保证被处理,但是处理顺序不确定。如果顺序很重要的话,可以将键值保存爱单独的列表中]。




一些迭代工具



并行迭代



  •   程序可以同时得带两个序列。

      names = ['anne', 'beth', 'george', 'damon']ages = [12, 45, 32, 102]for i in range(len(names)):print names, 'is', ages, 'years old'

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

      names = ['anme', 'beth', 'george', 'damon']ages = [12, 45, 32, 102]for name, age in zip(names, ages):print name, 'is', age, 'years old'

  •   关于zip函数很重要的一点是zip可以应付不等长的序列: 当最短的序列用完的时候就会停止:

      print zip(range(5), xrange(100000000))print zip(range(5), xrange(4))
      [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)][(0, 0), (1, 1), (2, 2), (3, 3)]



编号迭代



  •   版本1:


    for string in strings:
    if 'xxx' in string:
    index = strings.index(string)
    strings[index] = '[censored]'
  •   版本2:


    index = 0
    for string in strings:
    if 'xxx' in string:
    strings[index] = '[censored]'
    index += 1
  •   版本3(使用内建的enumerate函数):


    for index, string in enumerate(strings):
    if 'xxx' in string:
    strings[index] = '[censored]'


翻转和排序迭代



  •   reversed和sorted: 它们同列表的reverse和sort方法类似,但作用于任何序列或可迭代对象上,不是原地修改对象,而是返回翻转或排序后的版本:


    >>>sorted([4, 3, 6, 8, 3])
    [3, 3, 4, 6, 8]
    >>>sorted('Hello, world!')
    [' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'o', 'o', 'r', 'w']
    >>> list(reversed('Hello world'))
    ['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'H']
    >>> ''.join(reversed('Hello world'))
    'dlrow olleH'


跳出循环



break



  •   结束(跳出)循环可以使用break语句。

      from math import sqrtfor n in range(99, 0, -1):root = sqrt(n)if (root == int(root)):print nbreak


continue



  • continue会让当前的迭代结束,"跳"到下一轮循环的开始。其最基本的意思是"跳过剩余的循环体,但是不结束循环"


whlie True/break习语



  •   如果需要当用户在提示符下输入单词时做一些事情,并且在用户不输入单词后结束循环。

      while True:word = raw_input('Please enter a word: ')if not word:breakprint 'The word was', word


循环中else语句



  •   在循环中增加一个else子句--它仅在没有调用break时执行。

      from math import sqrtfor n in range(99, 81, -1):root = sqrt(n)if root == int(root):print nbreakelse:print 'Didn\'t find it!'


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



  •   列表推导式是利用其他列表创建新列表的一种方法。


    >>> [x * x for x in range(10) if x % 3 == 0]
    [0, 9, 36, 81]
    >>> [x * x for x in range(10)]
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    >>> [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)]


三人行



pass



  • pass函数什么都不做,而可以在代码中做占位符使用。


使用del删除



  •   使用del不仅益处一个对象的引用,也会移除那么名字本身。


    >>> x = 1
    >>> del x
    >>> x
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'x' is not defined
  •   del删除的只是名称,而不是列表本身。


    >>> x = ['Hello', 'world']
    >>> y = x
    >>> del x
    >>> x
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'x' is not defined
    >>> y
    ['Hello', 'world']


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



  • [注: 本节中,会学到如何执行存储在字符串中的python代码]


exec



  •   执行一个字符串的语句是exec:


    >>>exec "print 'Hello, world'"
    Hello, world


eval



  •   eval是类似于exec的内建函数。exec语句会执行一系列python语句,而eval会计算python表达式,并返回结果值。


    >>>eval(raw_input('Enter an arithmetic expression: ')
    Enter an arithmetic expression: 6 +18 * 2
    42


新函数


函数 & 描述 \\
chr(n) & 当传入序号n时,返回n所代表的包含一个字符串(0 <= n < 256) \\
eval(source[, globals[, locals]]) & 将字符串作为表达式计算,并且返回值 \\
enumerate(seq) & 产生用于迭代的(索引, 值)对 \\
ord(c) & 返回单字符字符串的int值 \\
range([start, ][, key][, reverse]) & 创建整数的列表 \\
reversed(seq) & 产生seq中值的反向版本,用于迭代 \\
sorted(seq[, cmp][, key][, reverse]) & 返回seq中值排序后的列表 \\
xrange([start,] stop[, step]) & 创建xrange对象用于迭代 \\
zip(seq1, _seq2,...) & 创建用于并行迭代的新序列 \\




条件、循环和其他语句



print和import的更多信息



使用逗号输出



  •   打印多个表达式,只要将它们用逗号隔开:


    >>>print 'Age:', 42
    Age: 42
  •   可以看到每个参数之间都插入了一个空格符




把某事件作为另一事件导入



  •   从模块导入函数的时候,可以使用:


    import somemodule
    or
    from somemodule import somefunction
    or
    from somemodule import somefunction, anotherfunction, yetanotherfunction
    or
    from somemodule import *
  •   如果两个模块有相同的函数,需按如下方式使用函数:


    modulename.functionname
  •   可以在语句末尾增加一个as子句,在该子句后给出名字,或为整个模块提供别名:


    >>>import math as foobar
    >>>foobar.sqrt(4)
    2.0
    >>>from math import sqrt as foobar
    >>>foobar(4)
    2.0


赋值



序列解包



  •   多个赋值操作可以同时进行:


    >>>x, y, z = 1, 2, 3
    >>>print x, y, z
    1, 2, 3
  •   用它交换两个(或更多个)变量也没有问题:


    >>> x, y = 1, 2
    >>> x, y = y, x
    >>> print x, y
    2 1
  •   这里所做的事情叫序列解包或可选代解包--将多个值的序列解开,然后放到变量的序列中。


    >>>values = 1, 2, 3
    >>>values
    (1, 2, 3)
    >>>x, y , z = values
    >>>x
    1
  •   允许函数返回一个以上的值并打包成元组,然后通过一个赋值语句很容易进行访问。所解包的序列中的元素数量必须和放置在赋值符号=左边的变量数量完全一致,否则python会在赋值时,引发异常。




链式赋值



  •   链式赋值是将同一个值赋给多个变量的捷径。


    >>>x = y = z


增量赋值


+=, -=, *=, /=, %=


语句块: 缩排的乐趣



  • 语句块是条件为真时执行或执行多次的一组语句。在代码前放置空格来缩进语句即可创建语句块。
  • 在python中,冒号(:)用来标识语句块的开始,块中的每一个语句都是缩进的(缩进量相同)。当回退到和已经闭合的块一样的缩进量时,就表示前块已经结束了。


条件和条件语句



这就是布尔变量的作用



  •   下面的在作为布尔表达式的时候,会被解释器看作假(false):


    False None 0 "" () [] {}

      其他的一切都被解释为真,包括特殊值True。


  •   在python中,"标准"的布尔值为False和True


  •   bool函数可以用来转换其他值


    >>>bool('I think, therefore I am')
    True
    >>>bool(42)
    True
    >>>bool(0)
    False
  •   因为所有值都可以用作布尔值,所以几乎不需要对它们进行显示转换




条件执行和if语句


name = raw_input('What is your name? ')
if name.endswith('Gumby'):
print 'Hello, Mr. Gumby'


else子句


name = raw_input('What is your name? ')
if name.endswith('Gumby'):
print 'Hello, Mr. Gumby'
else:
print 'Hello, stranger'


elif语句



  •   elif是"else if"的缩写,也是if和else语句的联合使用--也就是具有条件的else子句

      num = input('Enter a number: ')if num > 0:print 'The number is positive'elif num < 0:print 'The number is negtive'else:print 'The number is zero'


嵌套代码块



更复杂的条件



  •   比较运算符


    x == y & x等于y \\
    x < y & x小于y \\
    x > y & x大于y \\
    x >= y & x大于等于y \\
    x <= y & x小于等于y \\
    x != y & x不等于y \\
    x is y & x和y是同一个对象 \\
    x is not y & x和y是不同对象 \\
    x in y & x是y容器的成员 \\
    x not in y & x不是y容器的成员 \\
  •   在python中比较运算和复制运算一样是可以连接的--几个运算符可以连接在一起使用,比如: 0 < age < 100


  •   is运算符是判断同一性而不是相等性的


  •   字符串可以按照字母顺序排列进行比较


  •   布尔运算符(通常被称为逻辑运算符): and, or, not



断言



  •   如果需要确保程序中的某一条件一定为真才让程序正常工作的话,assert语句就有用了,它可以在程序中置入检查点


    >>> age = -1
    >>> assert 0 < age and age < 100
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    AssertionError


循环



while循环


x = 1
while x <= 100:
print x
x += 1
name = ''
while not name or name.isspace():
name = raw_input('Please enter your name: ')
print 'Hello, %s!' % name


for循环



  •   range函数一次创建整个序列


    >>>range(10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>>range(0, 10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    >>>range(1, 10)
    [1, 2, 3, 4, 5, 6, 7, 8, 9]


循环遍历字典元素



  •   一个简单的for语句就能循环字典的所有键,就像处理序列一样:

      d = {'x': 1, 'y': 2, 'z': 3}for key in d:print key, 'corresponds to', d[key]

  •   d.items方法会将键-值对作为元组返回,for循环的一大好处就是可以在循环中使用序列解包:

      d = {'x': 1, 'y': 2, 'z': 3}for key, value in d.items():print key, 'corresponds to', value

  •   [注: 字典元素的顺序是没有定义的。换句话说,迭代的时候,字典中的键和值都能保证被处理,但是处理顺序不确定。如果顺序很重要的话,可以将键值保存爱单独的列表中]。




一些迭代工具



并行迭代



  •   程序可以同时得带两个序列。

      names = ['anne', 'beth', 'george', 'damon']ages = [12, 45, 32, 102]for i in range(len(names)):print names, 'is', ages, 'years old'

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

      names = ['anme', 'beth', 'george', 'damon']ages = [12, 45, 32, 102]for name, age in zip(names, ages):print name, 'is', age, 'years old'

  •   关于zip函数很重要的一点是zip可以应付不等长的序列: 当最短的序列用完的时候就会停止:

      print zip(range(5), xrange(100000000))print zip(range(5), xrange(4))
      [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)][(0, 0), (1, 1), (2, 2), (3, 3)]



编号迭代



  •   版本1:


    for string in strings:
    if 'xxx' in string:
    index = strings.index(string)
    strings[index] = '[censored]'
  •   版本2:


    index = 0
    for string in strings:
    if 'xxx' in string:
    strings[index] = '[censored]'
    index += 1
  •   版本3(使用内建的enumerate函数):


    for index, string in enumerate(strings):
    if 'xxx' in string:
    strings[index] = '[censored]'


翻转和排序迭代



  •   reversed和sorted: 它们同列表的reverse和sort方法类似,但作用于任何序列或可迭代对象上,不是原地修改对象,而是返回翻转或排序后的版本:


    >>>sorted([4, 3, 6, 8, 3])
    [3, 3, 4, 6, 8]
    >>>sorted('Hello, world!')
    [' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'o', 'o', 'r', 'w']
    >>> list(reversed('Hello world'))
    ['d', 'l', 'r', 'o', 'w', ' ', 'o', 'l', 'l', 'e', 'H']
    >>> ''.join(reversed('Hello world'))
    'dlrow olleH'


跳出循环



break



  •   结束(跳出)循环可以使用break语句。

      from math import sqrtfor n in range(99, 0, -1):root = sqrt(n)if (root == int(root)):print nbreak


continue



  • continue会让当前的迭代结束,"跳"到下一轮循环的开始。其最基本的意思是"跳过剩余的循环体,但是不结束循环"


whlie True/break习语



  •   如果需要当用户在提示符下输入单词时做一些事情,并且在用户不输入单词后结束循环。

      while True:word = raw_input('Please enter a word: ')if not word:breakprint 'The word was', word


循环中else语句



  •   在循环中增加一个else子句--它仅在没有调用break时执行。

      from math import sqrtfor n in range(99, 81, -1):root = sqrt(n)if root == int(root):print nbreakelse:print 'Didn\'t find it!'


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



  •   列表推导式是利用其他列表创建新列表的一种方法。


    >>> [x * x for x in range(10) if x % 3 == 0]
    [0, 9, 36, 81]
    >>> [x * x for x in range(10)]
    [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    >>> [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)]


三人行



pass



  • pass函数什么都不做,而可以在代码中做占位符使用。


使用del删除



  •   使用del不仅益处一个对象的引用,也会移除那么名字本身。


    >>> x = 1
    >>> del x
    >>> x
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'x' is not defined
  •   del删除的只是名称,而不是列表本身。


    >>> x = ['Hello', 'world']
    >>> y = x
    >>> del x
    >>> x
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'x' is not defined
    >>> y
    ['Hello', 'world']


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



  • [注: 本节中,会学到如何执行存储在字符串中的python代码]


exec



  •   执行一个字符串的语句是exec:


    >>>exec "print 'Hello, world'"
    Hello, world


eval



  •   eval是类似于exec的内建函数。exec语句会执行一系列python语句,而eval会计算python表达式,并返回结果值。


    >>>eval(raw_input('Enter an arithmetic expression: ')
    Enter an arithmetic expression: 6 +18 * 2
    42


新函数


函数 & 描述 \\
chr(n) & 当传入序号n时,返回n所代表的包含一个字符串(0 <= n < 256) \\
eval(source[, globals[, locals]]) & 将字符串作为表达式计算,并且返回值 \\
enumerate(seq) & 产生用于迭代的(索引, 值)对 \\
ord(c) & 返回单字符字符串的int值 \\
range([start, ][, key][, reverse]) & 创建整数的列表 \\
reversed(seq) & 产生seq中值的反向版本,用于迭代 \\
sorted(seq[, cmp][, key][, reverse]) & 返回seq中值排序后的列表 \\
xrange([start,] stop[, step]) & 创建xrange对象用于迭代 \\
zip(seq1, _seq2,...) & 创建用于并行迭代的新序列 \\

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-370278-1-1.html 上篇帖子: Python进阶 函数式编程 下篇帖子: 每天换一个新桌面的python
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表