为什么下面的代码给予了一个无限循环,并且没有正确检查是否有一个相同的元素作为用户名输入在文件中使用的csv模块在Python中,当我试图签入输入现有用户的用户名和密码它打印'这个用户名是采取'和'成功注册'在一起.我想写一个函数,允许用户通过输入用户名和密码注册,并将值存储在CSV文件中。函数应检查用户名是否已被使用,密码是否仅包含数字。如果注册成功,函数应打印成功消息。如果用户名已被使用或密码无效,函数应打印错误消息,并允许用户重试。
def register():
try:
with open('users.csv','x') as f:
pass
except:
pass
finally:
with open('users.csv','r+',newline='') as f:
while True:
lines = csv.reader(f)
username=input('type your username: ')
password=input('type your password (must contain only numbers): ')
for i in lines:
if username not in i[0]:
if password.isdigit():
writer = csv.writer(f)
writer.writerows([[username,password]])
print('successful registration')
break
else:
print('password must contain only numbers')
else:
print('this username is already taken')
这是csv文件中的元素:
user,0809
user2,5677
3条答案
按热度按时间fivyi3re1#
假设这是整个函数,您可以使用
return
代替break
:但是对于用户名来说,这样做是不正确的。下面是我的建议:
r6l8ljro2#
break
从第一个for
输出,但仍在while
循环中。hpxqektj3#
无限循环,因为您使用了
您可以初始化变量
第一个月
在while循环之上,当before
break
执行它的工作时,您可以goodtogo=True
然后在for循环后,检查
再一次。