get_guess is a Python function for obtaining a valid Bulls and Cows guess. It repeatedly asks the player for input until the guess has the required length, contains only digits, and has no repeated digits. section 10.3.4 section 10.3.2
The function separates input collection from the rules that determine validity:
- Accept a length parameter so different game sizes can use the same function. section 10.3.3
- Prompt with input('Enter a guess: '). section 10.3.4
- Continue prompting while the length, digit-only, or distinctness check fails. section 10.3.4
- Return the accepted guess as a string for comparison with the secret code. section 10.3.3
Validation behavior
For a four-digit game, get_guess rejects entries with the wrong length, nondigit characters, or repeated digits. It accepts a string such as 0123 and returns it to play. section 10.3.4 section 10.3.4
Listing 10.3 Function get_guess for user input
def get_guess(length):
'''
length is an integer.
Keep asking the player to enter a string where each character
is a digit from 0 to 9, until they enter a valid guess.
A valid guess has the given length and has no repeated digits.
'''
guess = input('Enter a guess: ') #1
while len(guess) != length or not guess.isdigit()\ #2
or len(set(guess)) != length:
guess = input('Enter a guess: ') #3
return guess #4
The complete listing shows the prompt, validation condition, repeated input, and returned guess. section 10.3.4
