[英]Why does this function not re-prompt the user after an incorrect guess?
我在空闲时间写了一段代码,搞乱打开/关闭文件以尝试获得100%安全的文件。
到目前为止我有这个:
def StartLock():
my_pass = open("pass.txt", "r+")
passcode = my_pass.read()
my_pass.close()
# Establish "passcode" variable by reading hidden text file
if passcode != "":
PasswordLock(input("Password: "))
elif passcode == "": #Passcode is empty
print("Passcode not set, please set one now.")
my_pass = open("pass.txt", "r+")
passcode = my_pass.write(input("New Pass: ")) #User establishes new pass
my_pass.close()
print("Passcode set to :" + passcode)
PasswordLock(passcode) #User is passed on with correct pass to the lock
def PasswordLock(x):
my_pass = open("pass.txt", "r+")
passcode = my_pass.read()
my_pass.close()
attempts = 3
def LockMech(x): #Had to do this to set attempts inside instance while not resetting the num every guess
if attempts != 3:
print("Attempts Left: " + str(attempts))
if x == passcode:
print("Passcode was correct. Opening secure files...")
return True
elif attempts == 0:
print("You are out of attempts, access restricted.")
Close()
elif x != passcode and attempts > 0:
print("Passcode was not corrent, please try again.") #This does get printed to console when I type in a wrong pass, so it gets here
attempts = attempts - 1
LockMech(input(":")) #This is what seems to be broken :(
def Close():
pass
StartLock()
出于某种原因,当我运行它(已经存储在“pass.txt”中的单词)并故意输入错误的密码进行错误测试时,我不会再次提示输入另一个密码,我的尝试打印应该是这样。
我已经确保在另一个函数中定义一个函数是可以接受的并且我的拼写是正确的,并且在使用代码试图让它工作之后我无法找到问题。 。
我没有看到LockMech
被称为何处。
让LockMech
递归调用本身是一种奇怪的方法来进行重试。 为什么不使用while
循环或for
循环?
读取密码的首选方法是使用上下文管理器
with open("pass.txt", "r+") as my_pass:
passcode = my_pass.read()
这样,文件在块结束时自动关闭
这是您的PasswordLock
的简化版本。 您必须对程序进行一些其他小的更改才能使用它
def PasswordLock():
with open("pass.txt", "r+") as my_pass:
passcode = my_pass.read()
for attempts_remaining in (2, 1, 0):
x = input("Password: ")
if x == passcode:
print("Passcode was correct. Opening secure files...")
return True
if attempts_remaining:
print("Passcode was not corrent, please try again.")
print("Attempts Left: {}".format(attempts_remaining)
print("You are out of attempts, access restricted.")
return False
请注意,我将您的调用替换为Close()
并return False
。 函数调用与“goto”不同。 如果你继续这样做,你会让自己烦恼
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.