Python三种结构

Python的三种结构

顺序、分支、循环

某单次测试的流程:

Created with Raphaël 2.1.0 测试结果? True处理 接下来 False:else处理 yes no

例子:

# coding=utf-8
__author__ = 'zyt'

# if-elif-else
x = 0
if x < 0:
    print 'x less than 0'
elif x == 0:
    print 'x equals to 0'
else:
    print 'x large than 0'

# while
x = 0
while x < 5:
    print x
    x += 1
else:
    x = 0
    print 'while statement over, now x = %d' % x

# for-in
for y in range(10, 19, 3):
    print y,  # print默认会每行增加一个换行符,print句后加一个逗号就不会了
else:
    print '\nfor statement over'



运行结果:
E:\python_workspace>python test.py
x equals to 0
0
1
2
3
4
while statement over, now x = 0
10 13 16
for statement over

try…语句

语法

“try” “:” suite
(“except” [expression [(“as” | “,”) identifier]] “:” suite)+
[“else” “:” suite]
[“finally” “:” suite]

The optional else clause is executed if and when control flows off the end of the try clause.

Created with Raphaël 2.1.0 *try异常? 尝试成功的处理 *else处理 *finally *except捕获的处理 yes no

例子:

# coding=utf-8
__author__ = 'zyt'


def my_func(denominator):
    try:
        a = 1 / denominator
        print 'try statement'
    except:
        print 'except statement'
        a = 999999
    else:
        print 'else statement'
    finally:
        print 'finally statement'

    print 'function end'
    return a


if __name__ == '__main__':
    print my_func(1)
    print '---------'
    print my_func(0)



运行结果:
E:\python_workspace>python test.py
try statement
else statement
finally statement
function end
1
---------
except statement
finally statement
function end
999999

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值