Home > OS >  Login system with number of tries on python how can i simplify it?
Login system with number of tries on python how can i simplify it?

Time:11-10

I am a Beginner in Python and i made this login system with number of tries. I think it can be simplified Can anyone help?

a=int(input("Enter the Password: "))
i=5
if a==1234:
        print("ACCESS GRANTED")
        
while not a==1234:
    print(f"INVALID PASSWORD ( {i} times left)")
    a=int(input("Enter the Password: "))
    i-=1
    if a==1234:
        print("ACCESS GRANTED")
    if i==0:
        print("Console has been locked")
        break

I tried it to change the number of print("ACCESS GRANTED") but I dont get how to without doing it wrong.

CodePudding user response:

Maybe something like this:

a = 0
i = 6
while not a==1234:
    a=int(input("Enter the Password: "))
    i-=1
    if a==1234:
        print("ACCESS GRANTED")
    elif i==0:
        print("Console has been locked")
        break
    else:
        print(f"INVALID PASSWORD ( {i} times left)")

CodePudding user response:

possibility = 5
while True:
    attempt=int(input("Enter the Password: "))
    if attempt==1234:
        print("ACCESS GRANTED")
        break
    elif possibility > 0:
        possibility -= 1
        print(f"INVALID PASSWORD ( {possibility} times left)")
    else:
        print("Console has been locked")
        break

Use more informative names

CodePudding user response:

You can use for loops instead of a while loop.

Here is my answer:

max_tries = 5
correct_password = "1234"

for i in range(1, max_tries   1):
    password = input("Enter the password: ")
    if password == correct_password:
        print("Access granted!")
        break
    else:
        print(f"Wrong password! You have {max_tries - i} more tries.")
        if i == max_tries:
            print("Console has been locked")

print("Closing program...")

CodePudding user response:

a=int(input("Enter the Password: "))
i=5    
while True:
    if a==1234:
        print("ACCESS GRANTED")
        break
    elif i==0:
        print("Console has been locked")
        break
    else:
        print(f"INVALID PASSWORD ( {i} times left)")
        a=int(input("Enter the Password: "))
        i=i-1
  • Related