23213ew 发表于 2016-3-8 09:01:02

python 控制流语句

一、print语句
        1.1 基本输出
        1.2 print的逗号
        1.2 输出到文件 >>为重定向

1
2
3
>>> a=2
>>> print a,2 #,表示不换行
2 2





1
2
3
4
5
6
7
8
9
#!/usr/bin/python2.6
#coding=utf-8
print "2",
print "3",
print "4"
f = open('print.txt','w')
print >>f,"Hello",
print >>f,"world"
f.close





二、控制流语句(control flow)
    2.1 由条件和执行代码块组成。
                2.1.1 条件可分为决策、循环和分支
        2.2 格式(冒号与4个空格永不忘,尽量使用4个空格,而不是制表符)
        2.3 if while for 函数,皆为contorl flow

1
2
3
4
5
6
7
8
#!/usr/bin/python2.6
#coding=utf-8
'''
: 分隔了条件和代码块
缩进4个空格
'''
if True:
    print 4





       
3、布尔值
        3.1 控制流与真假值息息相关
                3.1.1 不要误解了真假与布尔值


1
2
3
4
5
6
7
8
#!/usr/bin/python2.6
#coding=utf-8
"""
建议使用bool()来判断真假,或者省略不写
"""
x = 3
if x:            #等价于if x == if bool(x)
    print 4




    3.2 布尔值的几个最基本运算符

                3.2.1 and
                3.2.2 or
                3.2.3 is 检查共享 ,判断是否引用了相同的对象,并且值相同
                3.2.4 == 检查值


1
2
3
4
          >>> 1 == True
          True
               >>> 1=='1'
               False





                3.2.5 not
                3.2.6 其他若干比较符号

1
2
3
4
if True:
print "True"
else:
print "not True"




       

1
2
3
4
5
6
if True:
print "True"
elif not True:
print "not True"
else:
pass




               
三、if语句 (控制流语句)
        4.1 if的组成 if else elif pass
                4.1.1 if与elif替代了switch
                4.1.2 pass       

        4.2 三元表达式
                4.2.1 x ifelse
                4.2.2 活用list
                4.2.3 三元表达式玩玩就好,因为python崇尚简洁

1
2
3
4
5
6
>>> 4 if True else 3
4
if True:
print 4
else:
print 3







1
2
>>> #[假的答案,真的答案][条件]
3





四、while语句
       
        1、while的基本格式
                while expression: #控制流的条件表达式(expression)结果,必须为True真
                        statement(s)

        2、while的基本组成部分
                2.1 break 结束while,如果有else,也不执行
                2.2 continue 跳出当前这次循环,不执行continue后面的代码,但不结束while
                2.3 else 正常结束while以后执行,但是如果while里面有break,则不会执行else


        3 注意:普通应用里,while一定要给一个结束条件,否则就是传说中的死循环

1
2
3
4
5
6
7
8
9
#coding=utf-8
x = 1
while True:
    x +=1
    print x
    if x > 20:
      break
else:
    print 'end'





五、for语句
        1、 for的基本格式
                for item in iterable:
                        statement(s)

        2、for的基本组成部分
                3.2.1 break
                3.2.2 continue
                3.2.3 else ,正常结束for以后执行,但是如果for里面有break,则不会执行else

        3、注意:for的最后一个迭代值将保留

1
2
3
4
5
6
7
8
9
10
11
# -*- coding:utf-8 -*-
for x in "i am li lei".split(' '):
    print x
else:
    print "for end" #for end
print x #lei
for x in "you are haimmeimei".split(' '):
    print x
else:
    print "for end" #for end
print x #haimmeimei





4.布尔值再议

        4.1 惰性求值,短路逻辑,需要时再求值。
        4.2 从左到右,从先到后。
        4.3 利用小技巧。or之默认值,前面的值不存在,则可以赋给一个默认值
   False or defaultValue
       


页: [1]
查看完整版本: python 控制流语句