python try except else循环_Python 条件、循环、异常处理

一、条件语句

1、布尔值

条件语句中,判断条件的值一般是布尔值。即条件为真时,将执行什么,条件为假时,将执行什么。

下面的值在作为布尔表达式的时候,会被解释器看做假(false):

False None 0 "" () [] {}

注:虽然上面的值被看做是假,但是它们本身并不相等,也就是说None != ()

2、条件语句

a、if语句

b、if....else语句

c、if....elif...elif...else语句

num = input('Enter a number:')if num>0:print 'the number is positive'

elif num<0:print 'the number is negative'

else:print 'the number is zero'

d、嵌套代码块,if....else语句中,if代码块中还包含if...else语句之类

二、循环

1、while循环

x = 1

while x <= 5:printx

x+= 1

2、for循环

for i in range(4):print(i)

三、跳出循环

一般情况下,循环会一直执行到条件为假,或者到序列元素用完时。但是有些时候可能会提前中断一个循环,进行新的迭代,或者仅仅就是想结束循环

1、break

2、continue

3、while True/break习语

whiletrue:

word= raw_input('please enter a word:')if not word:break

print 'the word was'+ words

四、列表推导式

是利用其它列表创建新列表的一种方法。

print([x*x for x in range(5)]) #[0, 1, 4, 9, 16]

五、异常

1、raise语句,用来引发异常

raise Exception('something is wrong')

2、try..except语句,捕捉异常

3、try..except...except,不止一个except子句

4、try...except () as e,捕捉对象,记录下错误

5、try...except..else..,如果没有发生异常,执行完try子句后,会执行else子句;

try:print 'the right way'

exceptException as e:print 'the wrong way'

print 'return the exception:',eelse:print 'continue the right way'

finally:

print 'all continue'

6、try...except..finally..不管异常是否发生,都会执行finally子句;

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值