I'm having trouble with a while loop!
What I'm trying to do is to make a simple account creation system. I want the user to enter a username, if the username already exists, It should let me try again.
But even if the username exists, it continues the function, and asks me for a password, and writes the username and password to the file.
here's the code:
def create_user():
passw = open('passwords.txt', 'r+')
x = 1
passwr = passw.readlines()
print "What's your username?"
while x == 1:
user = raw_input(">> ")
for l in passwr:
a = l.split()
if user.lower() not in a[0]:
x = 0
else:
print 'Sorry, that\'s already in use!'
print "What's your pw?"
pw = raw_input(">> ")
passw.seek(0, 2)
passw.write(user + ' ' + pw + '\n')
The file is formated like this:
Username1 Password
Username2 Password
I've tried to figure out what's wrong for a while now. But can't seem to figure out a solution.
Your validation part can be more simple Try something like this
while x == 1:
user = raw_input(">> ")
usernames = [i.split()[0] for i in passwr]
if user.lower() not in usernames:
x = 0
else:
print 'Sorry, that\'s already in use!'
The output will then be
What's your username?
>> Username1
Sorry, that's already in use!
>> Username2
Sorry, that's already in use!
>> Username3
What's your pw?
>> Password
and the file contents
username1 Password
username2 Password
Username3 Password
The problem is that you set x = 0 if there's any user with a different user name. Imagine there are two existing users, foo and bar. The user enters bar. This happens:
if user.lower() not in a[0]: produces True, because user is "bar" and a[0] is "foo".x is set to 0.a[0] will now be "bar".if user.lower() not in a[0]: produces False, and Sorry, that's already in use! is printed.x has been set to 0.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With