python基础教程总结4—基本语句

一、print 和 import 的更多信息

   print 打印多个表达式也是可行的,只要将它们用逗号隔开就好:

  1. >>> print('Age:' , 42)  
  2. Age: 42  

   可以看到,每个参数之间都插入了一个空格符。如果想要同时输出文本和变量值,却又不希望使用字符串格式化的话,那这个特性就非常有用了。

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

  1. import  somemodule  

        或者

  1. from  somemodule import  somefunction  

        或者

  1. from somemodule import somefunction, anotherfunction, yetanotherfunction 

        或者

  1. from somemodule import *  

 

        只有确定自己想要从给定的模块导入所有功能时,才应该使用最后一个版本。但是如果两个模块都有 open 函数,那又该怎么办?只需使用第一种方式导入,然后像下面这样使用函数:

  1. module1.open(...)  
  2. module2.open(...)  

       还有另外的选择:可以在语句末尾增加一个 as 子句,在该子句后给出名字,或为整个模块提供别名:

  1. >>> import math as foobar  
  2. >>> foobar.sqrt(4)  
  3. 2.0  

         也可以为函数提供别名:

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

         对于open函数,可以像下面这样使用:

  1. from module1 import open as open1  
  2. from module2 import open as open2  

 

二、赋值

        1. 序列解包

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

 
  1. >>> x, y, z = 1, 2, 3  
  2. >>> print(x, y, z)  
  3. 3  

        用它交换两个(或更多个)变量:

  1. >>> x, y = y, x  
  2. >>> print(x, y, z)  
  3. 3  

        事实上,这里所做的事情叫做序列解包(sequence unpacking)或可选代解包——将多个值的序列解开,然后放到变量的序列中。当函数或者方法返回元组(或者其他序列或可选迭代对象)时,这个特性尤其有用。它允许函数返回一个以上的值并且打包成元组,然后通过一个赋值语句很容易进行访问。

 
  1. >>> scoundrel = {'name':'Robin', 'girlfriend':'Marion'}  
  2. >>> key, value = scoundrel.popitem()  
  3. >>> key  
  4. 'name'  
  5. >>> value  
  6. 'Robin'  

        所解包的序列中元素数量必须和放置在赋值符号 = 左边的变量数量完全一致,否则 Python 会在赋值时引发异常:

  1. >>> x, y, z = 1, 2  
  2. Traceback (most recent call last):  
  3.   File "<stdin>", line 1, in <module>  
  4. ValueError: need more than 2 values to unpack  
  5. >>> x, y, z = 1, 2, 3, 4  
  6. Traceback (most recent call last):  
  7.   File "<stdin>", line 1, in <module>  
  8. ValueError: too many values to unpack (expected 3)  

        Python 3.0中有另外一个解包的特性:可以像在函数的参数列表中一样使用星号运算符。例如,a, b, *rest = [1, 2, 3, 4]最终会在 a 和 b 都被赋值之后将所有其他的参数都是收集到 rest 中。

 

2. 链式赋值

        链式赋值(chained assignment)是将同一个赋值给多个变量的捷径。   x = y = somefunction()   

 

3. 增量赋值

        将表达式运算符(本例中是 + -) 放置在赋值运算符 = 的左边,写成 x +=1。这种写法叫做增量赋值。

 
  1. >>> x = 2  
  2. >>> x += 1  
  3. >>> x *= 2  
  4. >>> x  
  5. 6  

        对于其他数据类型也适用:

  1. >>> fnord = 'foo'  
  2. >>> fnord += 'bar'  
  3. >>> fnord *= 2  
  4. >>> fnord  
  5. 'foobarfoobar'  

 

三、语句块

        语句块是在条件为真(条件语句)时执行或者执行多次(循环语句)的一组语句。在代码前放置空格来缩进语句即可创建语句块。

        在Python中,冒号(:)用来标识语句块的开始,块中的每一个语句都是缩进的(缩进量相同)。当回退到和已经闭合的块一样的缩进量时,就表示当前块已经结束了。

 

四、条件和条件语句

 1. 布尔变量

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

                 False     None     0     “”     ()      []     {}

        换句话说,也就是标准值 False 和 None、所有类型的数字 0(包括浮点型、长整型和其他类型)、空序列(比如空字符串、元组和列表)以及空的字典都为假。其他的一切都被解释为真,包括特殊值 True。

        布尔值True 和 False 属于布尔类型,bool函数可以用来(和list、str以及tuple一样)转换其他值。 

  1. >>> bool('I think, therefore I am')  
  2. True  
  3. >>> bool(42)  
  4. True  
  5. >>> bool('')  
  6. False  
  7. >>> bool(0)  
  8. False  

        因为所有值都可以用作布尔值,所以几乎不需要对他们进行显示转换(可以说Python会自动转换这些值)。

 

2. 条件执行(if / else / elif)

 
  1. num = input('Enter a number: ')  
  2. if num > 0:  
  3.     print('The number is positive')  
  4. elif num < 0:  
  5.     print('The number is negative')  
  6. else:  
  7.     print('The number is zero'

3. 嵌套代码块

  1. name = raw_input('What is your name? ')  
  2. if name.endswith('Gumby'):  
  3.     if name.startswith('Mr. '):  
  4.         print('Hello, Mr. Gumby')  
  5.     elif name.startswith('Mrs. '):  
  6.         print('Hello, Mrs. Gumby')  
  7.     else:  
  8.         print('Hello, Gumby')  
  9. else:  
  10.     print('Hello, stranger')  

 

 4. 更复杂的条件

 4.1 比较运算符

 

表达式描述
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 3.0中,比较不兼容类型的对象已经不再可行。

 

           在Python中比较运算和赋值运算一样是可以连接的——几个运算符可以连在一起使用,比如:0 < age < 100。

 4.2 相等运算符

           如果想要知道两个东西是否相等,应该使用相等运算符,即两个等号 == :

  1. >>> "foo"=="foo"  
  2. True  
  3. >>> "foo"=="bar"  
  4. False  

 4.3 is:同一性运算符

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

  1. >>> x = y = [1, 2, 3]  
  2. >>> z = [1, 2, 3]  
  3. >>> x == y  
  4. True  
  5. >>> x == z  
  6. True  
  7. >>> x is y  
  8. True  
  9. >>> x is z  
  10. False  

           使用 == 运算符来判定两个对象是否相等,使用 is 判定两者是否等同(同一个对象)。

 

 4.4 in:成员资格运算符

 4.5 字符串和序列比较

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

 
  1. >>> "alpha" < "beta"  
  2. True  

           其他的序列也可以用同样的方式进行比较,不过比较的不是字符而是元素的其他类型。

 
  1. >>> [1, 2] < [2, 1]  
  2. True  

     

4.6 布尔运算符

           and , or 和 not 运算符就是所谓的布尔运算符。

 

 

5. 断言

  1. >>> age = 10  
  2. >>> assert 0 < age < 100  
  3. >>> age = -1  
  4. >>> assert 0 < age < 100  
  5. Traceback (most recent call last):  
  6.   File "<stdin>", line 1, in <module>  
  7. AssertionError  

      如果需要确保程序中的某个条件一定为真才能让程序正常工作的话,assert语句就有用了,它可以在程序中置入检查点。条件后可以添加字符串,用来解释断言:

 
    1. >>> age = -1  
    2. >>> assert 0 < age < 100, 'The age must be realistic'  
    3. Traceback (most recent call last):  
    4.   File "<stdin>", line 1, in <module>  
    5. AssertionError: The age must be realistic  

 

五、循环

5.1 while 循环

  1. >>> while x <= 100:  
  2. ...     print(x)  
  3. ...     x += 1  
  4. ...  

 

5.2 for 循环

  1. >>> words = ['this', 'is', 'an', 'ex', 'parrot']  
  2. >>> for word in words:  
  3. ...     print(word)  
  4. ...  

      因为迭代(循环的另外一种说法)某范围的数字是很常见的,所以有个内建的范围函数 range 供使用:

  1. >>> for number in range(1, 101):  
  2. ...     print(number)  
  3. ...  

 

5.3 循环遍历字典元素

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

  1. >>> d = {'x':1, 'y':2, 'z':3}  
  2. >>> for key in d:  
  3. ...     print(key, 'corresponds to', d[key])  
  4. ...  
  5. z corresponds to 3  
  6. x corresponds to 1  
  7. y corresponds to 2  

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

  1. >>> for key, value in d.items():  
  2. ...     print(key, 'corresponds to', d[key])  
  3. ...  

        字典元素的顺序通常是没有定义的。换句话说,迭代的时候,字典中的键和值都能保证被处理,但是处理顺序不确定。

 

 5.4 一些迭代工具

 a。并行迭代

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

  1. >>> names = ['anne', 'beth', 'george', 'damon']  
  2. >>> ages = [12, 45, 32, 102]  
  3. >>> for i in range(len(names)):  
  4. ...     print(names[i], 'is', ages[i], 'years old')  
  5. ...  

               而内建的 zip 函数可以用来进行并行迭代,可以把两个序列"压缩"在一起。     zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表。

  1. >>> for name, age in zip(names, ages):  
  2. ...     print(name, 'is', age, 'years old')  
  3. ...  

               zip 函数也可以作用于任意多的序列。关于它很重要的一点是 zip 可以应付不等长的序列:当最短的序列“用完”的时候就会停止。

 

b. 编号迭代

               enumerate 函数可以在提供索引的地方迭代 索引 - 值 对。        enumerate 函数用于遍历序列中的元素以及它们的下标:

>>> for i,j in enumerate(('a','b','c')):
 print i,j

0 a
1 b
2 c
>>> for i,j in enumerate([1,2,3]):
 print i,j

0 1
1 2
2 3
>>> for i,j in enumerate({'a':1,'b':2}):
 print i,j

0 a
1 b

>>> for i,j in enumerate('abc'):
 print i,j

0 a
1 b
2 c

  

c。翻转和排序迭代

     reversed 和 sorted 作用于任何序列或可迭代对象上,不是原地修改对象,而是返回翻转或排序后的版本: 虽然 sorted 方法返回列表,reversed 方法却返回一个更加不可思议的迭代对象。

  1. >>> sorted('Hello, world!')  
  2. [' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']  
  3. >>> list(reversed('Hello, world!'))  
  4. ['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']  

   

  注: sort   sorted()   reverse()   reversed()的区别      

  1). sort()是可变对象(字典、列表)的方法,无参数,无返回值,sort()会改变可变对象,因此无需返回值。  

     sort()方法是可变对象独有的方法或者属性,而作为不可变对象如元组、字符串是不具有这些方法的,如果调用将会返回一个异常。

        >>> a=[5,4,3,2,1]
        >>> a.sort()
        >>> 
        >>> a
        [1, 2, 3, 4, 5]

    sorted()是python的内置函数,并不是可变对象(列表、字典)的特有方法,

    sorted()函数需要一个参数(参数可以是列表、字典、元组、字符串),无论传递什么参数,都将返回一个以列表为容器的返回值,如果是字典将返回键的列表。

        >>> mystring="54321"
        >>> mytuple=(5,4,3,2,1)
        >>> mylist=[5,4,3,2,1]
        >>> sorted(mystring)
        ['1', '2', '3', '4', '5']
        >>> sorted(mytuple)
        [1, 2, 3, 4, 5]
        >>> sorted(mylist)
        [1, 2, 3, 4, 5]

    reverse()与sort的使用方式一样,而reversed()与sorted()的使用方式相同

        >>> mylist=[5,4,3,2,1]
        >>> mylist.reverse()
        >>> mylist
        [1, 2, 3, 4, 5]
        >>> mylist=[5,4,3,2,1]
        >>> for i in reversed(mylist):
        ...     print i,
        ... 
        1 2 3 4 5

 

5.5 跳出循环

a。break

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

b。continue

              continue 会让当前的迭代结束,“跳”到下一轮循环的开始

c。while True / break 习语

 
  1. >>> while True:  
  2. ...     word = input('Please enter a word: ')  
  3. ...     if not word: break  
  4. ...     print('The word was ' + word)  
  5. ...  

      while True 的部分实现了一个永远不会自己停止的循环。但是在循环内部的 if 语句中加入条件可以的,在条件满足时调用 break 语句。

 

5.6 循环中的 else 子句

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

 
  1. >>> from math import sqrt  
  2. >>> for n in range(99, 81, -1):  
  3. ...     root = sqrt(n)  
  4. ...     if root == int(root):  
  5. ...             print(n)  
  6. ...             break  
  7. ... else:  
  8. ...     print("Didn't find it")  
  9. ...  
  10. Didn't find it  

 

六、列表推导式

      列表推导式(list comprehension)是利用其它列表创建新列表的一种方法。它的工作方式类似于 for 循环:

  1. >>> [x*x for x in range(10)]  
  2. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]  

        可以增加一个if部分添加到列表推导式: 

  1. >>> [x*x for x in range(10) if x % 3 == 0]  
  2. [0, 9, 36, 81]  

         也可以增加更多 for 语句的部分:

  1. >>> [(x, y) for x in range(3) for y in range(3)]  
  2. [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]  

         也可以和if子句联合使用,像以前一样:

 
  1. >>> girls = ['alice', 'bernice', 'clarice']  
  2. >>> boys = ['chris', 'arnold', 'bob']  
  3. >>> [b + '+' + g for b in boys for g in girls if b[0]==g[0] ]  
  4. ['chris+clarice', 'arnold+alice', 'bob+bernice']  

 

 


七、pass、del和exec

 1. 什么都没发生

        有的时候,程序什么事情都不用做。这种情况不多,但是一旦出现,就应该让 pass 语句出马。

2. 使用 del 删除

        使用 del 语句,它不仅会移除一个对象的引用,也会移除这个名字本身。

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

 a。exec

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

 
  1. >>> exec('print("Hello, world!")')  
  2. Hello, world!  

        exec 语句最有用的地方在于可以动态地创建代码字符串。

 

b。eval

      evel(用于“求值”)是类似于 exec 的内建函数。exec语句会执行一系列 Python 语句,而eval 会计算 Python 表达式(以字符串形式书写),并且返回结果值。

 
    1. >>> eval(input("Enter an arithmetic expression: "))  
    2. Enter an arithmetic expression: 6 + 18 * 2  
    3. 42  

 

posted @ 2015-07-14 18:27  zxqstrong  阅读(294)  评论(0编辑  收藏  举报