or

ask mattrab Visit www.askmattrab.com for more academic resources.

Cows and Bulls (Python)

Hqdefault

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 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.



import random as rand
r=rand.randint(1000,10000)
cows=0;c=0;bulls=0
print(f''' CONGRATULATIONS!!!
k=str(r) def win():
YOU WON!!!
You have guessed {c} time(s).'''
print("Please enter 4 digit number.")
while True: n = str(input()) if len(n)<4:
if n[x]==k[x]:
else: for x in range(len(n)):
bulls+=1
cows+=1 else: c+=1
else:
if cows==4: win() break
bulls=0;cows=0
print("You have {} cows and {} bulls.".format(cows,bulls))