Python基础入门-While循环

讲完了for循环我们继续来看第二个循环,那就是while循环,while循环和for循环虽然都是循环,但是有着本质的不同。我们先来看下她们之间的区别和联系:

While循环和for循环区别:

  • 1.for循环迭代的是(序列)可迭代的对象用于遍历所有序列对象的元素
  • 2.顶端测试为真,既会执行循环体,并会重复多次测试直到为假后执行循环后的其他语句

1.先看下while循环的定义:while循环是当while后面的条件(表达式)为真,才执行while循环体内的while suite,直到条件为假时,退出循环。

2.while循环结构

while expression:
  while stiue 

实例1:

while  True:
   print "----------------->"  

当条件为真时,while语句块的内容将会一直被执行,也成为死循环。在看一个例子:

while  1:
   print "--------------------->"

原理等同于实例1

count  = 5  
while count   < 0:
  print  '当前打印数值小于',count
  count  += 1 
else:
  print  '当前打印的数值大于',count

while结合if语句实例演示:

count  = 0
while count < 3:
    name  = input("输入你的名字:")
    if  name.endswith('shan'):
        if name.startswith('zhao'):
            print 'hello,{}'.format(name)
        elif  name.startswith('li'):
            print 'bye,{}'.format(name)
        else:
            print  '++++++++',name
    else:
        print 'game over'
    count+=1
else:
    print  '游戏结束'

while和break结合,break 和continue 语句:break跟别的编程语言一致,退出循环continue只是跳出本次循环

b = 1
while b:
  print  b 
  b+=1 
  if  b == 4:
print  'out cxunhuan'

或者使用while循环实现一个敏感词的过滤机制:

test = []
while True:
    x = raw_input("enter a quary:")
    if  x == 'e' or x=='quit':
        break
    else:
        test.append(x)
print  test
在或者当变量 var 等于 5 时退出循环
var  = 10
while var > 0:
    print '当前打印的是',var
    var = var - 1
    if  var == 5:
        break
        
print 'byebye'

使用while循环将列表内的奇数和偶数分开

number = [1,2,3,0,4,5,6,7]
odd = []
even =[]
while len(number)>0:
    numbers = number.pop()
    if numbers % 2 == 0:
        odd.append(numbers)
    else:
        even.append(numbers)
print odd
print even
#while循环打印url 地址
url ='www.baidu.com'
while url:
  print url 
  url = url[1:]

输出结果如下:

www.baidu.com
ww.baidu.com
w.baidu.com
.baidu.com
baidu.com
aidu.com
idu.com
du.com
u.com
.com
com
om

 while循环是不是很强大呢?这一篇我们就介绍到这里了.....

原文地址:https://www.cnblogs.com/fighter007/p/8268670.html