我正在做一个牛和牛游戏,你应该猜一个四位数的数字。当我运行程序时,计算机一直说0头牛,0头牛,而我不知道为什么或如何解决它
import random
print("Welcome to the cows and bulls game!")
number = [random.randint(0,9), random.randint(0,9), random.randint(0,9), random.randint(0,9)] counter = 0 teller1 = 0 teller2 = 0
while True :
guess = input("Enter a four digit number:")
bulls= 0
cows = 0
if cows == 4:
print("Congratulations, you have won the game. you only used:", counter, " attempts")
break
for i in range(4):
if guess[teller1] == number[teller2]:
cows = cows + 1
teller1 = teller1 + 1
teller2 = teller2 + 1
teller1 = 0
for i in range(4):
teller2 = teller1 - 1
for i in range(3):
if guess[teller1] == number[teller2]:
bulls = bulls + 1
teller1 = teller1 + 1
print(cows," cows, ", bulls," bulls")
counter = counter + 1
没有错误消息,但它一直说0头牛,0头牛。
答案 0 :(得分:2)
您的number
变量是int
的列表,但是您的guess
变量是字符串。因此,当您进行if guess[teller1] == number[teller2]
时,就是将整数与字符串进行比较,而这总是错误的。
您可以通过将字符串转换为整数列表来解决此问题:
guess = [int(num) for num in input("Enter a four digit number:")]
请注意,适当的解决方案还会验证用户提供的输入(如果他们输入“ 12345”,“ hello world”?什么都不会发生?)。