Functions and Classes in Python

Solutions

In [14]:
class GuessGame:
    def __init__(self, secret):
        self._secret = secret
        self._nguesses = 0
    def guess(self, value):
        if (value == self._secret):
            print("Well done - you have guessed my secret")
        else:
            self._nguesses += 1
            print("Try again...")
    def nGuesses(self):
        return self._nguesses
In [15]:
g = GuessGame("cat")
In [16]:
g.nGuesses() == 0
Out[16]:
True
In [17]:
g.guess("dog")
Try again...
In [18]:
g.nGuesses() == 1
Out[18]:
True
In [19]:
g.guess("horse")
Try again...
In [20]:
g.nGuesses() == 2
Out[20]:
True
In [21]:
g.guess("cat")
Well done - you have guessed my secret
In [22]:
g.nGuesses() == 2
Out[22]:
True

2

In [23]:
class GuessGame:
    def __init__(self, secret, max_guesses=5):
        self._secret = secret
        self._nguesses = 0
        self._max_guesses = max_guesses
    def guess(self, value):
        if (self.nGuesses() >= self.maxGuesses()):
            print("Sorry, you have run out of guesses")
        elif (value == self._secret):
            print("Well done - you have guessed my secret")
        else:
            self._nguesses += 1
            print("Try again...")
    def nGuesses(self):
        return self._nguesses
    def maxGuesses(self):
        return self._max_guesses
In [24]:
g = GuessGame("fish", 3)
In [25]:
g.maxGuesses() == 3
Out[25]:
True
In [26]:
g.guess("cat")
Try again...
In [27]:
g.guess("dog")
Try again...
In [28]:
g.guess("horse")
Try again...
In [29]:
g.guess("gerbil")
Sorry, you have run out of guesses