Python变量没有定义的时候?

时间:2016-01-26 18:09:11

标签: python error-handling

import linecache
print("Welcome to the online safety quiz!") 



registereduser = input("Are you a registered user? Enter Y or N: ") 

registereduser = registereduser.upper() 


if registereduser == "Y":
    username = input("What is your school username? ")
    stored_username = linecache.getline("{0}.csv".format(username), 4)
    print (stored_username)

    if username == stored_username:
        stored_password = linecache.getline("{0}.csv".format(username), 5)
        stored_fullname = linecache.getline("{0}.csv".format(username), 1)
        print("Hello {0} ").format(stored_fullname)
        password = input("What is your password? ")
        import hashlib, uuid
        salt = "87e6781077c7420cbc160853b62693f3"
        hashed_password = hashlib.sha512(password.encode('utf-8') + salt.encode('utf-8')).hexdigest()
    if stored_password == hashed_password:

        print("You have logged in successfully")
    else:
        print("ERROR Your details do not match the one in our database please retry or register again ") 

这是我运行代码时遇到的错误。 Traceback(最近一次调用最后一次):   文件“C:\ Users \ joel \ python”,第25行,in     如果stored_pa​​ssword == hashed_pa​​ssword: NameError:名称'stored_pa​​ssword'未定义

请记住,我已将数据文件存储在程序从...中检索数据的同一文件夹中。

3 个答案:

答案 0 :(得分:2)

问题是stored_password仅在username == stored_username时声明。通过使用默认值预先声明它来解决此问题。

stored_password = ''
if username == stored_username:
    ...

答案 1 :(得分:0)

Stored_pa​​ssword在if语句中本地定义。你需要在第16行添加stored_pa​​ssword = None

答案 2 :(得分:-1)

你的缩进是关闭的。当前的缩进与当前用户名== stored_username。

的级别相同

如果你缩进if语句,它应该有效。