第八天学习:Python流程控制语句

1、python语句块缩进,建议四个空格缩进。

 

2、if、while用法
 
if控制语句基本形式:
if 判断条件:
    执行语句……
else:
    执行语句……

  

当判断条件为多个值时:
if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……
 
while 基本形式:
while 判断条件:
    执行语句……
 
 

while … else 在循环条件为 false 时执行 else 语句块:

#!/usr/bin/python
 
count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

 

 

3、for用法
 
for循环的语法格式:
for iterating_var in sequence:
   statements(s)

  

test = ('a', 'b', 'c')
for i, v in enumerate(test):
    print(i, v)
D:\Python27\python.exe D:/PycharmProjects/learn5/5.1.py
(0, 'a')
(1, 'b')
(2, 'c')

 

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中
 
 
 
4、 循环使用 else 语句
在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样.
for i in range(10):
    print(i)
else:
    print('end')
D:\Python27\python.exe D:/PycharmProjects/learn5/5.1.py
0
1
2
3
4
5
6
7
8
9
end

Process finished with exit code 0

  

xrange返回一个生成器,每次调用返回其中的一个值
range 返回一个列表,一次把所以数据都返回,占用很大的内存
 
 
5、 continue 和 break 用法
while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立。
break 中止循环,如果您使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码
for i in range(10):
    print(i)
    if i >3:
        break

  

continue跳出本次循环,进入下一轮循环
for i in range(10):
    if i == 3:
        continue
    print('%d is not 3' %i )

 

i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    print i         # 输出双数2、4、6、8、10
 
i = 1
while 1:            # 循环条件为1必定成立
    print i         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break

  

 

 

posted @ 2017-10-26 01:06  男孩别哭  阅读(146)  评论(0编辑  收藏  举报