Start learning free

LESSON 631 OF 673 · OBJECT-ORIENTED PROGRAMMING

Secret PIN in Python: A Class with Private Fields

Practice Read the full explanation

You build the class Phone. It keeps a secret PIN and counts the wrong tries.

Both values are private. Other code can't read or change them. It can only call the methods below.

  • Phone(pin) makes a phone with that PIN and no wrong tries.
  • isLocked() returns True after 3 wrong tries. Before that, it returns False.
  • unlock(attempt) returns True when attempt is the PIN.
  • Any other attempt returns False. It counts as one more wrong try.
  • A locked phone stays locked for good. Then unlock always returns False, even with the right PIN.
  • The right PIN doesn't reset the count of wrong tries.

Make both fields private the way the Access Modifiers lesson does in Python. In Python the names start with an underscore. In JavaScript they start with #.

The starter code spells the methods your language's way. Python has is_locked. C# has Unlock and IsLocked.

Each test case makes one phone with the given PIN. Then it calls the methods in order. The output line shows each answer as True or False.

 

Example 1:

Input:
    pin = "1234"
    unlock("1111")
    unlock("1234")
    isLocked()
Output: False True False
Explanation: "1111" is wrong. That is 1 wrong try.
"1234" is the PIN, so the phone opens.
1 wrong try doesn't lock the phone.

Example 2:

Input:
    pin = "0042"
    unlock("4200")
    unlock("0000")
    unlock("0041")
    isLocked()
    unlock("0042")
Output: False False False True False
Explanation: Three wrong tries lock the phone.
After that, even the right PIN "0042" gets False.

Example 3:

Input:
    pin = "7777"
    unlock("1234")
    unlock("7777")
    unlock("0000")
    unlock("7777")
    unlock("9999")
    isLocked()
Output: False True False True False True
Explanation: The right PIN works twice.
It doesn't reset the count.
"9999" is the third wrong try, so the phone locks.

 

Constraints:

  • Each PIN has exactly 4 digits.
  • Each attempt has exactly 4 digits too.
  • A PIN can start with 0, like "0042".
  • 1 to 1000 calls per phone.
STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · OBJECT-ORIENTED PROGRAMMING

    Secret Pin in Python, explained

    Problem overview

    You write a class Phone that guards a PIN. It stores the PIN and counts wrong tries, and the outside world may only call three things: the constructor Phone(pin), is_locked() and unlock(attempt).

    The rules, in the order they matter:

    • After 3 wrong tries the phone is locked for good.
    • On a locked phone, unlock returns False for every attempt, even the right PIN.
    • On an unlocked phone, the right PIN returns True and changes nothing.
    • Any other attempt returns False and counts as one more wrong try.

    Take the PIN "0042" and the attempts "4200", "0000", "0041". All three are wrong, so the third one locks the phone. The next call, unlock("0042"), uses the right PIN but still returns False. The tests print False False False True False for the calls unlock, unlock, unlock, is_locked, unlock.

    Approach

    The class needs two pieces of state: the PIN and a counter of wrong tries. Python has no real private fields, so the convention is a leading underscore: self._pin and self._wrong_tries tell other programmers "don't touch this, use the methods". The language doesn't enforce it, but code that follows the convention keeps the rules in one place.

    The only design choice is where to write the "3 wrong tries" rule. Put it in is_locked and let unlock call that method. If the number 3 ever changes, there is one line to edit.

    Step by step

    1. Store the PIN in self._pin inside __init__.
    2. Start the counter: a new phone has self._wrong_tries = 0.
    3. Write is_locked as a single comparison: the counter is at least 3. A comparison already is True or False, so no if is needed.
    4. Refuse a locked phone first. At the top of unlock, ask self.is_locked() and return False. This check must come before the PIN comparison, or a locked phone would accept the right PIN.
    5. Accept the right PIN. If attempt == self._pin, return True and leave the counter alone.
    6. Count anything else. Add 1 to self._wrong_tries and return False.

    The solution in Python

    class Phone:
        def __init__(self, pin):
            self._pin = pin
            self._wrong_tries = 0
    
        def is_locked(self):
            return self._wrong_tries >= 3
    
        def unlock(self, attempt):
            if self.is_locked():
                return False
            if attempt == self._pin:
                return True
            self._wrong_tries += 1
            return False
    

    Using it like the tests do:

    phone = Phone("7777")
    print(phone.unlock("1234"), phone.unlock("7777"), phone.unlock("0000"),
          phone.unlock("7777"), phone.unlock("9999"), phone.is_locked())
    
    False True False True False True
    

    The right PIN worked twice because it never touches the counter. The wrong tries "1234", "0000" and "9999" are the three that lock the phone.

    Python details

    • The PIN is a string, not a number. Strings keep leading zeros: "0042" is a four-digit PIN, while int("0042") is 42. Comparing "0042" with 42 gives False, because a string never equals an integer.
    • self._wrong_tries += 1 is shorthand for self._wrong_tries = self._wrong_tries + 1.
    • The underscore is only a convention. Code outside can still write phone._wrong_tries; the convention says it shouldn't.

    Edge cases and common mistakes

    • Checking the PIN before the lock. Then a locked phone opens with the right PIN. Example 2 catches this.
    • Resetting the counter on success. With self._wrong_tries = 0 in the success branch, the pattern wrong, right, wrong, right, wrong never locks the phone: for PIN "7777" the attempts "1", "7777", "2", "7777", "3" leave is_locked() at False, while the lesson's rules lock it. Example 3 catches this.
    • Counting tries on a locked phone. Harmless to the answers, but the early return False makes it unnecessary.
    • Locking at 2 or at 4. Off-by-one in >= 3. The phone must be unlocked after 2 wrong tries and locked after the third.
    • Leaving the fields public. Naming them pin and wrong_tries works in the tests, but it invites other code to read the PIN or reset the count.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free