Python 分支和迴圈

來源:互聯網
上載者:User

標籤:mos   end   start   while   bre   ace   開始   last   one   

1、當有多個條件是用 elif 這樣就不用那麼多縮排

score = int(input(‘輸入一個分數‘))
if 100 >= score >= 85:
print(‘A‘)
elif 85 > score >= 60:
print(‘B‘)
elif 60 > score >= 0:
print(‘C‘)
else:
print(‘輸入錯誤! ‘)

2、三元操作符  文法 x if 條件 else y

    small = x if x < y else y  #當if後面的條件為真的時候把x的值賦給small;當條件為假的時候把y的值賦給small

3、斷言 assert #當這個關鍵字後面的條件為假的時候程式自動崩潰,並拋出AssertError。當需要程式中的某個條件一定為真時才能讓程式正常運行,assert就非常有用。

>>> assert 3 < 4
>>> assert 3 > 5
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
assert 3 > 5
AssertionError

4、while迴圈  #在條件為真的時候執行某一段制定的代碼,只要條件為真,while迴圈就會一直去重複執行那一段代碼。這段代碼就是一個迴圈體。

5、for迴圈

①>>> favourite = ‘welcom‘          ②>>>member = [‘QQ‘, ‘QW‘, ‘QR‘]       
   >>> for i in favourite:                 >>>for each in member:
               print(i, end=‘8‘)                         print(eacd, len(each))         #列印each的長度  即QQ有兩個字元就列印2    


   w8e8l8c8o8m8                            QQ 2

                                                    QW 2

                                                    QR 2
 6、range文法:range(start, stop, step) 預設step=1 

     ① >>> range(0,5)     

      >>> list(range(5))

      [0, 1, 2, 3, 4]

      ② >>> for i in range(2, 7):    #7是不包含的

                      print(i)


        2
        3
        4
        5
        6

>>> for i in range(1, 10, 4):        #4代表每次步進4,從1開始列印出1-10從1開始每次步進4的數

              print(i)


   1
   5
   9

7、break 終止當前迴圈並跳出這個迴圈體  

bingo = ‘猜答案‘
print(‘輸入一句話‘)
answer = raw_input()
#print bingo
#print answer
while True:
if answer == bingo:
break
print(‘抱歉輸錯了,請重新輸入才能退出‘)
answer = raw_input()
print(‘很好額‘)
print(‘答對了‘)

8、continue  當迴圈條件為True的時候終止本輪迴圈並開始下一輪迴圈 ,如果不退的話會跳出迴圈

for i in range(10):
if i%2 != 0:
print(i)
continue
i += 2
print(i)

顯示結果是:
2

1

4

3

6

5

8

7

10

9                                  

                                             

 

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.