为什么这个函数在猜错之后没有重新提示用户?

时间:2013-06-06 06:47:11

标签: python locking

我一直在空闲时间编写一段代码,弄乱打开/关闭文件以尝试获得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”中的单词)并故意输入错误的密码进行错误测试时,我没有被提示输入另一个密码,我的尝试打印为这应该。

我已经确定在另一个函数中定义一个函数是可以接受的并且我的拼写是正确的,并且在使用代码试图让它工作后我无法找到问题。

1 个答案:

答案 0 :(得分:2)

我没有看到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”不同。如果你继续尝试那么你会让自己烦恼