Hello, I'm trying to make a login code for my game algorithm but it isn't working as I want it to so can someone help to stop my loops from repeating when I don't want it to please?

def login(): 
  username = input("Enter username: ")
  password = input("Enter password: ")
  file = open("Account.txt","r")
  account = file.readlines()

access = False
while access == False:
for user in account:
if username in user and password in user:
login = user.strip("\n")
login = login.split(",")
if username == login[0] and password == login[1]:
access = True
print("Welcome", username)
else:
print("Username or Password is incorrect, try again.")

else:
print("Username or Password is incorrect, try again.")
username = input("Enter username: ")
password = input("Enter password: ")

if access == True:
break

all my indents are correct i just had to remove them from this (im new i don't know how to use this)

Unfortunately, there's really no way to read Python code when the indentation has been lost. I'll try to puzzle out your intentions here, but it isn't straightforward. As it is, I can't even tell if this is all supposed to be one function, or the function followed by some top-level code. As best as I can determine, you intended the code to read like so:

def login(): 
    username = input("Enter username: ")
    password = input("Enter password: ")
    file = open("Account.txt","r")
    account = file.readlines()

    access = False
    while access == False:
        for user in account:
            if username in user and password in user:
                login = user.strip("\n")
                login = login.split(",")
                if username == login[0] and password == login[1]:
                    access = True
                    print("Welcome", username)
                else:
                    print("Username or Password is incorrect, try again.")

            else:
                print("Username or Password is incorrect, try again.")
                username = input("Enter username: ")
                password = input("Enter password: ")

        if access == True:
            break

This forum uses Markdown, so in order to preserve the formatting of your code, you would indent teach line by four spaces. The Code Block button (</>) will open a separate sub-window to make this easier to paste the code into the message while preserving formatting.

As an aside, you generally don't want to have the text of a password to echo to the console, to prevent people from shoulder-surfing. There is a standard password library, getpass as part of the Python standard library, for precisely this purpose.

On a related note, you seem to be using a cleartext file for the username and password information, which is, shall we say, unwise. Even for a simple game, you want to hash the passwords to make sure that, should anyone reuse a password that they already used on other accounts, no one could simply open up the file and get all the passwords. I would recommend using a simple hash library such as bcrypt for this purpose.

I spent far too much time on this, but I worked out a usable password sign-in process that you may want to look into. It uses a third party library, passlib, which can be installed using pip install passlib.

import getpass
from passlib.context import CryptContext

# some of the code taken from the web page
# https://blog.teclado.com/learn-python-encrypting-passwords-python-flask-and-passlib/

def init_pwd_context():
    return CryptContext(
        schemes=["pbkdf2_sha256"],
        default="pbkdf2_sha256",
        pbkdf2_sha256__default_rounds=30000
    )

def encrypt_password(pwd_context, password):
    return pwd_context.hash(password)


def check_encrypted_password(pwd_context, password, hashed):
    return pwd_context.verify(password, hashed)


def add_account(fname, pwd_context, username, password):
    """ Adds an account to a file of 'username, password' pairs.
        Simply appends the new information to the end of the file, if a username already
        exists the new one shadows the old information."""
    file = open(fname, "a")
    file.write(f"{username}: {encrypt_password(pwd_context, password)}\n")


def collect_accounts(fname):
    """ Reads a file with 'username,password' pairs and returns a dictionary with the pairs."""

    accounts = dict()
    try:
        file = open(fname,"r")
    except FileNotFoundError as e:
        return accounts
    account_strings = file.readlines()
    for acct in account_strings:
        username, password = acct.split(': ')
        accounts[username.strip()] = password.strip()
    return accounts


def get_user_pwd(): 
    """ Reads in a username and password."""
    username = input("Username: ")
    password = getpass.getpass()
    return username.strip(), password.strip()


def login(accounts, pwd_context):
    """ Log user in, returning the user name."""
    while True:
        username, password = get_user_pwd()

        if (username in accounts):
            if check_encrypted_password(pwd_context, password, accounts[username]):
                return username
        print("Username or password incorrect.")



if __name__ == "__main__":
    pwd_context = init_pwd_context()
    accounts = collect_accounts("Accounts.txt")
    a_or_l = input("A)dd or L)ogin? ").upper()
    if a_or_l == 'A':
        username, password = get_user_pwd()
        add_account("Accounts.txt", pwd_context, username, password)
    elif a_or_l == 'L':
        user = login(accounts, pwd_context)
        print(f"User {user} is logged in.")
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.