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循環是不是很強大呢?這一篇我們就介紹到這里了.....


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM