Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

In python 3. Create a game where the player should guess a random number between 1 and…

  1. User

    In python 3. Create a game where the player should guess a random number between 1 and 100. The game should be re-playable, the number of guesses should be counted each run and a high score should be kept and updated each run.

  2. Assistant

    Here's one example implementation:

    import random
    
    # initialize high score to a large number
    high_score = float('inf')
    
    while True:
        # generate a random number between 1 and 100
        answer = random.randint(1, 100)
    
        # initialize number of guesses to 0
        num_guesses = 0
    
        # loop until the player guesses correctly
        while True:
            guess = input('Guess a number between 1 and 100: ')
            num_guesses += 1
    
            # make sure the input is a valid number
            try:
                guess = int(guess)
            except ValueError:
                print('Invalid input, please enter a number')
                continue
    
            # check if the guess is correct
            if guess == answer:
                print('Correct!')
                break
            elif guess < answer:
                print('Too low, try again')
            else:
                print('Too high, try again')
    
        # update high score if needed
        if num_guesses < high_score:
            high_score = num_guesses
            print(f'New high score: {high_score} guesses!')
    
        # ask if the player wants to play again
        again = input('Play again? (yes/no): ').lower()
        if again != 'yes':
            break
    
    print('Thanks for playing!')
    

    In this implementation, we first set the high score to a large number (infinity) so that any valid high score will be less than it. Then we enter an infinite loop that generates a new random number on each iteration, initializes the number of guesses to 0, and loops until the player guesses correctly. We keep track of the number of guesses, update the high score if needed, and ask if the player wants to play again. The loop continues until the player enters anything other than "yes". Finally, we print a message thanking the player for playing.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.