Python基礎之控制語句

來源:互聯網
上載者:User

標籤:style   列印   控制流程   print   integer   pytho   sed   包括   個數   

在Python 中有三種控制流程語句——if、for 和while。 1.if語句
Number = 23Guess = int(input(‘Enter an integer : ‘))if Guess == Number:  print(‘Congratulations, you guessed it.‘)  print(‘(but you do not win any prizes!)‘)elif Guess < Number:  print(‘No, it is a little higher than that‘)else:  print(‘No, it is a little lower than that‘)print(‘Done‘)
輸出:Enter an integer : 50No, it is a little lower than thatDoneEnter an integer : 22No, it is a little higher than thatDoneEnter an integer : 23Congratulations, you guessed it.(but you do not win any prizes!)Doneelif事實上是把兩個相關聯的if else-if else語句結合為一個if-else-else語句,使程式更簡單,並且減少所需的縮排數量。2.while語句
number = 23Running = Truewhile Running:  Guess = int(input("Enter an integer:"))  if Guess == Number:    print("Congratulations, you guessed it.")  elif Guess < Number:    print("No, it is a little higher.")  else:    print("No, it is a little lower.")else:  print("the while loop is over.")print("Done")
輸出:
Enter an integer : 50No, it is a little lower.Enter an integer : 22No, it is a little higher.Enter an integer : 23Congratulations, you guessed it.The while loop is over.Done
while 語句有一個可選的else 從句,他將始終被執行,除非迴圈永遠迴圈下去。3.for迴圈
for i in range(1,5):  print(i)else:  print("The for loop is over")
輸出:1234The for loop is over  在這裡,提供兩個數,range返回一個序列的數,這個序列從第一個數開始到第二個數位置,range(1,5)給出序列[1,2,3,4]。預設range的步長為1。如果為range提供第三個數,那麼它將作為步長,例如,range(1,5,2)給出序列[1,3],步長為2。range的範圍不包括第二個數。  for i in range(1,5)等價於for i in [1,2,3,4],把序列的裡的每個數賦值給i,一次一個。這個程式中列印的是i的值。  else是可選的,如果包含else,他總在for迴圈結束後執行一次,除非遇到break語句。

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.