0

I'm new to Python and programming in general so I decided to set myself a bit of a challenge to code a password storage system. It basically writes and reads from a text file with passwords stored inside it. At the end, the user needs to put in the password that matches in the text file. All of it works but I can't seem to get the while loop to end after the correct password has been entered. It just keeps asking to enter the password even if the user got it correct. Does anyone know how to correct this? I'm sure it's quite a small mistake that I overlooked but I've been stuck on this for the past few hours now.

Many thanks in advance :)

Luke

my_list = ["yes", "no"]

while True:
    password_question: str = input('Do you want to create a new password?, please type yes or no ')
    word = password_question
    if word.lower() in my_list:
        break
    else:
        print("Sorry, try again")

if password_question == my_list[0]:
    print("Great, let's get started!")

    text_write = open("passwords.txt", "a")
    lst = []
    new_password = input("Please enter a new password -> ")
    lst.append(new_password)

    text_write.write(new_password + '\n')
    text_write.close()
    print("Okay, your new password is " + new_password)

while True:
    password: str = input("Please enter your password -> ")
    found: bool = False
    with open("passwords.txt", "r") as text_read:
        for line in text_read:
            if line.rstrip() == password:
                print("Great, you are logged in!")
                found = True
                break
            if not found:
                print('Incorrect password, try again')

I tried to move the while loop around as I thought it was in the wrong place initially but then that messed everything else up. I also tried moving the "break" statement to see if it works elsewhere but that didn't work either.

  • which loop does this `break` breaks out of, do you think? – njzk2 Nov 28 '22 at 10:21
  • break in a nested loop only breaks the inner loop. Here is a good page explaining how to use break correctly with nested loops: https://eecs.oregonstate.edu/ecampus-video/CS161/template/chapter_5/nested.html – Niko Nov 28 '22 at 10:26

1 Answers1

1

while True: is creating an "infinite" loop, which you probably tried to break with the break statement, but it breaks an internal for loop only.

I think a good solution is to put "not found" into the while condition, so it will run the input sequence only if found is False

found: bool = False
while not found:
    password: str = input("Please enter your password -> ")
    with open("passwords.txt", "r") as text_read:
        for line in text_read:
            if line.rstrip() == password:
                print("Great, you are logged in!")
                found = True
                break
            if not found:
                print('Incorrect password, try again')
print('here we go')
svfat
  • 3,273
  • 1
  • 15
  • 34