Generate Random Number in Python | Heads and Tails Game

Published March 08, 2021


In this Post we create a python program that will play the “Heads and Tails” game with the user. This example game works like:

  1. Randomly generate a 4-digit number
  2. Take the input from user to guess a 4-digit number
  3. For every digit that the user entered correctly in the correct place, then they get a “Head”
  4. For every digit the user entered correctly in the wrong place then he get  “Tail”
  5. Every time the user makes a guess, will give the user to how many “Heads” and “Tails” he have
  6. Once the user guesses the correct number, the game is over

 

Program for the above steps

import random


def compare_numbers(number, user_guess):
    headtail = [0, 0]  # Heads, then Tails
    for i in range(len(number)):
        if number[i] == user_guess[i]:
            headtail[1] += 1
        else:
            headtail[0] += 1
    return headtail


if __name__ == "__main__":
    playing = True  # gotta play the game
    number = str(random.randint(0, 9999))  # random 4 digit number

    guesses = 0

    print("Let's play a game of HeadsTail!")  # explanation
    print("I will generate a number, and you have to guess the numbers one digit at a time.")
    print("For every number in the wrong place, you get a Tail. For every one in the right place, you get a Heads.")
    print("The game ends when you get 4 Heads!")
    print("Type exit at any prompt to exit.")
    print("\n")
    while playing:
        user_guess = raw_input("Give me your best guess!")
        if user_guess == "exit":
            break
        headstailscount = compare_numbers(number, user_guess)
        guesses += 1

        print("You have " + str(headstailscount[0]) + " Tails, and " + str(headstailscount[1]) + " Heads.")

        if headstailscount[1] == 4:
            playing = False
            print("You win the game after " + str(guesses) + "! The number was " + str(number))
            break  # redundant exit
        else:
            print("Your guess isn't quite right, try again.")

 

 

Output:
 

Let's play a game of HeadsTail!
I will generate a number, and you have to guess the numbers one digit at a time.
For every number in the wrong place, you get a Tail. For every one in the right place, you get a Heads.
The game ends when you get 4 Heads!
Type exit at any prompt to exit.


Give me your best guess!2367
You have 3 Tails, and 1 Heads.
Your guess isn't quite right, try again.
Give me your best guess!2789
You have 2 Tails, and 2 Heads.
Your guess isn't quite right, try again.
Give me your best guess!2738
You have 0 Tails, and 4 Heads.
You win the game after 3! The number was 2738

Process finished with exit code 0

 

Python Heads and Tails Game


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

276 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions