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

if...while循环

时间:2017-07-18 22:12:01      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:als   log   ges   代码   bre   loop   tin   ==   images   

一.if语句

功能:希望电脑像人脑一样在不同的条件下,做出不同的反应。

语法:

 执行代码

1.第一种

1 a = 1
2 b = 2
3 if a > b and (a/b > 0.2):
4     print(yes)
5 else:
6     print(no)

2.第二种

 1 num = 5     
 2 if num == 3:            
 3     print boss        
 4 elif num == 2:
 5     print user
 6 elif num == 1:
 7     print worker
 8 elif num < 0:           
 9     print error
10 else:
11     print roadman 

3.第三种

NUM = 7
if NUM > 6 or NUM >4: 
   print(ok)

注意:1.一个if判断只能有一个else,else代表if判断的终结

           2.条件可以引入运算符:not,and,or,is,is not

           3.下列对象的布尔值都是False

            技术分享

二.while语句

 基本形式

 

while 判断条件:

         执行语句……

例子:

1 #!/usr/bin/python
2  
3 count = 0
4 while (count < 9):
5    print The count is:, count
6    count = count + 1  
7 print "Good bye!"

while 语句时还有另外两个重要的命令 continue,break 来跳过循环,continue 用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立,具体用法如下:

 1 # continue 和 break 用法
 2  
 3 i = 1
 4 while i < 10:   
 5     i += 1
 6     if i%2 > 0:     # 非双数时跳过输出
 7         continue
 8     print i         # 输出双数2、4、6、8、10
 9  
10 i = 1
11 while 1:            # 循环条件为1必定成立
12     print i         # 输出1~10
13     i += 1
14     if i > 10:     # 当i大于10时跳出循环
15         break

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

 1 #!/usr/bin/python
 2  
 3 count = 0
 4 while count < 5:
 5    print count, " is  less than 5"
 6    count = count + 1
 7 else:
 8    print count, " is not less than 5"
 9 #输出结果
10 0 is less than 5
11 1 is less than 5
12 2 is less than 5
13 3 is less than 5
14 4 is less than 5
15 5 is not less than 5

无限循环:

count=0
while True:
    print(the loop is %s %count)
    count+=1
tag=True
count=0
while tag:
    if count == 9:
        tag=False
    print(the loop is %s %count)
    count+=1

 

if...while循环

标签:als   log   ges   代码   bre   loop   tin   ==   images   

原文地址:http://www.cnblogs.com/sxh-myblogs/p/7202780.html

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