Skip to content

script_8.py - While Loop Password Validator

Code

Python
#!/usr/bin/env python3
"""While loop password validator"""

password = ""

while password != "secret":
    password = input("Enter password: ")
    if password != "secret":
        print("Incorrect! Try again.")

print("Access granted!")

Explanation

Line 4: password = "" - Initialize variable before while loop - Empty string literal "" - String type - Must exist before loop condition is checked

Line 6: while password != "secret": - while keyword creates a loop that runs while condition is True - != is "not equal to" operator - Condition checked before each iteration - Loop continues as long as password is not "secret" - No automatic counter like for - must manually change condition - Could run 0 times (if password="secret" initially) or infinite times (if condition never becomes False)

Line 7: password = input("Enter password: ") - Indented under while = loop body - Reassigns password variable with user input - Must happen inside loop to change the condition - Without this, loop would be infinite (password never changes)

Line 8: if password != "secret": - Nested if inside while loop - Checks same condition as while - Only shows error if password is still wrong

Line 11: print("Access granted!") - Not indented under while - Runs after loop exits (when password == "secret")