08-python_流程控制-if

来源:互联网 发布:淘宝 无忧退货 运费 编辑:程序博客网 时间:2024/04/29 05:20
if 语句

1. 语法-1 单分支


if expression:
    statement(s)

 expression
     True    非零, 非空
     False   零, 空(None)

2. 注意

   python使用缩进作为其语句分组的方法,
   缩进数量相同的代码 被认为是 同一等级的代码
   建议使用一个缩进为4个空格.
   即, 缩进数量相同的连续的语句 被认为是 同一语句块

3. 举例


 3.1 if_1.py
-------------------
if 1 < 2 :
    print "hello"
-------------------
 output:
    hello

 3.2 if_2.py
-------------------
if 1 < 2 :
    print "hello"
    print "world"
-------------------
 output:
    hello
    world

 3.3 if_3.py
-------------------
if 100 < 2 :
    print "hello"
print "world!!" 
-------------------
 output:
    world!!

4. 语法-2 双分支


if expression :
    statement(s)
else :
    statement(s)

5. 举例

if_else_1.py
-------------------
if 1 > 2 :
    print "hello "
else :
    print "world"
-------------------

6. 语法-3 多分支

if expression1 :
    statement(s)
elif expression2 :
    statement(s)  
elif expression3 :    
    statement(s)  
... ...
else :
    statement(s)  

7. 举例

-------------------
condition = raw_input("input A, B or C :")
if   "A" == condition :
    print "AAAAAAAAAAA"
elif "B" == condition :
    print "BBBBBBBBBB"
else :
    print "CCCCCCCCCC"
-------------------

8. if语句的嵌套

if exp1 :
    ...
    if exp2 :
        ...
else:
    ...

原创粉丝点击