您的位置:首页 > 编程语言 > Python开发

python学习记录(五)

2016-03-02 18:13 531 查看
1、print和import  P83

  import ... as ...

2、赋值

3、语句块
  语句块是在条件为真if时执行或者执行多次for的一组语句。在代码前放置空格来缩进语句即可创建语句块。
  使用冒号: 表示语句块的开始

  假: False, None, 0, "", (), []
  注意: [] != False   []:空的字典

      () != "" ():空的元组和序列

  name = raw_input('what is your name?')
  if name.endswith('Yilia'):
    print 'hello %s' %name
  else:
    print 'input error'

4、比较运算符
  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容器的成员
  0<x<y # 合法的

  >>> x = [1,2,3]
  >>> z = [1,2,3]
  >>> y = x
  >>> x == y
  True
  >>> x == z
  True
  >>> y == z
  True
  >>> x is y # x和y是同一个对象
  True
  >>> x is z # x和z不是同一个对象
  False
  >>> y is x
  True
  >>> y is z
  False

5、断言
  错误出现时程序直接崩溃
  要求某些条件必须为真时,使用断言。关键字:assert

  num = input('enter a number:') # 注意这里使用数字,必须使用input
  assert -10 < num < 10

6、while循环和for循环
  range函数
    >>> range(0,10)
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

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

  遍历字典
    >>> x = {'name':'yilia', 'age':'16', 'class':['math','english','music']}

    >>> for key in x:
    ...    print key, 'corresponds to ', x[key]
    ...
    age corresponds to 16
    name corresponds to yilia
    class corresponds to ['math', 'english', 'music']

    >>> for key,value in x.items():
    ...    print key, ' corresponds to ', value
    ...
    age corresponds to 16
    name corresponds to yilia
    class corresponds to ['math', 'english', 'music']

  跳出循环:
    break
    continue

简单例子:
  girls = ['alice', 'birnice', 'clacrice']
  boys = ['chris', 'arnold', '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 + clacrice', 'arnold + alice', 'bob + birnice']

7、三人行 pass del exec

  pass: 用来代替空代码块
  del : 删除不再使用的对象
    >>> x = 9
    >>> x = None # 移除对象引用
    >>> x
    >>> x = 9
    >>> del x # 不仅移除对象的引用,也移除对象名称,而不会删除本身值
    >>> x
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'x' is not defined

    >>> x = 9
    >>> y = x
    >>> y
    9
    >>> x
    9
    >>> del x
    >>> x # x不存在
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'x' is not defined
    >>> y # y的值仍然存在
    9

  exec: 执行字符串中的python代码
    >>> exec "print 'hello,world'"
    hello,world

  eval: 计算Python表达式(以字符串形式书写),并且返回结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: