Zander Møysal
Zander Møysal

Reputation: 55

Having trouble with a while loop, it breaks, even though it shouldn't

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.

Upvotes: 2

Views: 110

Answers (3)

Kasravnd
Kasravnd

Reputation: 107287

You need to check with == not in ,and so you dont need to extra assignment a = l.split() ,change your if statement to following :

if user.lower() == l.split()[0]

as this work for check one id , if you need to check for all ids you can grab all of them in a list and check :

while x == 1:
    user = raw_input(">> ")
    user-list=[line.split()[0] for line in passwr]  
    if user.lower() not in user-list:
            x = 0

Upvotes: 3

Aran-Fey
Aran-Fey

Reputation: 43126

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:

  1. if user.lower() not in a[0]: produces True, because user is "bar" and a[0] is "foo".
  2. x is set to 0.
  3. the loop continues with the next line in the file, a[0] will now be "bar".
  4. if user.lower() not in a[0]: produces False, and Sorry, that's already in use! is printed.
  5. the loop quits because x has been set to 0.

Upvotes: 3

Bhargav Rao
Bhargav Rao

Reputation: 52071

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

Upvotes: 3

Related Questions