2016-11-22 138 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

相关问题