简体   繁体   中英

Checking to see if username already exists

Starting at "#If user does not have account:" the code is printing the output multiple times. I just want it to print the output (either the username is taken or they can continue) once. Then, I want the password to be typed twice and compared to make sure that they match. Can you help me fix this issue?

import colorama
colorama.init()

print_in_green = "\x1b[32m"
print_in_red = "\x1b[31m"
print_in_blue = "\x1b[36m"
print_in_pink = "\x1b[35m"
print_default = "\x1b[0m"

#STAGE 1: Opening the files and grabbing data
users_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\usernames.txt"
passwords_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\passwords.txt"
scoreslist_path = "c:\\Users\\Anna Hamelin\\Documents\\Python Scripts\\SourceCode\\Project2\\scores.txt"


def get_file_contents(file_path):
    return [line.strip() for line in open(file_path)]

scoreslist = get_file_contents(scoreslist_path)

def add_file_contents(file_path, contents):
    with open(file_path, "a") as file:
        file.write(contents)

def login_user(new_account=False):
    usernameslist = get_file_contents(users_path)
    passwordslist = get_file_contents(passwords_path)

    if new_account:
        response = 'y'
    else:
        response = input("-"*50 + "\nWelcome! Do you have an account (y/n)? ")
        print("-"*50)

    #If user has an account:
    if response == "y":
            goodlogin = False
            username = input("Please enter your username: ")
            password = input("Please enter your password: ")
            for id in range(len(usernameslist)):
                if username == usernameslist[id] and password == passwordslist[id]:
                    goodlogin = True

            if goodlogin:
                print(print_in_green + "Access granted!" + print_default)
                #Ask if user would like to view leaderboard
                leaderboard = input("Would you like to view the leaderboard (y/n)? ")

                #If thet want to see scores:
                if leaderboard == "y":
                    print("-"*50 + "\n" + print_in_blue + "Here is the leaderboard!\n" + print_default + "-"*50)
                    for c in range(0, len(scoreslist)-1):
                        max = scoreslist[c]
                        index_of_max = c
                        for i in range (c+1, len(scoreslist)):
                            if (scoreslist[i] > max):
                                max = scoreslist[i]
                                index_of_max = i
                        aux = scoreslist[c]
                        scoreslist[c] = max
                        scoreslist[index_of_max] = aux
                        #print(scoreslist)
                    print(*scoreslist, sep = "\n")
                    print("-"*50)
                    #If they don't want to see scores:
                else:
                    print("OK. Thanks for loging in!")


            else:
                print(print_in_red + "Incorrect Login credentials, please try again by restarting." + print_default)

    #If user does not have account:
    else:
        goodlogin2 = False
        newusername = input("What is your new username? ")
        for id in range(len(usernameslist)):
            if newusername != usernameslist[id]:
                goodlogin2 = True
                print("Ok, please continue!")
            else:
                print("This username is already taken. Please try another.")

        newpassword = input("What is your new password? ")
        newpasswordagain = input("Please enter your new password again.")
        if newpassword == newpasswordagain:
            print("Please follow the instructions to log in with your new credentials.")
            add_file_contents(users_path, '\n' + newusername)
            add_file_contents(passwords_path, '\n' + newpassword)
            login_user(new_account=True)
        else:
            print("Your passwords do not match. Please try again.")

login_user()

The problem with your code lies in the fact that you are printing the message "Ok, please continue!" within your for loop.

...
for id in range(len(usernameslist)):
        if newusername != usernameslist[id]:
            goodlogin2 = True
            print("Ok, please continue!")
        else:
            print("This username is already taken. Please try another.")
...

What happens is that every time your usernameslist[id] is checked against the 'newusername' variable, the print statement 'print("Ok, please continue!")' is run, causing the message to be displayed multiple times.

What you can do to fix this issue is to move the print statement out of the for loop, so that, assuming that a new username does not match any username in the usernameslist, the message "Ok, please continue!" will be displayed once to the user before they are prompted to input their password twice.

Here's what should work for you:

...
for id in range(len(usernameslist)):
        if newusername != usernameslist[id]:
            goodlogin2 = True
        else:
            print("This username is already taken. Please try another.")

if goodlogin2 = True:
    print("Ok, please continue!")

    newpassword = input("What is your new password? ")
    newpasswordagain = input("Please enter your new password again.")
    ...

It looks like you're iterating over your whole list of usernames and printing out a success or error message with each iteration. Try this instead:

# If user does not have account:
else:
    goodlogin2 = False
    newusername = input("What is your new username? ")
    if newusername in usernameslist:
        print("This username is already taken. Please try another.")
    else:
        goodlogin2 = True
        print("Ok, please continue!")
    # for id in range(len(usernameslist)):
    #     if newusername != usernameslist[id]:
    #         goodlogin2 = True
    #         print("Ok, please continue!")
    #     else:
    #         print("This username is already taken. Please try another.")

    newpassword = input("What is your new password? ")
    newpasswordagain = input("Please enter your new password again.")
    if newpassword == newpasswordagain:
        print("Please follow the instructions to log in with your new credentials.")
        add_file_contents(users_path, '\n' + newusername)
        add_file_contents(passwords_path, '\n' + newpassword)
        login_user(new_account=True)
    else:
        print("Your passwords do not match. Please try again.")

This produces the following output for a user with no previous account who enters a name which has not been used:

--------------------------------------------------
Welcome! Do you have an account (y/n)? n
--------------------------------------------------
What is your new username? not_taken2
Ok, please continue!
What is your new password? pwd2
Please enter your new password again.pwd2
Please follow the instructions to log in with your new credentials.
Please enter your username: 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM