Python條件判斷和迴圈

來源:互聯網
上載者:User

標籤:sse   tin   通過   意思   for 迴圈   break   退出   list   用法   

一、Python 之 if條件判斷 語句

(1)、Python 之 if——if語句後面接運算式,然後用 : 表示代碼開始

          注意: Python代碼的縮排規則。縮排要嚴格按照Python的習慣用法:4個空格,不要使用TAb,更不要混合Tab和空格,否則很容易造成因為縮排引起的語法錯誤。

         如果你在Python互動環境下敲代碼,還要特別留意縮排,並且退出縮排需要多敲一行斷行符號: 
 

>>> age = 20>>> if age >= 18:...     print ‘your age is‘, age...     print ‘adult‘...your age is 20adult

 

(2)、Python 之 if-else語句        

         利用 if ... else ... 語句,我們可以根據條件運算式的值為 True 或者 False ,分別執行 if 代碼塊或者 else 代碼塊。

          注意: else 後面有個“:”。

>>> score = 55>>> if score >= 60:...     print ‘passed‘... else:...     print ‘failed‘...failed

 

(3)、Python之if-elif-else語句

 

 

         elif 意思就是 else if。這樣一來,我們就寫出了結構非常清晰的一系列條件判斷。

 

         特別注意: 這一系列條件判斷會從上到下依次判斷,如果某個判斷為 True,執行完對應的代碼塊,後面的條件判斷就直接忽略,不再執行了。

 

>>> score = 85>>> if score >= 90:...     print ‘excellent‘... elif score >= 80:...     print ‘good‘... elif score >= 60:...     print ‘passed‘... else:...     print ‘failed‘...good

 

二、Python之迴圈語句

     (1)、Python之for迴圈語句

             Python的 for 迴圈就可以依次把list或tuple的每個元素迭代出來:

#班裡考試後,老師要統計平均成績,已知4位同學的成績用list表示如下:#L = [75, 92, 59, 68]#請利用for迴圈計算出平均成績。>>> L = [75,92,68,59]>>> sum = 0.0>>> for a in L:...     sum = sum + a...>>> print sum / 473.5

 

      (2)、Python之while語句

             

               

#利用while迴圈計算100以內奇數的和。>>> sum = 0>>> x = 1>>> while x < 100:...     sum = x + sum...     x = x + 2...>>> print sum2500

 

       (3)、Python之break退出迴圈語句

            用 for 迴圈或者 while 迴圈時,如果要在迴圈體內直接退出迴圈,可以使用 break 語句。

 

#利用 while True 無限迴圈配合 break 語句,計算 1 + 2 + 4 + 8 + 16 + ... 的前20項的和。>>> sum = 0>>> x = 1>>> n = 1>>> while True:...     sum = sum + x...     x = x * 2...     n = n + 1...     if n > 20:...         break...>>> print sum1048575

 

         (4)、Python之continue繼續迴圈語句

             continue跳過後續迴圈代碼,繼續下一次迴圈。

 

 

#通過 continue 語句,計算 0 - 100 的奇數的和:>>> sum = 0>>> x = 0>>> while True:...     x = x + 1...     if x > 100:...         break...     if x%2==0:...         continue...     sum = sum + x...>>> print sum2500

 

 

 

 

 

 

Python條件判斷和迴圈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.