Python學習筆記(4):控制流程

來源:互聯網
上載者:User

Python的控制語句有if、while、for、break、continue。

1. if語句

下面是一個猜數字遊戲例子:

# Filename: if.pynumber = 10guess = int(input("Enter a integer:"))if guess == number:    print("Congratulations, you guessed it.")elif guess < number:    print("No, it is a little higher than that")else:    print("No, it is a little lower than that")

注意if語句結尾處包含一個冒號(:),所有控制語句結尾處都需要冒號。Python沒有switch語句,您可以用if...elif...else來完成相同功能。

2. while語句

您可能發現上面猜數字遊戲,每次都要啟動一下才能猜,下面可以用while語句來控制直到你猜中才離開遊戲。

# Filename: while.pynumber = 10running = Truewhile running:    guess = int(input("Enter a integer:"))    if guess == number:        print("Congratulations, you guessed it.")        running = False    elif guess < number:        print("No, it is a little higher than that")    else:        print("No, it is a little lower than that")else:    print("The game is over.")

其實與while相對的else是多餘的,與直接把它的語句放在在while語句塊後面的效果相同。

3. for語句
# Filename: for.pyfor i in range(1, 5):    print(i)else:    print("The for loop is over.")

輸出結果為:

1

2

3

4

The for loop is over.

4. break語句
# Filename: break.pywhile True:    s = input("Enter something:")    if s == "quit":        break    print("Length of the string is", len(s))print("Done")
5. continue語句
# Filename: continue.pywhile True:    s = input("Enter something:")    if s == "quit":        break    if len(s) < 3:        continue    print("Input is of sufficient length")
相關文章

聯繫我們

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