python基礎 -- 04流程式控制制語句

來源:互聯網
上載者:User

標籤:需要   for   最好   art   流程式控制制語句   迴圈語句   並且   UI   strong   

1.Python縮排規則

         最好四個空格,其次Tab,禁止空格Tab混用

2.Python流程式控制制語句代碼塊原則

         : 表示代碼塊開始

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

3.if語句3.1普通if語句

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

3.2if-else語句

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

>>> if age >= 18:
... print ‘aduit‘
... else:
... print ‘teenager‘
...
aduit

3.3if-elif-else語句

if-elif語句和多if語句區別

       if-elif條件判斷會從上到下依次判斷,如果某個判斷為 True,執行完對應的代碼塊,後面的條件判斷就直接忽略,不再執行了。

       多if語句會全部執行,即使前面的條件已滿足,後面的也會執行。

>>> if age >=18:
... print ‘aduit‘
... elif age >=6:
... print "teenager"
... elif age >=3:
... print ‘Kid‘
... else:
... print ‘baby‘
...
aduit

4.迴圈語句 4.1for 迴圈

>>> L= [‘Adam‘,‘Lisa‘,‘Bart‘]

>>> for name in L:

...     print name

4.2While 迴圈

>>> N=10

>>> x=0

>>> while x<N:

...     print x

...     x+=1

4.3break 退出迴圈

>>> sum = 0

>>> x=1

>>> while True:

...     sum+=x

...     x+=1

...     if x>100:

...         break

4.4continue 繼續迴圈

>>> L=[75,98,59,81,66,43,69,85]

>>> sum =0.0

>>> n=0

>>> for x in L:

...    if x<60:

...             continue

...    sum +=x

...    n+=1

4.5 多重迴圈嵌套

>>> for x in [‘A‘,‘B‘,‘C‘]:

...    for y in [‘1‘,‘2‘,‘3‘]:

...             print x+y

python基礎 -- 04流程式控制制語句

聯繫我們

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