Home > Blockchain >  Why does the loop skip the if statement
Why does the loop skip the if statement

Time:11-15

I was trying to make a password system but whenever I run my code it ignores the if statement, Does anyone know why this is happening and how to fix it?

key = 1057

while True:

    inputKey = input("Enter your password ")

    if inputKey == key:
        print("Welcome Back!")
        break

    else:
        print("Incorrect password, Please try again.")

CodePudding user response:

You compared the integer 1057 to a string. Put it into quotes and it will work or you can also do inputKey = int(input("Enter your password "))

key = "1057"

while True:

    inputKey = input("Enter your password ")

    if inputKey == key:
        print("Access granted")
        break
    else:
        print("Incorrect password, Please try again.")

Output: Access granted

CodePudding user response:

Convert your input to int(input("Enter your password ")). Because, in python, input is taken as string by default. So "1057" is not equal to 1057. That's the reason your if condition is getting skipped. Your corrected code:

key = 1057

while True:
    try:
        inputKey =int(input("Enter your password "))
        if inputKey == key:
            print("Welcome Back!")
            break
        else:
            print("Incorrect password, Please try again")
    except ValueError:
        print("Password must be integer")
  • Related