python基礎while迴圈及if判斷的執行個體講解,pythonwhile

來源:互聯網
上載者:User

python基礎while迴圈及if判斷的執行個體講解,pythonwhile

wlile迴圈

while True表示永遠為真,不管是什麼條件都會向下執行,下面是寫的一個例子。

#!/usr/bin/env pythonage = 24                            #給age賦一個值while True:                           #進入迴圈 inputting = int (input("The input number is:"))       #儲存使用者輸出到變數inputting if inputting == age:                     #然後依次比較  print("Guessed it!!!")     break if inputting < age:  print("Is to small!!!") else:  print("Is to big!!!")

在寫一個比較人性化得例子,上面的例子是while True所有條件都為真,下面的例子是你符合條件了才認為是真,才可以執行以下代碼。下面例子作用就是限制你輸入3次後會告訴你,輸入的次數過多是否繼續,繼續按yes退出按no。

#!/usr/bin/env pythonage = 24   count = 0       #計數器while count <3:     #count值小於0才可以執行以下代碼。 inputting = int (input("The input number is:")) #將使用者輸出儲存到inputting變數裡面,int是資料類型。   if inputting == age:      print("Guessed it!!!") #講變數的值做比較  break      #如果使用者輸出的值等於age的值輸出列印,接著破壞迴圈 if inputting < age:  print("Is to small!!!") else:  print("Is to big!!!") count +=1      #每迴圈一次加一 while count == 3:    #如果count等於3了則執行以下代碼  warning = input("Whether or not to continue?(yes no)")#彈出警告資訊並將使用者輸出值存在warning變數中  if warning == 'no':  #按no破壞迴圈,yes繼續count被重設返回第一個迴圈,其他返回讓你輸入的資訊   break  elif warning == 'yes':   count = 0  else :   print("yes or no")

if判斷

“if”顧名思義就是如果怎樣,那就怎樣。接下來下面的例子就會用到if判斷,功能就是輸入使用者名稱密碼如果對了那面就會顯示歡迎資訊,如果使用者名稱密碼錯了,就會提示密碼或使用者名稱錯誤。當然你要不斷的輸入可以和上面的while迴圈關聯起來。

#!/usr/bin/env pythonusername = input("username:")password = input("password:")_username = ("admin")     #把使用者名稱密碼存放在_username和_password裡面_password = ("abc")if username == _name and password == _password: #把使用者輸出和給定的使用者名稱密碼做比較 print("Welcome {name} login....".format(name = username)) #{name}好比是預留位置,後面.format給定他真正的身份。else : print("Invalid username password")

以上這篇python基礎while迴圈及if判斷的執行個體講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援幫客之家。

聯繫我們

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