I’m very new to Python. I want to write a code for the “Bulls and Cows” game, using recursion. I have some code, but it doesn’t work. Would be grateful for any hint!
import random
progNum=str(random.randint(1000,9999))
print("Guess the number. It contains 4 digits.")
userNum=list(input("Enter your number: "))
l1=progNum
l2=userNum
def check(bulls,cows):
if cows==4 and bulls==4:
return ('right number')
else:
bulls=0
cows=0
if l1[0]==l2[0]:
cows=cows+1
print('Cows{}'.format(cows))
if l2[0] in l1:
bulls=bulls+1
print('Bulls{}'.format(bulls))
if l1[1]==l2[1]:
cows=cows+1
print('Cows{}'.format(cows))
if l2[1] in l1:
bulls=bulls+1
print('Bulls{}'.format(bulls))
if l1[2]==l2[2]:
cows=cows+1
print('Cows{}'.format(cows))
if l2[2] in l1:
bulls=bulls+1
print('Bulls{}'.format(bulls))
if l1[3]==l2[3]:
cows=cows+1
print('Cows{}'.format(cows))
if l2[3] in l1:
bulls=bulls+1
print('Bulls{}'.format(bulls))
check(bulls,cows)
I made a base condition for the game termination as
if cows==4 and bulls==4:return (‘right number’), but it seems that without without specifying the number of attempts, it continues until a number is guessed. I think if the base condition could be the number of attempts, like cows=cows+(x), where x the number of attempts.
apprentice is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.