码迷,mamicode.com
首页 > 其他好文 > 详细

基础知识回顾——流程控制

时间:2017-01-14 13:52:48      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:回顾   代码块   free   size   pwd   通过   程序   class   for循环   

通过条件语句或循环语句改变程序运行顺序的过程叫流程控制。

 

条件语句

条件语句:用于改变程序的执行流程,其中else代码块是可选的。
1.if/else

1 pwd = raw_input("what‘s the password ?")
2 if pwd == apple:
3   print "loging on..."
4 else:
5   print "password error!"
6 print "all done"

 

2.升级版if/elif

1 pwd = raw_input("how old are you ?")
2 if age <= 12:
3   print free
4 elif 12 < age < 16:
5   print child fare
6 else :
7   print adult fare

 

循环语句

循环语句:用于重复执行代码块,主要有for循环和while循环,其中for循环比while易使用,while比for灵活。

for循环更适用于条件已知,循环次数固定的场合;while循环更适合于条件不确定的场合,while循环比for循环内存中多一个变量声明。


1.for循环,执行N次

1 for i in range(10):
2     print i

 

2.while循环,执行N+1次,直到最后一次为假

1 i = 0
2 while i < 10:
3     print i
4     i = i + 1

 

3.中断循环,continue中断本次循环,break中断整个循环

 1 #当循环执行到i = 2的时候,if条件成立,触发continue, 跳过本次执行(不执行print),继续进行下一次执行(i = 3)
 2 for i in range(10):
 3     if i == 2:
 4       continue
 5     print i
 6 
 7 #当循环执行到i = 2的时候,if条件成立,触发break, 整个循环结束
 8 for i in range(10):
 9     if i == 2:
10       break
11     print i

 

基础知识回顾——流程控制

标签:回顾   代码块   free   size   pwd   通过   程序   class   for循环   

原文地址:http://www.cnblogs.com/Ryana/p/5972533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!