本文是对python中条件判断语句和循环语句的一个简单回顾性总结。 python和多数语言一样,控制流主要包括if条件判断语句和循环条件判断,将结合具体代码案例进行记录。
目录
if条件控制流
if控制流主要包括 if else 和if elif elif... else语句。
实例:
x=-3
if x < 0:
print ("'It's negative'")
#输出: 'It's negative'
x=20
if x < 0:
print "'It's negative'"
elif x == 0:
print 'Equal to zero'
elif 0 < x < 5:
print 'Positive but smaller than 5'
else:
print 'Positive and larger than 5'
# 输出: Positive and larger than 5
a = 5; b = 7
c = 8; d = 4
if a < b or c > d:
print 'Made it'
# 输出: Made it
循环控制流
循环条件控制主要包括 : for循环和while循环
sequence = [1, 2, None, 4, None, 5]
total = 0
for value in sequence:
if value is None:
continue
total += value
sequence = [1, 2, 0, 4, 6, 5, 2, 1]
total_until_5 = 0
for value in sequence:
if value == 5:
break
total_until_5 += value
# while
x = 256
total = 0
while x > 0:
if total > 500:
break
total += x
x = x // 2
print(x)
# pass
if x < 0:
print 'negative!'
elif x == 0:
# s put something smart here
pass # pass 关键字, python中的空操作
else:
print 'positive!'
异常处理
优雅的处理python 错误或者异常是构建健壮程序的重要环节 ,try/except finally 模块
def attempt_float(x):
try: # try /except 模块 处理报错
return float(x)
except:
return x
attempt_float('1.2345')
attempt_float('something')
输出:'something'
def attempt_float(x):
try:
return float(x)
except (TypeError,ValueError): #注意 编写一个由异常类型组成的元组(圆括号是必须的)即可捕获多个异常
return x
attempt_float((1, 2))
输出: (1, 2)
不想处理任何异常,而只是希望有一段代码不管try 模块代码成功与否 ,finally模块都能被执行,
# 注意 当你不想处理任何异常,而只是希望有一段代码不管try 模块代码成功与否 ,finally模块都能被执行,
path='./tempPath.txt'
f = open(path, 'w')
try:
f.write("hhh")
finally:
f.close()
f = open(path, 'w')
try:
f.write("hhh")
except:
print 'Failed'
else: # 没有发生异常则会执行else
print 'Succeeded'
finally:
f.close()