Python程序结构与控制流

evernote原文链接:https://app.yinxiang.com/shard/s7/sh/05b93ac4-1420-4506-aafa-d12d7c080d63/292e3b9b84d6c775

(有些图片无法显示,请点击链接查看笔记原文)

#!/usr/bin/env python

# -*- encoding: utf-8 -*-

'''
Created on 2015年1月27日

@author : cuckoocs
'''
import sys

'''
笔记1:
使用 if 控制可以定义不同形式下的方法,或 import不同模块

笔记2:
使用 break 可以跳出循环,continue 可以跳到下次循环,Python 没有 goto 语句

笔记3:
使用raise 可以抛出异常
raise Exception('message')
使用try...except...可以获取截住异常
try:
    ...
except (IOError, TypeError) as e:
    ...
except Exception as ex:
    ...
finally:
    ... #不管正常还是异常都会执行finally 中的代码
else:
    ... #只有当正常执行才会执行 else 里面的代码

笔记4:
Python内置异常


笔记5:
使用 with 语句支持内容上下文管理
可以通过覆盖__enter__, 和__exit__两个内置方法定义一个可上下文管理的类

笔记6:
使用 assert 可以用做调试判断,
eg: assert False, 'assert is true'
在最优模式(-O)下运行时,asster 语句和 if __debug__ 语句都将被省略

'''

class DeviceError(Exception):
   
def __init__(self, code=100, message=None):
        self.code = code
        self.msg = message

debug =
False

if debug:
   
def func():
       
print 'is debug'
else:
   
def func():
       
print 'is not debug'

def tfor():
    li = [(
1,2,3), (3,4,5), (8,4,5)]
   
for x,y,z in li:
       
print x,y,z
       
   
for i, x in enumerate(li):
       
print x
       
   
print i

def texcept():
   
try:
       
print __debug__     #Python 内置一个 debug 变量
       
assert True, 'assert is true'
       
raise DeviceError(999, 'CODE-999')
   
except DeviceError as de:
       
print de.msg
       
print sys.exc_info()    #可以查看系统最近的执行信息


if __name__ == '__main__':
   
#func()
   
#tfor()
    texcept()
   

    


转载于:https://my.oschina.net/cuckoocs/blog/375273

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值