zoukankan      html  css  js  c++  java
  • 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:
        print x
        x += 1

    2、for循环

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

     三、跳出循环

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

    1、break

    2、continue

    3、while True/break习语

    while true:
        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'
    except Exception as e:
        print 'the wrong way'
        print 'return the exception:',e
    else:
        print 'continue the right way'
    finally:
    print 'all continue'

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

  • 相关阅读:
    基于.net 4.0框架的Cipher演示程序
    文件校验 加解密
    Base64加解密
    RSA加解密
    UBT框架加解密工具项目 UBT.Framework.Encryption
    AESTest
    message-digest algorithm 5
    Aforge.net
    Winform非UI线程更新UI界面的各种方法小结
    Hadoop-2.6.5安装
  • 原文地址:https://www.cnblogs.com/susan-su/p/10732786.html
Copyright © 2011-2022 走看看