Cows and Bulls Problem – Python Solution

lets us program a game to play the “cows and bulls” with the user. The game works like this:

Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wrong place is a “bull.” Every time the user makes a guess, tell them how many “cows” and “bulls” they have.

Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout the game and tell the user at the end.

Say the number generated by the computer is 1038. An example of interaction could look like this:

  Welcome to the Cows and Bulls Game! 
  Enter a number: 
  >>> 1234
  2 cows, 0 bulls
  >>> 1256
  1 cow, 1 bull
  ...

Until the user guesses the number.

Here is the Python program

#   Program of cows and bulls number guessing game
#   program by          : rakesh kumar
#   website             : https://cbsetoday.com


import random as r
cows = 0
bulls = 0
n = str(r.randint(1000, 9999))
ans = input('Enter Your guess :')

for i in range(len(n)):
    if (n[i] == ans[i]):
        cows += 1
    elif ans[i] in n:
        bulls += 1

print("Actual No was : ", n)
print('Cows :', cows, " Bulls :", bulls)

Well, this is my version of this problem.

 

Related Posts

If you like CBSEToaday and would like to contribute, you can also write an article using submit article or mail your article to contribute@cbsetoday.com See your article appearing on the cbsetoday.com main page and help other students/teachers.