为什么我的with语句在while循环后跳过?

  • 本文关键字:循环 while 语句 with python
  • 更新时间 :
  • 英文 :


使用这段代码(我添加了一些打印来测试代码停止的地方),我得到这个:

您的详细信息已经存储在这里了吗?y/n y

请输入用户名

测试debug: username_exists is True

debug: I run this command

您的详细信息已经存储在这里了吗?y/n

import hashlib
import time
while True:
have_account = input("do you have your details stored here already? y/n    ")
while have_account not in ("y", "n"):
print("please type either y or n")
have_account = input("y/n    ")
if have_account == "y":
username_exists = False
while username_exists is False:
username_login = input("Please enter a username    ")
with open("users.txt", "r") as f:
readfile = f.read()
if username_login in readfile:
username_exists = True
print("debug: username_exists is " + str(username_exists))
else:
username_exists = False
print("That user does not exist")
print("debug: I ran this command")
with open("users.txt", "r") as f:
readfile = f.read()
user_loc = readfile.index(username_login)
user_len = len(username_login)
f.seek(user_loc + user_len + 3)
pass_hash = f.read(64)
password_login_hashed = None
pass_matches = None
while pass_matches is False:
password_login = input("Please enter your password    ")
password_login_hashed = hashlib.sha256(password_login.encode('utf-8')).hexdigest()
password_login = None
if password_login_hashed == pass_hash:
pass_matches = True
print("Congrats! You logged in!")
else:
pass_matches = False
quit_question = input("Incorrect password! Please try again or type "quit" to quit")
if quit_question == "quit":
quit()

pass_matches初始化为None然后检查pass_matches is False它将始终返回False因为这里pass_matches将始终为None

用以下代码修改while语句:

while pass_matches in (False, None)

为什么不在第一个循环开始时读取一次文件呢?如:

import hashlib
import time
while True:
with open("users.txt", "r") as f:
readfile = f.read()
have_account = input("do you have your details stored here already? y/n    ")
while have_account not in ("y", "n"):
print("please type either y or n")
have_account = input("y/n    ")
if have_account == "y":
username_exists = False
while username_exists is False:
username_login = input("Please enter a username    ")
if username_login in readfile:
username_exists = True
print("debug: username_exists is " + str(username_exists))
else:
username_exists = False
print("That user does not exist")
print("debug: I ran this command")

我运行下面的代码并检查硬编码值Test-它正在打印"Pram"在最后一个语句之后,看到下面的图像代码,我运行并为我工作输入图像描述在这里

如果您还有什么疑问,请告诉我。

最新更新