Python 學習筆記(十一)Python語句(三),學習筆記python語句

來源:互聯網
上載者:User

Python 學習筆記(十一)Python語句(三),學習筆記python語句

While 迴圈語句

用於迴圈執行程式,即在某條件下,迴圈執行某段程式,以處理需要重複處理的相同任務。

文法:

while 判斷條件:    執行語句……

執行語句可以是單個語句或語句塊。判斷條件可以是任何錶達式,任何非零、或非空(null)的值均為true。

當判斷條件假false時,迴圈結束。

樣本:for迴圈實現猜字遊戲

 1 #! /usr/bin/env python 2 #! coding:utf-8 3  4  5 """ 6 一個猜字遊戲:隨機產生一個數字,使用者每次輸入一個數字,來猜這個數字是否為隨機數。 7 for實現 8 """ 9 10 import random11 12 num =random.randint(1,100) #return a int [1,100]13 #注意:for 迴圈得有個問題,得知道迴圈多少次14 for i in range(0,100):15     input_num =int(raw_input("Please input a int:"))16     if input_num ==num:17         print "ok,you are right"18         print num19         break  #從當前迴圈體跳出20     elif input_num>num:21         print "input number is larger than int."22     else:23         print "input number is smaller than int."

while 實現猜字遊戲

 1 #! /usr/bin/env python 2 #! coding:utf-8 3  4  5 """ 6 while expression: 7     do something 8 """ 9 10 import random11 12 num =random.randint(1,100) #return a int [1,100]13 14 15 i =016 while i<10: #此處也可修改為1,直到猜中才會停止17     print i18     input_num =int(raw_input("Please input a int:"))19     if input_num ==num:20         print "ok,you are right"21         print num22         break  #從當前迴圈體跳出,執行迴圈體後面的內容23     elif input_num>num:24         print "input number is larger than int."25     else:26         print "input number is smaller than int."27 28     i +=1

break 

break語句用來終止迴圈語句,即迴圈條件沒有False條件或者序列還沒被完全遞迴完,也會停止執行迴圈語句。

break語句用在while和for迴圈中。

continue

continue 語句跳出本次迴圈,而break跳出整個迴圈。

continue 語句用來告訴Python跳過當前迴圈的剩餘語句,然後繼續進行下一輪迴圈。

continue語句用在while和for迴圈中。

樣本:continue

 1 #! /usr/bin/env python 2 #! coding:utf-8 3  4 a =9 5 while a: 6     if a%2==0: 7         a -=1 8         continue #如果是偶數,就返回迴圈的開始 9         print a 10     else:11         print "%d is odd number "%a #如果是奇數,就列印出來12         a -=113         

while ... else 

1 #! /usr/bin/env python2 #! coding:utf-83 4 count = 05 while count < 5:6       print count," is less than 5"7       count =count+18 else:9       print count," is not less than 5"

for ... else

 1 #! /usr/bin/env python 2 #! coding:utf-8 3  4 #開平方 5 from math import sqrt 6  7 for n in range(99,1,-1): 8     root = sqrt(n) 9     if root == int(root):10         print n11         break12 else:13     print "Nothing."

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.