0

我一直在空闲时间编写一段代码,搞乱打开/关闭文件以尝试获得 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”中已经存储了一个单词)并故意输入错误的密码进行错误测试时,我不会再次提示我输入另一个密码,并按应有的方式打印我的尝试。

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

4

1 回答 1

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”不同。如果你继续尝试,你会惹上麻烦

于 2013-06-06T06:51:12.427 回答