【发布时间】:2019-12-10 19:37:48
【问题描述】:
我是 Python 新手,尝试使用我还不完全理解的方法(特别是自定义异常部分)。
在下面的代码 sn-p 中,我希望用户输入用户名(作为注册过程的一部分)。然后我想验证这个用户名的两件事。首先只是格式(重新)然后我想通过引用包含用户名和密码的文件来检查用户名是否已经被使用。
首先,我知道我这样做的整个方式可能是错误的。我也很好奇为什么这种方法不起作用。当前发生的情况是它一次可以正常工作,即如果我使用已经使用的用户名,它会遇到我的自定义异常并返回并要求我再次输入用户名。但从那时起,验证就不起作用了——我可以再次输入完全相同的用户名,它就通过了。
def register():
uf = open("user.txt","r+")
un = re.compile(r"[a-zA-Z]{3,10}$") # Only allow a-z, 3-10 length, and check full string.
up = re.compile(r".{3,10}$") # Allow a-z, numbers and some special chars.
class ExistException(Exception):
pass
print("Register new user:\n")
# Get and validate username:
while True:
try:
new_user = input("Please enter a username:\n-->")
assert un.match(new_user)
for line in uf:
existing_un = line.strip().split(", ")[0] # Stores username in variable
# Check variable against input from user:
if new_user == existing_un:
raise ExistException()
except AssertionError:
print("That is not a valid username. \nOnly alpha characters are allowed (a - z)"
", and username must be between 3 and 10 characters.")
except ExistException:
print("That username already exists")
else:
break
【问题讨论】:
标签: python-3.x exception