Python的三种结构
顺序、分支、循环
某单次测试的流程:
例子:
# 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.
例子:
# 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