liveBook · Manning

Get_guess

As explained in Learn AI-Assisted Python Programming, Second Edition

get_guess is a book-specific Python function that obtains a player's guess containing a required number of distinct digits.

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

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains the parameter, return string, prompt, and validation loop, but stops short of adding user-facing error messages.
Examples
Demonstrates repeated prompts for Bulls and Cows guesses and proposes clearer validation messages as an exercise.
What it assumes
Assumes basic Python functions, strings, conditions, loops, and sets while explaining string-based digit handling.
What you can do after
Build it from scratch as a reusable Python input function that rejects invalid guesses before gameplay continues.
How it connects
Connects functions, parameters, strings, input validation, while loops, sets, and top-down design.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.