2016-11-22 96 views
-1

這是什麼造成了無限循環?如果它沒有創建一個,爲什麼程序凍結?不像IDLE停止響應,它只是停止,就像我創建了一個無限循環,它唯一做的就是input()。試着看看我的意思。 (也告訴我,如果在評論中爲的是正確的,請)爲什麼這個函數創建一個無限循環?

Accounts = {} 
def create_account(x,y,z,a): 
    global Accounts 
    Checked = False 
    while Checked == False: 
     if x in Accounts: 
      print("Sorry, that name has already been taken") 
      print("Please choose a new name") 
      x = input() 
     for dictionary in Accounts: 
      for key in dictionary: 
       if a in key: 
        print("Sorry, password is invalid or not avalible") 
        print("Please choose a new password") 
        a = input() 
    Accounts[x] = {"Proggress":y,"Points":z,"Pass":a} 
    print(Accounts[x]) 
+9

在哪裏'檢查'成爲'真'來打破循環?無處。在哪裏可以打破它呢?無處。沒有回報,沒有任何東西,你會得到一個無限循環。 –

+0

爲了退出while循環,你必須設置檢查爲真 – mWhitley

+0

爲什麼不'def create_account(name,progress,points,password)'? 'x,y,z,a'是非常不清楚的。 – IanAuld

回答

0

我認爲你正在嘗試做的是這樣的: 此代碼是未經測試

Accounts = {} 
def create_account(x,y,z,a): 
    global Accounts 
    Checked = False 
    while Checked == False: 
     if x in Accounts: 
      print("Sorry, that name has already been taken") 
      print("Please choose a new name") 
      x = input() 
     else: 
      passwordOk = True 
      for dictionary in Accounts: 
       for key in dictionary: 
        if a in key: 
         passwordOk = False 
         break 
       if not passwordOk: 
        break 
      if not passwordOk: 
       print("Sorry, password is invalid or not avalible") 
       print("Please choose a new password") 
       a = input() 
      else: 
       Checked = True # this is the important part that you missed 
    Accounts[x] = {"Proggress":y,"Points":z,"Pass":a} 
    print(Accounts[x]) 

僅供您知道,您的代碼可以進行優化。我試圖通過修改儘可能最小的代碼來解決您的問題,以便您能夠理解問題

1

您的代碼創建了一個無限循環,因爲沒有什麼可以阻止它。

while checked == False會做什麼這聽起來像,它會遍歷所有的代碼,一遍又一遍,直到checked = True或者直到你break

break只會停止循環,使程序完成。

checked = True也將停止循環

0

有導致此兩個問題。

正如你所說,

打印()是輸入(前),並打印從不輸出,所以它不會走到這一步

然而,讓我們一起來退後一步:打印語句位於塊if x in Accounts:內。在第一行中,您將Accounts設置爲空字典(Accounts = {}),因此無論x是什麼,此時x in Accounts都不會是真的 - 其中沒有任何

現在,你有一個線,增加了項目Accounts

Accounts[x] = {"Proggress":y,"Points":z,"Pass":a} 

然而,正如其他人所指出的那樣,你永遠不會在這裏 - 這是外循環,而循環永遠不會退出因爲Checked永遠不會設置爲True,也不會調用break

你的節目則基本上只是打算通過什麼都不做同樣的幾個步驟:

  1. 是否Checked == False?是的,繼續循環。
  2. x in Accounts?不,請跳過這個塊。
  3. dictionaryAccounts,做一些東西,但Accounts是空的,所以我不需要做任何事情。
  4. 請問Check == False?是的,繼續循環。
+0

我知道它說不要用評論來表達謝意,但無論如何,這正是我所需要的。設置賬戶變量後,我忘記添加pickle.dump語句。現在我知道我需要添加一些內容來檢查帳戶是否爲空,然後中斷。再次感謝! – Nate

相關問題