【问题标题】:Why is it continuing to repeat the while True even though I have broken it?为什么即使我已经打破它,它仍然会继续重复 while True ?
【发布时间】:2013-12-27 03:42:03
【问题描述】:
...
elif error.lower() == 'create':
    while True:
        try:
            username = raw_input('What would you like your username to be?  ')
            username2 = raw_input('Please enter the same username again: ')
            while not pickle.load(open("%s.p"%username, "rb"))[1]:
                break
                break
            else:
                pickle.load(open("","rb"))
        except IOError:
            print 'The username is not available. Please try a different one.'
    pword = getpass('What would you like your password to be?  ')
    pword2 = getpass('Please enter the same password again: ')
    while pword != pword2:
          print 'The passwords do not match.'
          pword = getpass('What would you like your password to be?  ')
          pword2 = getpass('Please enter the same password again: ')
    money_left = 0
    isguest = False
    print 'Your username is %s, and your password is %s. You have $%d ingame money.' % (username, pword, money_left)
...

当我尝试在我的 while True 中创建帐户时,我会在注册之前确保用户名可用。如果用户名不可用,它会再次询问我,但即使是,它仍然会继续询问。你能帮帮我吗?

【问题讨论】:

  • 你只是跳出while not pickle.load循环,你永远不会跳出while True:
  • 如果您认为第二个 break 会这样做,那您就错了。它永远不会被执行,因为第一次中断会导致内部循环中的所有代码停止。

标签: python-2.7 while-loop pickle break


【解决方案1】:

break 语句脱离了while not... 语句,而不是while True 循环。我怀疑你的意思是写:

if not pickle.load(open("%s.p"%username, "rb"))[1]:
    break

break 上的文档是here.

我对您的代码进行了一些调整。看看这是否适合你:

import os.path
while True:
    username = raw_input('What would you like your username to be?  ')
    if os.path.exists("%s.p" % username):
        print 'The username "%s" is not available. Please try a different one.' % (username,)
        continue
    username2 = raw_input('Please enter the same username again: ')
    if username == username2:
        break
    else:
        print "The usernames don't match.  Try again."

while True:
    pword = raw_input('What would you like your password to be?  ')
    pword2 = raw_input('Please enter the same password again: ')
    if pword == pword2:
        break
    else:
        print 'The passwords do not match. Try again.'

money_left = 0
isguest = False
print 'Your username is %s, and your password is %s. You have $%d ingame money.' % (username, pword, money_left)

【讨论】:

    猜你喜欢
    • 2013-05-10
    • 2017-05-05
    • 2022-01-11
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多