如何修复Python中的无限循环?
我正在用Python编写一个登录安全程序,这部分总是卡在无限循环中。如果你被锁在外面,它会不断地说“你被锁在外面10秒钟了”,然后无限循环。我该如何解决这个问题如何修复Python中的无限循环?,python,loops,infinite-loop,infinite,Python,Loops,Infinite Loop,Infinite,我正在用Python编写一个登录安全程序,这部分总是卡在无限循环中。如果你被锁在外面,它会不断地说“你被锁在外面10秒钟了”,然后无限循环。我该如何解决这个问题 tries=0 while finalusername!=username or finalpassword!=password: tries=tries+1 print "That incorrect. Try again." print "You have", 5-tries, "tries left." finalusernam
tries=0
while finalusername!=username or finalpassword!=password:
tries=tries+1
print "That incorrect. Try again."
print "You have", 5-tries, "tries left."
finalusername= raw_input ("Username:")
finalpassword= raw_input ("Password:")
while tries>=4:
print "You have been locked out for 10 seconds. Please call the administrator if this keeps happening."
sleep (10.0)
system ('CLS')
finalusername!=username
finalpassword!=password
容易,改变
while tries>=4:
到
如果你遵循你的代码,当你进入你的第二个while循环时,变量trys的值永远不会改变,所以你将永远留在那里。如果将while更改为If,则将执行If语句的主体,然后继续循环。当尝试次数大于四次时,第二个while循环将激活,但循环本身从不在尝试时运行或包含任何其他退出条件。这就是它变得无限的原因。因此,尝试保持在4以上,循环从未停止
根据你的代码,在我看来,在他们尝试完之后,他们会被锁定10秒钟,然后重新开始?如果是这样,您希望如下调整代码:
tries=0
while finalusername!=username or finalpassword!=password:
tries=tries+1
print "That incorrect. Try again."
print "You have", 5-tries, "tries left."
finalusername= raw_input ("Username:")
finalpassword= raw_input ("Password:")
if tries>=4:
print "You have been locked out for 10 seconds. Please call the administrator if this keeps happening."
sleep (10.0)
system ('CLS')
tries = 0 #Reset tries counter
finalusername!=username #I don't think this part is required
finalpassword!=password #I don't think this part is required
我认为您应该在睡眠后将尝试设置为0,如果没有必要,则循环。睡眠后,用户应再次尝试5次
import os
import time
tries=0
finalusername, finalpassword= 'a', 'a'
username, password = None, None
while True:
finalusername= raw_input ("Username:")
finalpassword= raw_input ("Password:")
if finalpassword == username and finalpassword == password:
break
tries=tries+1
print "That incorrect. Try again."
print "You have", 5-tries, "tries left."
if tries>=5:
print "You have been locked out for 10 seconds. Please call the administrator if this keeps happening."
time.sleep (10.0)
os.system('cls')
tries = 0
你的压痕显然是错的。这将生成语法错误。
import os
import time
tries=0
finalusername, finalpassword= 'a', 'a'
username, password = None, None
while True:
finalusername= raw_input ("Username:")
finalpassword= raw_input ("Password:")
if finalpassword == username and finalpassword == password:
break
tries=tries+1
print "That incorrect. Try again."
print "You have", 5-tries, "tries left."
if tries>=5:
print "You have been locked out for 10 seconds. Please call the administrator if this keeps happening."
time.sleep (10.0)
os.system('cls')
tries = 0