if...while循环

一.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

 

posted @ 2017-07-18 21:23  爱笑的大象  阅读(822)  评论(0编辑  收藏  举报