Search code examples
pythonloopswhile-loopinfinite-loop

infinite while loop in last lines of code


Could anyone please assist me with the following:

I have a code that reads a username and password then allows users to access a program. I have the first option to register a new user correct. I'm having a problem with an infinite loop problem with my last two lines of code. Id like to run a string stating that if an unregistered username is entered it returns with a string saying that there is no such registered user. The string just keeps running in the loop and is there anything I could do to change this.

username: admin

password: adm1n

my code is as follows:

users = {}  
with open ('user.txt', 'rt')as username:
    for line in username:
        username, password = line.split(",")
        users[username.strip()] = password.strip()  # strip removes leading/trailing whitespaces

uinput = input("Please enter your username:\n")
while uinput not in users:
    print("Username incorrect.")
    uinput = input("Please enter a valid username:/n")

if uinput in users:
            print ("Username correct")

with open('user.txt', 'rt') as password:
    for line in password:
        username, password = line.split(",")
        users[password.strip()] = username.strip()  # strip removes leading/trailing whitespaces

uinput2 = input("Please enter your password:\n")
while uinput2 not in users:
    print("Your username is correct but your password is incorrect.")
    uinput2 = input("Please enter a valid password:\n")

if uinput2 in users:
    password2 = ("Password correct")
    print (password2)

if password2 == ("Password correct"):
       menu = (input("\nPlease select one of the following options:\nr - register user\na - add task\nva - view all tasks\nvm - view my tasks\ne - exit\n"))
    if menu == "r" or menu == "R":
                new_user = (input("Please enter a new user name:\n"))
                new_password = (input("Please enter a new password:\n"))
                with open ('user.txt', 'a')as username:
                        username.write("\n" + new_user + ", " + new_password)
    elif menu == "a" or menu == "A":
                task = input("Please enter the username of the person the task is asigned to.\n")
        while task not in username:
                print("User not registered. Please enter a valid username:\n")

Solution

  • You have a loop at the end that says

    while task not in username:
        print("User not registered. Please enter a valid username:\n")
    

    This is unfinished and will loop endlessly since if task is not in username, printing something will not change that fact so it will just loop and print again. You probably wanted to add something like

    task = input("Please enter a valid username of a person the task is assigned to.\n")