你好我有这个登录,我正在尝试,当我到达命令屏幕,如果我想退出程序我键入“退出”,但问题是我有一个双时循环和不知道如何突破两者。以下是代码示例:
a = 0
b = 0
loginatt = 0
while a == 0:
if loginatt == 4:
print "Too many tires!"
break
password = raw_input("Password: ")
if password == "test":
b = 1
while b == 1:
command = raw_input("command: ")
if command == "exit":
break
else:
loginatt += 1
print "error, login failed!"
这部分代码不会突破double while循环:
command = raw_input("command: ")
if command == "exit":
break
答案 0 :(得分:0)
break
只会留下一个级别的循环。您可以尝试重置外部循环变量:
if command == "exit":
a = 1
break
但是,最好稍微破解你的代码:
def access_control(correct_pass="test", attempts=4):
"""Control access to the supplied function func."""
for _ in range(attempts):
password = raw_input("Password: ")
if password == correct_pass:
get_commands()
break
else:
print "Incorrect password."
else:
print "Too many tries."
def get_commands():
"""Take user input until they enter 'exit'."""
while True:
command = raw_input("Command: ")
if command == "exit":
break
您现在可以致电access_control
输入密码;如果正确,您将被转移到get_commands
:
>>> access_control()
Password: test
Command: exit
>>>
或
>>> access_control()
Password: foo
Incorrect password.
Password: bar
Incorrect password.
Password: baz
Incorrect password.
Password: python
Incorrect password.
Too many tries.
>>>
答案 1 :(得分:0)
没有关键字可以从多个循环中断开。您可以尝试以下方法:
wantToBreak = False
while b == 1:
command = raw_input("command: ")
if command == "exit":
wantToBreak = True
break
if wantToBreak:
break
它利用一个布尔变量来指示是否应该中断流程(打破更多级别)。
答案 2 :(得分:0)
通常,a
和b
之类的变量名称不是非常明确的。此外,您的登录功能与您的命令功能无关,因此为什么不将它们分开?
#! /usr/bin/python2.7
def login(maxTries = 4):
while maxTries:
password = raw_input('Password: ')
if password == 'test':
return True
maxTries -= 1
print 'Too many tries.'
return False
def runCommand():
while True:
command = raw_input('Command: ')
if command == 'exit': break
print 'processing command', command
if login(): runCommand()
在找到命令exit
时,您也可以使用带有标记的迭代器,而不是断开:
def runCommand():
for command in iter(lambda: raw_input('Command: '), 'exit'):
print 'processing command', command